From e740b9582c99064cb734f4db59db061df20d7ca4 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 00:15:22 +0000 Subject: [PATCH 1/6] A mirror fetch keeps what it receives as a pack, so shared checkouts see it Git stores a fetch of fewer than fetch.unpackLimit objects (100 by default) as loose objects. A compiler-tier checkout links only the mirror's packs, so the objects of such a fetch were missing from it. The checkout's own fetch then found the target incomplete and had the mirror send it again; a checkout with no ref yet received the mirror's whole history. Mirror fetches now run with fetch.unpackLimit=1, so every fetch writes a pack that the next tier pass links. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 4 +- server/code/app/index/gitrepo.py | 6 ++- tests/unit/test_code_compiler_checkout.py | 61 +++++++++++++++++++++++ 3 files changed, 68 insertions(+), 3 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 11c30551f5d..52de328954c 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -375,8 +375,8 @@ initializes a missing or empty working tree directory as a Git repository and fe each commit into it from the entry's mirror, so a new leader starts from nothing. With `LOOM_CODE_COMPILER_SHARE_MIRROR_PACKS` on (off by default; turn it on once no older build serves, [upgrades](upgrades.md) step 8), the checkout's packs are hard links -of the mirror's (each marked by a `.keep` file; an operator's own `.keep` stays), -so a tier costs its working tree rather than a second copy of the repository; a +of the mirror's (each marked by a `.keep` file; an operator's own `.keep` stays; +the mirror's fetches always write a pack, never loose objects), so a tier costs its working tree rather than a second copy of the repository; a checkout that already holds its own copy, from an earlier version or an operator, drops it in the checkout gc of the tier's next pass with a new commit (for C/C++, the full-index worker's), which keeps the shared packs. That gc runs only with room for diff --git a/server/code/app/index/gitrepo.py b/server/code/app/index/gitrepo.py index c1ff2989b7e..c47ba7fa328 100644 --- a/server/code/app/index/gitrepo.py +++ b/server/code/app/index/gitrepo.py @@ -303,10 +303,14 @@ async def _network_git( ) -> tuple[int, bytes, bytes]: from server.code.app.index.sandbox import run_job + env = auth_env(token, remote) + # A fetch of fewer than `fetch.unpackLimit` objects (100 by default) is stored as + # loose objects, and a checkout shares only the mirror's packs. + add_git_config(env, "fetch.unpackLimit", "1") try: done = await run_job( argv, - env=auth_env(token, remote), + env=env, timeout_s=timeout_s, writable=[Path(git_dir)], stdin=stdin, diff --git a/tests/unit/test_code_compiler_checkout.py b/tests/unit/test_code_compiler_checkout.py index 1f6fe232537..7971afa1fa6 100644 --- a/tests/unit/test_code_compiler_checkout.py +++ b/tests/unit/test_code_compiler_checkout.py @@ -839,3 +839,64 @@ def test_the_checkout_gc_needs_no_room_for_the_packs_it_keeps(tmp_path: Path) -> keep.unlink() assert mirrors._tree_bytes(str(git_dir)) - kept > pack.stat().st_size + + +def _loose_objects(git_dir: Path) -> int: + counts = dict(line.split(": ") for line in git(git_dir, "count-objects", "-v").splitlines()) + return int(counts["count"]) + + +def _mirror_fetch(tmp_path: Path) -> None: + """The mirror's own fetch of the source's branch, as ingest runs it.""" + from server.code.app.index import gitrepo + + source = tmp_path / "source" + branch = git(source, "branch", "--show-current").strip() + asyncio.run(gitrepo.fetch(str(tmp_path / "repo.git"), str(source), branch)) + + +def test_a_small_mirror_fetch_keeps_its_objects_in_a_pack( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Git unpacks a fetch of fewer than 100 objects into loose files by default, and a + checkout links only the mirror's packs.""" + from server.code.app.index import sandbox + + monkeypatch.setattr(sandbox, "sandbox_available", lambda: False) + bare = _packed_bare(tmp_path) + _commit(tmp_path / "source", "one.py") + + _mirror_fetch(tmp_path) + + assert _loose_objects(bare) == 0 + assert git(bare, "cat-file", "-t", _head(tmp_path / "source")).strip() == "commit" + + +def test_a_checkout_fetch_after_small_and_large_mirror_fetches_transfers_nothing( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A small mirror fetch, then a large one, then a tier pass: the shared packs hold + the target's whole closure, so the checkout's fetch writes nothing of its own.""" + from server.code.app.index import sandbox + + monkeypatch.setattr(sandbox, "sandbox_available", lambda: False) + bare = _packed_bare(tmp_path) + cfg = repo_config(git_dir=str(bare), scip_checkout_dir=str(tmp_path / "co")) + checkout, _bare, _missing = resolve_checkout(cfg, "python") + _fetch_and_check_out(checkout, bare) + source = tmp_path / "source" + _commit(source, "one.py") + _mirror_fetch(tmp_path) + for i in range(150): + (source / f"f{i}.py").write_text(f"print({i})\n") + git(source, "add", ".") + git(source, "commit", "-qm", "many") + _mirror_fetch(tmp_path) + + checkout, _bare, _missing = resolve_checkout(cfg, "python") + target = _fetch_and_check_out(checkout, bare) + + assert _own_objects(checkout) == [] + assert git(checkout, "rev-list", "--objects", "--quiet", target) == "" + assert (checkout / "one.py").read_text() == "print('one.py')\n" + assert (checkout / "f149.py").read_text() == "print(149)\n" From 8e096fdefac60ba1712126287ada20eac179ee29 Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 01:44:10 +0000 Subject: [PATCH 2/6] The mirror's packs stay below git's pack limit, and a local clone writes a pack With every fetch writing a pack, a mirror between two weekly gcs could gather thousands of packs, and a shared checkout's sandboxed job mounts each one. Past 50 packs a gc may rewrite (git's gc.autoPackLimit), gc_if_due now runs a geometric repack, which merges the small packs and leaves the large one. A clone from a local path copied the source's loose objects as they were; it now runs with --no-local, so the mirror starts as a pack. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 10 ++++-- server/code/app/index/bootstrap.py | 5 ++- server/code/app/index/mirrors.py | 40 +++++++++++++++++++----- tests/unit/test_mirror_ready.py | 31 ++++++++++++++++++ tests/unit/test_mirrors.py | 30 ++++++++++++++++++ 5 files changed, 105 insertions(+), 11 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 52de328954c..f4b17004001 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -375,8 +375,9 @@ initializes a missing or empty working tree directory as a Git repository and fe each commit into it from the entry's mirror, so a new leader starts from nothing. With `LOOM_CODE_COMPILER_SHARE_MIRROR_PACKS` on (off by default; turn it on once no older build serves, [upgrades](upgrades.md) step 8), the checkout's packs are hard links -of the mirror's (each marked by a `.keep` file; an operator's own `.keep` stays; -the mirror's fetches always write a pack, never loose objects), so a tier costs its working tree rather than a second copy of the repository; a +of the mirror's (each marked by a `.keep` file; an operator's own `.keep` stays), +so a tier costs its working tree rather than a second copy of the repository; the +mirror's clone and fetches always write packs, never loose objects. A checkout that already holds its own copy, from an earlier version or an operator, drops it in the checkout gc of the tier's next pass with a new commit (for C/C++, the full-index worker's), which keeps the shared packs. That gc runs only with room for @@ -1006,7 +1007,10 @@ Each serving process runs `git gc --no-prune` on its host's mirrors every copy plus `LOOM_CODE_MIRROR_GC_MARGIN_GB`, 5 GB by default; without it the gc waits another interval and logs a warning), and sweeps `LOOM_CODE_REPOS_ROOT` of the mirrors, `checkout-*` trees and mirror lock files no active entry names, so a removed repository leaves -every host, not only the one `code.repo.remove` reached. The +every host, not only the one `code.repo.remove` reached. Between those gcs, a mirror +or checkout with more than 50 packs a gc may rewrite (git's `gc.autoPackLimit`) gets +`git repack -d -l --geometric=2`, which merges the small packs its fetches write and +leaves the large one. The `loom.host.disk.free_bytes` / `loom.host.disk.total_bytes` gauges are the disk alarm's input. ## Measured coverage diff --git a/server/code/app/index/bootstrap.py b/server/code/app/index/bootstrap.py index fe7fdc2316d..c59adfe949a 100644 --- a/server/code/app/index/bootstrap.py +++ b/server/code/app/index/bootstrap.py @@ -277,7 +277,10 @@ async def clone_mirror(cfg: Any, *, pin: bool = False) -> str: # The clone runs as a repository job: the empty target its one writable path. done = await run_job( ["git", "clone", "-c", "gc.auto=0", "-c", "maintenance.auto=false"] - + ["--bare", "--quiet", *upload_pack_args(cfg.git_remote), cfg.git_remote, tmp], + # `--no-local`: a clone from a local path copies its loose objects as they + # are, and a checkout shares only the mirror's packs. + + ["--bare", "--quiet", "--no-local", *upload_pack_args(cfg.git_remote)] + + [cfg.git_remote, tmp], env=auth_env(cfg.github_token, cfg.git_remote), timeout_s=settings.code_bootstrap_clone_timeout_s, writable=[Path(tmp)], diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index d0373d92cef..33a0fa66d37 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -371,15 +371,36 @@ async def _merge_page(cfg: Any, git_dir: str, repo: Any) -> None: logger.info("mirror %s: ledger merges of %s: %s", git_dir, cfg.namespace, e) +# Git's own `gc.autoPackLimit`. Every mirror fetch writes a pack, and a shared +# checkout's sandboxed job mounts each one it links. +_PACK_LIMIT = 50 + + +def _unkept_packs(git_dir: str) -> int: + """The packs a gc or repack may merge: a kept pack is never rewritten.""" + try: + names = os.listdir(os.path.join(git_dir, "objects", "pack")) + except OSError: + return 0 + kept = {n.removesuffix(".keep") for n in names if n.endswith(".keep")} + return sum(1 for n in names if n.endswith(".pack") and n.removesuffix(".pack") not in kept) + + async def gc_if_due(git_dir: str) -> None: """`git gc --no-prune` of a mirror or a compiler tier's checkout every `code_mirror_gc_interval_h`, or once its mark is gone, at low CPU and IO priority, only when the disk holds a second copy of what the gc rewrites plus the margin (the new pack is written beside the old one); without that room it waits another interval. Nothing unreachable is pruned, and a kept pack (a checkout's packs shared - with its mirror) is never rewritten.""" + with its mirror) is never rewritten. Between gcs, more than `_PACK_LIMIT` packs get + a geometric repack, which merges the small ones and leaves the large one.""" hours = float(settings.code_mirror_gc_interval_h) - if hours <= 0 or _mark_age_s(git_dir, _GC_MARK) < hours * 3600: + if hours <= 0: + return + if _mark_age_s(git_dir, _GC_MARK) < hours * 3600: + if _unkept_packs(git_dir) > _PACK_LIMIT: + rc = await _low_priority_git(git_dir, "repack", "-d", "-l", "--geometric=2", "-q") + logger.info("mirror %s: repack exit %s", git_dir, rc) return size = await asyncio.to_thread(_tree_bytes, git_dir) free = (await asyncio.to_thread(shutil.disk_usage, git_dir)).free @@ -392,10 +413,15 @@ async def gc_if_due(git_dir: str) -> None: size // 1024**3, ) return - argv = ["nice", "-n", "19", "git", "--git-dir", git_dir, "-c", "gc.auto=0", "gc"] - proc = await asyncio.create_subprocess_exec( - *argv, "--quiet", "--no-prune", stdout=asyncio.subprocess.DEVNULL - ) + rc = await _low_priority_git(git_dir, "-c", "gc.auto=0", "gc", "--quiet", "--no-prune") + logger.info("mirror %s: gc exit %s", git_dir, rc) + + +async def _low_priority_git(git_dir: str, *args: str) -> int: + """A housekeeping git command at the lowest CPU priority, bounded by + `code_mirror_gc_timeout_s`; its exit code, -1 when it timed out.""" + argv = ["nice", "-n", "19", "git", "--git-dir", git_dir, *args] + proc = await asyncio.create_subprocess_exec(*argv, stdout=asyncio.subprocess.DEVNULL) rc = -1 try: rc = await asyncio.wait_for(proc.wait(), settings.code_mirror_gc_timeout_s) @@ -405,7 +431,7 @@ async def gc_if_due(git_dir: str) -> None: if proc.returncode is None: # timed out, or a cancelled pass: no repack outlives its lock proc.kill() await proc.wait() - logger.info("mirror %s: gc exit %s", git_dir, rc) + return rc def _tree_bytes(path: str) -> int: diff --git a/tests/unit/test_mirror_ready.py b/tests/unit/test_mirror_ready.py index b929f060692..b9fa1bf4571 100644 --- a/tests/unit/test_mirror_ready.py +++ b/tests/unit/test_mirror_ready.py @@ -493,3 +493,34 @@ async def test_the_leaders_clone_runs_in_the_background(monkeypatch, tmp_path) - assert (present, failed) == (False, "") await asyncio.sleep(0.3) assert await bootstrap.clone_in_background(cfg, _StateRepo("a" * 40)) == (True, "") + + +def test_a_clone_from_a_local_path_keeps_its_objects_in_a_pack(monkeypatch, tmp_path) -> None: + """A checkout shares only the mirror's packs; a local clone would copy loose objects.""" + import subprocess + + from server.code.app.index import sandbox + + source = tmp_path / "source" + source.mkdir() + argv = ["git", "-c", "user.name=t", "-c", "user.email=t@t", "-C", str(source)] + subprocess.run([*argv, "init", "-q"], check=True) + (source / "a.txt").write_text("a\n") + subprocess.run([*argv, "add", "a.txt"], check=True) + subprocess.run([*argv, "commit", "-qm", "a"], check=True) + + async def _pin(_c: Any) -> None: + return None + + monkeypatch.setattr(sandbox, "sandbox_available", lambda: False) + monkeypatch.setattr(bootstrap, "_pin_ledger_merges", _pin) + cfg = _Cfg(str(tmp_path / "r.git"), git_remote=str(source)) + assert asyncio.run(bootstrap.clone_and_pin(cfg)) == "" + + count = subprocess.run( + ["git", "--git-dir", cfg.git_dir, "count-objects", "-v"], + check=True, + capture_output=True, + text=True, + ).stdout + assert "count: 0\n" in count and "packs: 1\n" in count diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index b3201ddd474..958ef6a7144 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -702,3 +702,33 @@ async def merge_commit_of(self, *_a: Any) -> str: monkeypatch.setattr(blame, "repo_siblings", lambda org, ns: (cfg, [cfg])) _out, summary = await bisect_fix._fix_blame_stage(_Repo(), "o", "code-r", [], 5) # type: ignore[arg-type] assert summary["skipped"].startswith("no_git_mirror: o/code-r: clone failed") + + +def test_more_packs_than_the_limit_are_merged_before_the_gc_is_due(monkeypatch, tmp_path) -> None: + """Every mirror fetch writes a pack; past git's `gc.autoPackLimit` they are merged + on the next round, not a week later.""" + import subprocess + + def g(repo, *args: str) -> str: + argv = ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args] + return subprocess.run(argv, cwd=repo, check=True, capture_output=True, text=True).stdout + + source, git_dir = tmp_path / "source", tmp_path / "r.git" + source.mkdir() + g(source, "init", "-q") + g(source, "commit", "-q", "--allow-empty", "-m", "0") + g(tmp_path, "clone", "-q", "--bare", "--no-local", "-c", "gc.auto=0", "source", "r.git") + for i in range(55): + (source / f"f{i}").write_text(f"{i}\n") + g(source, "add", ".") + g(source, "commit", "-q", "-m", str(i)) + g(git_dir, "-c", "fetch.unpackLimit=1", "fetch", "-q", str(source), "+HEAD:refs/heads/x") + (git_dir / mirrors._GC_MARK).touch() # the weekly gc ran a moment ago + monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) + packs = git_dir / "objects" / "pack" + assert len(list(packs.glob("*.pack"))) == 56 + + asyncio.run(mirrors.gc_if_due(str(git_dir))) + + assert len(list(packs.glob("*.pack"))) <= 2 + g(git_dir, "rev-list", "--objects", "--quiet", "refs/heads/x") From d54e5926e1f6e39a136228db19578601cd796cad Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 02:02:01 +0000 Subject: [PATCH 3/6] The mirror's geometric repack waits for 500 packs Each repack makes every shared checkout of the mirror run a full gc, and the sandbox's bind list overflows only at a few thousand packs, so the trigger sits well above git's own limit of 50. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 2 +- server/code/app/index/mirrors.py | 7 ++++--- tests/unit/test_mirrors.py | 5 +++-- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index f4b17004001..924bbfcb8df 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1008,7 +1008,7 @@ copy plus `LOOM_CODE_MIRROR_GC_MARGIN_GB`, 5 GB by default; without it the gc wa another interval and logs a warning), and sweeps `LOOM_CODE_REPOS_ROOT` of the mirrors, `checkout-*` trees and mirror lock files no active entry names, so a removed repository leaves every host, not only the one `code.repo.remove` reached. Between those gcs, a mirror -or checkout with more than 50 packs a gc may rewrite (git's `gc.autoPackLimit`) gets +or checkout with more than 500 packs a gc may rewrite gets `git repack -d -l --geometric=2`, which merges the small packs its fetches write and leaves the large one. The `loom.host.disk.free_bytes` / `loom.host.disk.total_bytes` gauges are the disk alarm's input. diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index 33a0fa66d37..f2e5ecd20f4 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -371,9 +371,10 @@ async def _merge_page(cfg: Any, git_dir: str, repo: Any) -> None: logger.info("mirror %s: ledger merges of %s: %s", git_dir, cfg.namespace, e) -# Git's own `gc.autoPackLimit`. Every mirror fetch writes a pack, and a shared -# checkout's sandboxed job mounts each one it links. -_PACK_LIMIT = 50 +# Every mirror fetch writes a pack, and a shared checkout's sandboxed job mounts each +# one it links: a few thousand overflow its argv. Each repack makes every shared +# checkout run a full gc, so it waits for far more packs than git's own limit of 50. +_PACK_LIMIT = 500 def _unkept_packs(git_dir: str) -> int: diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 958ef6a7144..bed5e8228ab 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -705,8 +705,8 @@ async def merge_commit_of(self, *_a: Any) -> str: def test_more_packs_than_the_limit_are_merged_before_the_gc_is_due(monkeypatch, tmp_path) -> None: - """Every mirror fetch writes a pack; past git's `gc.autoPackLimit` they are merged - on the next round, not a week later.""" + """Every mirror fetch writes a pack; past `_PACK_LIMIT` they are merged on the next + round, not a week later.""" import subprocess def g(repo, *args: str) -> str: @@ -725,6 +725,7 @@ def g(repo, *args: str) -> str: g(git_dir, "-c", "fetch.unpackLimit=1", "fetch", "-q", str(source), "+HEAD:refs/heads/x") (git_dir / mirrors._GC_MARK).touch() # the weekly gc ran a moment ago monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) + monkeypatch.setattr(mirrors, "_PACK_LIMIT", 50) # 500 in production packs = git_dir / "objects" / "pack" assert len(list(packs.glob("*.pack"))) == 56 From 13f7cf0d0a0e16ec49630aaad4a11c09c1465f5e Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 11:58:43 +0000 Subject: [PATCH 4/6] The mirror's geometric repack checks the disk's room like the gc The repack writes its new pack beside the old ones, so on a volume already below the gc margin it could use up the space ingest needs. It now takes the same free space check as the gc and is skipped, with a warning, when there is no room; the next round tries again. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 3 ++- server/code/app/index/mirrors.py | 19 +++++++++----- tests/unit/test_mirrors.py | 33 +++++++++++++++++++----- 3 files changed, 41 insertions(+), 14 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 924bbfcb8df..3979caae691 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1010,7 +1010,8 @@ another interval and logs a warning), and sweeps `LOOM_CODE_REPOS_ROOT` of the m every host, not only the one `code.repo.remove` reached. Between those gcs, a mirror or checkout with more than 500 packs a gc may rewrite gets `git repack -d -l --geometric=2`, which merges the small packs its fetches write and -leaves the large one. The +leaves the large one, under the same room check as the gc (without room it logs a +warning and tries again next round). The `loom.host.disk.free_bytes` / `loom.host.disk.total_bytes` gauges are the disk alarm's input. ## Measured coverage diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index f2e5ecd20f4..d36753d502b 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -394,26 +394,31 @@ async def gc_if_due(git_dir: str) -> None: new pack is written beside the old one); without that room it waits another interval. Nothing unreachable is pruned, and a kept pack (a checkout's packs shared with its mirror) is never rewritten. Between gcs, more than `_PACK_LIMIT` packs get - a geometric repack, which merges the small ones and leaves the large one.""" + a geometric repack, which merges the small ones and leaves the large one, under the + same room check.""" hours = float(settings.code_mirror_gc_interval_h) if hours <= 0: return - if _mark_age_s(git_dir, _GC_MARK) < hours * 3600: - if _unkept_packs(git_dir) > _PACK_LIMIT: - rc = await _low_priority_git(git_dir, "repack", "-d", "-l", "--geometric=2", "-q") - logger.info("mirror %s: repack exit %s", git_dir, rc) + due = _mark_age_s(git_dir, _GC_MARK) >= hours * 3600 + if not due and _unkept_packs(git_dir) <= _PACK_LIMIT: return size = await asyncio.to_thread(_tree_bytes, git_dir) free = (await asyncio.to_thread(shutil.disk_usage, git_dir)).free - await asyncio.to_thread(_touch, git_dir, _GC_MARK) + if due: + await asyncio.to_thread(_touch, git_dir, _GC_MARK) if free < size + float(settings.code_mirror_gc_margin_gb) * 1024**3: logger.warning( - "mirror %s: gc skipped, %d GB free for a %d GB mirror", + "mirror %s: %s skipped, %d GB free for a %d GB mirror", git_dir, + "gc" if due else "repack", free // 1024**3, size // 1024**3, ) return + if not due: + rc = await _low_priority_git(git_dir, "repack", "-d", "-l", "--geometric=2", "-q") + logger.info("mirror %s: repack exit %s", git_dir, rc) + return rc = await _low_priority_git(git_dir, "-c", "gc.auto=0", "gc", "--quiet", "--no-prune") logger.info("mirror %s: gc exit %s", git_dir, rc) diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index bed5e8228ab..959cd96bc7d 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -704,9 +704,9 @@ async def merge_commit_of(self, *_a: Any) -> str: assert summary["skipped"].startswith("no_git_mirror: o/code-r: clone failed") -def test_more_packs_than_the_limit_are_merged_before_the_gc_is_due(monkeypatch, tmp_path) -> None: - """Every mirror fetch writes a pack; past `_PACK_LIMIT` they are merged on the next - round, not a week later.""" +def _mirror_with_56_packs(tmp_path): + """A mirror whose weekly gc ran a moment ago and that holds 56 packs, one per fetch; + (its path, a runner of git commands in a repository).""" import subprocess def g(repo, *args: str) -> str: @@ -724,12 +724,33 @@ def g(repo, *args: str) -> str: g(source, "commit", "-q", "-m", str(i)) g(git_dir, "-c", "fetch.unpackLimit=1", "fetch", "-q", str(source), "+HEAD:refs/heads/x") (git_dir / mirrors._GC_MARK).touch() # the weekly gc ran a moment ago + assert len(list((git_dir / "objects" / "pack").glob("*.pack"))) == 56 + return git_dir, g + + +def test_more_packs_than_the_limit_are_merged_before_the_gc_is_due(monkeypatch, tmp_path) -> None: + """Every mirror fetch writes a pack; past `_PACK_LIMIT` they are merged on the next + round, not a week later.""" + git_dir, g = _mirror_with_56_packs(tmp_path) + monkeypatch.setattr(settings, "code_mirror_gc_margin_gb", 0.0) monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) monkeypatch.setattr(mirrors, "_PACK_LIMIT", 50) # 500 in production - packs = git_dir / "objects" / "pack" - assert len(list(packs.glob("*.pack"))) == 56 asyncio.run(mirrors.gc_if_due(str(git_dir))) - assert len(list(packs.glob("*.pack"))) <= 2 + assert len(list((git_dir / "objects" / "pack").glob("*.pack"))) <= 2 g(git_dir, "rev-list", "--objects", "--quiet", "refs/heads/x") + + +def test_the_repack_without_room_is_skipped_like_the_gc(monkeypatch, tmp_path) -> None: + """The repack writes its pack beside the old ones, so it needs the room the gc needs.""" + git_dir, _g = _mirror_with_56_packs(tmp_path) + monkeypatch.setattr(settings, "code_mirror_gc_margin_gb", 1e9) + monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) + monkeypatch.setattr(mirrors, "_PACK_LIMIT", 50) + mark = (git_dir / mirrors._GC_MARK).stat().st_mtime + + asyncio.run(mirrors.gc_if_due(str(git_dir))) + + assert len(list((git_dir / "objects" / "pack").glob("*.pack"))) == 56 + assert (git_dir / mirrors._GC_MARK).stat().st_mtime == mark From 680ebf5623a115d9aba97e07626a509bbdca232e Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 20:42:54 +0000 Subject: [PATCH 5/6] The mirror's repack threshold is a setting The pack count past which gc_if_due runs a geometric repack was a module constant, which test_no_new_tunable_constant rejects. It becomes code_mirror_gc_pack_limit, default 500, beside the other mirror gc settings. The tests that lowered the constant set the setting instead. Signed-off-by: Kaloyan Naumov --- docs/reference/configuration.md | 1 + loom.example.yaml | 7 +++++++ schemas/loom-settings.schema.json | 5 +++++ server/code/app/index/mirrors.py | 14 ++++---------- server/settings/catalog.py | 6 ++++++ tests/unit/snapshots/settings_defaults.json | 1 + tests/unit/test_mirrors.py | 6 +++--- 7 files changed, 27 insertions(+), 13 deletions(-) diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 1b41401dad0..b4d6a948c05 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -329,6 +329,7 @@ One code namespace indexes one repository. No repository is configured by defaul | `LOOM_CODE_GIT_FETCH_TIMEOUT_S` | `float` | `3600.0` | live | Seconds one fetch, full-tree `ls-tree`, forced checkout or whole-range diff may run; the first fetch after a shallow clone of a large repository can exceed ten minutes. | | `LOOM_CODE_MIRROR_GC_INTERVAL_H` | `float` | `168.0` | | Hours between `git gc` runs of each mirror on this host (low CPU and IO priority, only with room for a second copy plus `code_mirror_gc_margin_gb`). 0 = never. | | `LOOM_CODE_MIRROR_GC_MARGIN_GB` | `float` | `5.0` | | Free disk, in GB, a mirror's gc must leave beyond the mirror's own size; without it the gc waits another interval. | +| `LOOM_CODE_MIRROR_GC_PACK_LIMIT` | `int` | `500` | | Packs a mirror or compiler-tier checkout may hold between gcs before a geometric repack merges the small ones, under the same room check. Every mirror fetch writes a pack and a shared checkout's sandboxed job mounts each one it links (a few thousand overflow its argv); each repack makes every shared checkout run a full gc, so it stays far above git's own limit of 50. | | `LOOM_CODE_COMPILER_SHARE_MIRROR_PACKS` | `bool` | `False` | | Hard-link each compiler-tier checkout's packs to its mirror's, so a tier costs its working tree, not a second copy. An older build's git jobs could write the shared packs: turn it on only once no older replica serves, and off before a rollback. | ### Repository job sandbox diff --git a/loom.example.yaml b/loom.example.yaml index 02d6b32c849..77f4a2a8bc8 100644 --- a/loom.example.yaml +++ b/loom.example.yaml @@ -1187,6 +1187,13 @@ settings: # the gc waits another interval. [restart] # code_mirror_gc_margin_gb: 5.0 + # Packs a mirror or compiler-tier checkout may hold between gcs before a geometric + # repack merges the small ones, under the same room check. Every mirror fetch writes a + # pack and a shared checkout's sandboxed job mounts each one it links (a few thousand + # overflow its argv); each repack makes every shared checkout run a full gc, so it + # stays far above git's own limit of 50. [restart] + # code_mirror_gc_pack_limit: 500 + # Hard-link each compiler-tier checkout's packs to its mirror's, so a tier costs its # working tree, not a second copy. An older build's git jobs could write the shared # packs: turn it on only once no older replica serves, and off before a rollback. diff --git a/schemas/loom-settings.schema.json b/schemas/loom-settings.schema.json index 5918dc83817..69f4edbbac0 100644 --- a/schemas/loom-settings.schema.json +++ b/schemas/loom-settings.schema.json @@ -1481,6 +1481,11 @@ "type": "number", "description": "Free disk, in GB, a mirror's gc must leave beyond the mirror's own size; without it the gc waits another interval." }, + "code_mirror_gc_pack_limit": { + "default": 500, + "type": "integer", + "description": "Packs a mirror or compiler-tier checkout may hold between gcs before a geometric repack merges the small ones, under the same room check. Every mirror fetch writes a pack and a shared checkout's sandboxed job mounts each one it links (a few thousand overflow its argv); each repack makes every shared checkout run a full gc, so it stays far above git's own limit of 50." + }, "code_mirror_gc_timeout_s": { "default": 14400.0, "exclusiveMinimum": 0, diff --git a/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index d36753d502b..378d4a9126f 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -371,12 +371,6 @@ async def _merge_page(cfg: Any, git_dir: str, repo: Any) -> None: logger.info("mirror %s: ledger merges of %s: %s", git_dir, cfg.namespace, e) -# Every mirror fetch writes a pack, and a shared checkout's sandboxed job mounts each -# one it links: a few thousand overflow its argv. Each repack makes every shared -# checkout run a full gc, so it waits for far more packs than git's own limit of 50. -_PACK_LIMIT = 500 - - def _unkept_packs(git_dir: str) -> int: """The packs a gc or repack may merge: a kept pack is never rewritten.""" try: @@ -393,14 +387,14 @@ async def gc_if_due(git_dir: str) -> None: only when the disk holds a second copy of what the gc rewrites plus the margin (the new pack is written beside the old one); without that room it waits another interval. Nothing unreachable is pruned, and a kept pack (a checkout's packs shared - with its mirror) is never rewritten. Between gcs, more than `_PACK_LIMIT` packs get - a geometric repack, which merges the small ones and leaves the large one, under the - same room check.""" + with its mirror) is never rewritten. Between gcs, more than `code_mirror_gc_pack_limit` + packs get a geometric repack, which merges the small ones and leaves the large one, + under the same room check.""" hours = float(settings.code_mirror_gc_interval_h) if hours <= 0: return due = _mark_age_s(git_dir, _GC_MARK) >= hours * 3600 - if not due and _unkept_packs(git_dir) <= _PACK_LIMIT: + if not due and _unkept_packs(git_dir) <= int(settings.code_mirror_gc_pack_limit): return size = await asyncio.to_thread(_tree_bytes, git_dir) free = (await asyncio.to_thread(shutil.disk_usage, git_dir)).free diff --git a/server/settings/catalog.py b/server/settings/catalog.py index 161f05d56ad..8df1965b568 100644 --- a/server/settings/catalog.py +++ b/server/settings/catalog.py @@ -1024,6 +1024,12 @@ class CodeSettings(BaseModel): # Free disk, in GB, a mirror's gc must leave beyond the mirror's own size; without # it the gc waits another interval. code_mirror_gc_margin_gb: float = 5.0 + # Packs a mirror or compiler-tier checkout may hold between gcs before a geometric + # repack merges the small ones, under the same room check. Every mirror fetch + # writes a pack and a shared checkout's sandboxed job mounts each one it links (a + # few thousand overflow its argv); each repack makes every shared checkout run a + # full gc, so it stays far above git's own limit of 50. + code_mirror_gc_pack_limit: int = 500 # Hard-link each compiler-tier checkout's packs to its mirror's, so a tier costs its # working tree, not a second copy. An older build's git jobs could write the shared # packs: turn it on only once no older replica serves, and off before a rollback. diff --git a/tests/unit/snapshots/settings_defaults.json b/tests/unit/snapshots/settings_defaults.json index 9c9fe62ec5a..b361a33caca 100644 --- a/tests/unit/snapshots/settings_defaults.json +++ b/tests/unit/snapshots/settings_defaults.json @@ -258,6 +258,7 @@ "code_mirror_fetch_interval_s": 300.0, "code_mirror_gc_interval_h": 168.0, "code_mirror_gc_margin_gb": 5.0, + "code_mirror_gc_pack_limit": 500, "code_mirror_gc_timeout_s": 14400.0, "code_mirror_warmup": true, "code_mirror_warmup_concurrency": 2, diff --git a/tests/unit/test_mirrors.py b/tests/unit/test_mirrors.py index 959cd96bc7d..3439ae27f00 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -729,12 +729,12 @@ def g(repo, *args: str) -> str: def test_more_packs_than_the_limit_are_merged_before_the_gc_is_due(monkeypatch, tmp_path) -> None: - """Every mirror fetch writes a pack; past `_PACK_LIMIT` they are merged on the next + """Every mirror fetch writes a pack; past `code_mirror_gc_pack_limit` they are merged on the next round, not a week later.""" git_dir, g = _mirror_with_56_packs(tmp_path) monkeypatch.setattr(settings, "code_mirror_gc_margin_gb", 0.0) monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) - monkeypatch.setattr(mirrors, "_PACK_LIMIT", 50) # 500 in production + monkeypatch.setattr(settings, "code_mirror_gc_pack_limit", 50) # 500 by default asyncio.run(mirrors.gc_if_due(str(git_dir))) @@ -747,7 +747,7 @@ def test_the_repack_without_room_is_skipped_like_the_gc(monkeypatch, tmp_path) - git_dir, _g = _mirror_with_56_packs(tmp_path) monkeypatch.setattr(settings, "code_mirror_gc_margin_gb", 1e9) monkeypatch.setattr(settings, "code_mirror_gc_interval_h", 168.0) - monkeypatch.setattr(mirrors, "_PACK_LIMIT", 50) + monkeypatch.setattr(settings, "code_mirror_gc_pack_limit", 50) mark = (git_dir / mirrors._GC_MARK).stat().st_mtime asyncio.run(mirrors.gc_if_due(str(git_dir))) From 2f181343a5f4f2e27cbf34e0b493abb2a306c18b Mon Sep 17 00:00:00 2001 From: Kaloyan Naumov Date: Sat, 28 Nov 2026 21:11:41 +0000 Subject: [PATCH 6/6] The packed test mirror is cloned like Loom's own Loom's mirror clone writes gc.auto=0 and maintenance.auto=false, but the _packed_bare fixture cloned with git's defaults. Under git 2.56 the automatic maintenance repacked that mirror between the fetches, so the checkout transfer test received objects and failed on every run. The fixture now clones with the same two settings, and the operations page names LOOM_CODE_MIRROR_GC_PACK_LIMIT where it described the threshold. Signed-off-by: Kaloyan Naumov --- docs/operations/code-index-operations.md | 3 ++- tests/unit/test_code_compiler_checkout.py | 6 +++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 3979caae691..8373ec33dd9 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -1008,7 +1008,8 @@ copy plus `LOOM_CODE_MIRROR_GC_MARGIN_GB`, 5 GB by default; without it the gc wa another interval and logs a warning), and sweeps `LOOM_CODE_REPOS_ROOT` of the mirrors, `checkout-*` trees and mirror lock files no active entry names, so a removed repository leaves every host, not only the one `code.repo.remove` reached. Between those gcs, a mirror -or checkout with more than 500 packs a gc may rewrite gets +or checkout with more than `LOOM_CODE_MIRROR_GC_PACK_LIMIT` (500 by default) packs a gc may +rewrite gets `git repack -d -l --geometric=2`, which merges the small packs its fetches write and leaves the large one, under the same room check as the gc (without room it logs a warning and tries again next round). The diff --git a/tests/unit/test_code_compiler_checkout.py b/tests/unit/test_code_compiler_checkout.py index 7971afa1fa6..7ccc13bbf49 100644 --- a/tests/unit/test_code_compiler_checkout.py +++ b/tests/unit/test_code_compiler_checkout.py @@ -383,7 +383,11 @@ def _packed_bare(tmp_path: Path, *, packed: bool = True) -> Path: _commit(source, "main.py") bare = tmp_path / "repo.git" local = "--no-local" if packed else "--local" - git(tmp_path, "clone", "-q", "--bare", local, "source", "repo.git") + git( + tmp_path, + *("clone", "-q", "-c", "gc.auto=0", "-c", "maintenance.auto=false"), + *("--bare", local, "source", "repo.git"), + ) return bare