diff --git a/docs/operations/code-index-operations.md b/docs/operations/code-index-operations.md index 11c30551f5d..8373ec33dd9 100644 --- a/docs/operations/code-index-operations.md +++ b/docs/operations/code-index-operations.md @@ -376,7 +376,8 @@ 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 +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,12 @@ 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 `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 `loom.host.disk.free_bytes` / `loom.host.disk.total_bytes` gauges are the disk alarm's input. ## Measured coverage 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/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/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/server/code/app/index/mirrors.py b/server/code/app/index/mirrors.py index d0373d92cef..378d4a9126f 100644 --- a/server/code/app/index/mirrors.py +++ b/server/code/app/index/mirrors.py @@ -371,31 +371,57 @@ 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) +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 `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 or _mark_age_s(git_dir, _GC_MARK) < hours * 3600: + if hours <= 0: + return + due = _mark_age_s(git_dir, _GC_MARK) >= hours * 3600 + 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 - 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 - 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 - ) + 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) + + +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/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_code_compiler_checkout.py b/tests/unit/test_code_compiler_checkout.py index 1f6fe232537..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 @@ -839,3 +843,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" 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..3439ae27f00 100644 --- a/tests/unit/test_mirrors.py +++ b/tests/unit/test_mirrors.py @@ -702,3 +702,55 @@ 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 _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: + 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 + 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 `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(settings, "code_mirror_gc_pack_limit", 50) # 500 by default + + asyncio.run(mirrors.gc_if_due(str(git_dir))) + + 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(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))) + + assert len(list((git_dir / "objects" / "pack").glob("*.pack"))) == 56 + assert (git_dir / mirrors._GC_MARK).stat().st_mtime == mark