Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions docs/operations/code-index-operations.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions docs/reference/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 7 additions & 0 deletions loom.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
5 changes: 5 additions & 0 deletions schemas/loom-settings.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion server/code/app/index/bootstrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)],
Expand Down
6 changes: 5 additions & 1 deletion server/code/app/index/gitrepo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
44 changes: 35 additions & 9 deletions server/code/app/index/mirrors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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:
Expand Down
6 changes: 6 additions & 0 deletions server/settings/catalog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions tests/unit/snapshots/settings_defaults.json
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
67 changes: 66 additions & 1 deletion tests/unit/test_code_compiler_checkout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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"
31 changes: 31 additions & 0 deletions tests/unit/test_mirror_ready.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
52 changes: 52 additions & 0 deletions tests/unit/test_mirrors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading