Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): self-heal git housekeeping on partial clones (#92213)

Julian Bez3a1aca9cc79d
diff --git a/bin/start b/bin/start
index 2a25db8340d4..4270d1e90934 100755
--- a/bin/start
+++ b/bin/start
@@ -167,6 +167,16 @@ if [[ -z "${HOGLI_SKIP_ZOMBIE_CHECK:-}" ]] && command -v hogli &>/dev/null; then
hogli doctor:zombies --yes || true
fi
+# Repair git housekeeping. On a partial clone git never consolidates its own pack
+# files. A maintenance run killed by sleep or reboot also leaves a lock, which
+# disables every scheduled task without a message. Reading the state is cheap and
+# the repack runs detached, so start does not wait (see doctor_git in
+# hogli_commands/doctor.py).
+# Set HOGLI_SKIP_GIT_CHECK=1 to skip.
+if [[ -z "${HOGLI_SKIP_GIT_CHECK:-}" ]] && command -v hogli &>/dev/null; then
+ hogli doctor:git || true
+fi
+
# Pre-flight: detect who already holds the host ports the dev stack needs. A stale
# stack under a *different* compose project binds the same ports, so one of our
# containers fails to bind — and that aborts the entire `docker compose up`,
diff --git a/docs/published/handbook/engineering/developing-locally.md b/docs/published/handbook/engineering/developing-locally.md
index ef05050980c4..234189fc20ed 100644
--- a/docs/published/handbook/engineering/developing-locally.md
+++ b/docs/published/handbook/engineering/developing-locally.md
@@ -105,7 +105,12 @@ Clone the [PostHog repo](https://github.com/posthog/posthog). All future command
git clone --filter=blob:none https://github.com/PostHog/posthog && cd posthog/
```
-**Performance tip:** The `--filter=blob:none` flag downloads all commit history and tree structure, but defers file contents (blobs) until needed. This reduces the clone from ~3 GB to a few hundred MB and makes the initial clone **15-17x faster**. You still get full git history for commands like `git log` and `git diff` – blobs are fetched on demand as you use them.
+**Performance tip:** The `--filter=blob:none` flag downloads all commit history and tree structure, but defers file contents (blobs) until needed.
+File contents are about 95% of this repository, so the clone is a few hundred MB instead of several GB, and it finishes much faster.
+You still get full git history for commands like `git log` and `git diff`. Blobs are fetched on demand as you use them.
+
+`hogli start` keeps a blobless clone healthy, because git does not consolidate the pack files these on-demand fetches create.
+It repacks in the background when they build up. Run `hogli doctor:git` to do it yourself.
> The `feature-flags` container relies on the presence of the GeoLite cities
> database in the `/share` directory. If you haven't run `hogli start` this database may not exist.
diff --git a/hogli.yaml b/hogli.yaml
index 0cbb8c309dbe..877cc62a228a 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -912,6 +912,9 @@ tools:
doctor:ports:
click: hogli_commands.doctor:doctor_ports
description: Pre-flight check for host ports the dev stack needs
+ doctor:git:
+ click: hogli_commands.doctor:doctor_git
+ description: Report git housekeeping problems that make fetch and status slow
doctor:migrate-volumes:
click: hogli_commands.doctor:doctor_migrate_volumes
description: Auto-migrate ClickHouse/ZooKeeper data to the new named docker volumes
diff --git a/tools/hogli-commands/hogli_commands/doctor.py b/tools/hogli-commands/hogli_commands/doctor.py
index fb1c82b3e68e..8e6fc542b28d 100644
--- a/tools/hogli-commands/hogli_commands/doctor.py
+++ b/tools/hogli-commands/hogli_commands/doctor.py
@@ -2260,6 +2260,138 @@ def _check_zombies(repo_root: Path) -> CheckResult:
)
+# A blob:none clone writes a new promisor pack on each on-demand blob fetch.
+# Nothing consolidates them, because `gc.autoPackLimit` does not count promisor
+# packs and the `incremental-repack` maintenance task does not merge them.
+# Pack lookup cost grows with the pack count, which makes `git fetch` and
+# `git status` slow.
+#
+# The threshold is a budget, not a measurement. Set it where a person notices the
+# cost. A lower value warns while the repo is still fast, and people then ignore
+# the line.
+_GIT_PACK_WARNING_THRESHOLD = 1000
+
+# `git maintenance run` reads an existing lock as "another run is in progress".
+# It then exits 0 and prints nothing. A run killed by sleep or reboot leaves a lock
+# behind, which disables every scheduled maintenance task until a person deletes it.
+_GIT_MAINTENANCE_LOCK_STALE_SECONDS = 6 * 60 * 60
+
+
+def _git_common_dir(repo_root: Path) -> Path | None:
+ """Resolve the shared .git directory without spawning git.
+
+ In a worktree ``.git`` is a file pointing at ``<common>/worktrees/<name>``.
+ Packs, the commit-graph and the maintenance lock all live in the common dir.
+ """
+ dot_git = repo_root / ".git"
+ if dot_git.is_dir():
+ return dot_git
+ if not dot_git.is_file():
+ return None
+ try:
+ line = dot_git.read_text().strip()
+ except OSError:
+ return None
+ if not line.startswith("gitdir:"):
+ return None
+ worktree_dir = Path(line.split(":", 1)[1].strip())
+ # Git writes this pointer relative to the worktree in some layouts.
+ if not worktree_dir.is_absolute():
+ worktree_dir = repo_root / worktree_dir
+ try:
+ worktree_dir = worktree_dir.resolve(strict=True)
+ except OSError:
+ return None # Dangling pointer. Treat the tree as no repo at all.
+ # <common>/worktrees/<name> -> <common>
+ if worktree_dir.parent.name == "worktrees":
+ return worktree_dir.parent.parent
+ return worktree_dir
+
+
+@dataclass(frozen=True)
+class GitHealth:
+ pack_count: int
+ packs_capped: bool
+ has_promisor: bool
+ stale_lock: Path | None
+ missing_commit_graph: bool
+
+
+def _git_health(common_dir: Path, pack_cap: int) -> GitHealth:
+ """Read git housekeeping state with a bounded amount of work.
+
+ The scan stops counting packs past ``pack_cap``, so a neglected clone costs the
+ same as a healthy one.
+ """
+ pack_dir = common_dir / "objects" / "pack"
+ pack_count = 0
+ has_promisor = False
+ capped = False
+ try:
+ with os.scandir(pack_dir) as entries:
+ for entry in entries:
+ if entry.name.endswith(".pack"):
+ pack_count += 1
+ if pack_count > pack_cap:
+ capped = True
+ break
+ elif not has_promisor and entry.name.endswith(".promisor"):
+ has_promisor = True
+ except OSError:
+ pass
+
+ stale_lock = None
+ lock_path = common_dir / "objects" / "maintenance.lock"
+ try:
+ age = time.time() - lock_path.stat().st_mtime
+ if age > _GIT_MAINTENANCE_LOCK_STALE_SECONDS:
+ stale_lock = lock_path
+ except OSError:
+ pass
+
+ info_dir = common_dir / "objects" / "info"
+ missing_commit_graph = (
+ not (info_dir / "commit-graph").exists() and not (info_dir / "commit-graphs" / "commit-graph-chain").exists()
+ )
+
+ return GitHealth(
+ pack_count=pack_count,
+ packs_capped=capped,
+ has_promisor=has_promisor,
+ stale_lock=stale_lock,
+ missing_commit_graph=missing_commit_graph,
+ )
+
+
+def _check_git_health(repo_root: Path) -> CheckResult:
+ """Fast git housekeeping probe. Reads directory entries only, never runs git."""
+ common_dir = _git_common_dir(repo_root)
+ if common_dir is None:
+ return CheckResult(name="Git housekeeping", status=CheckStatus.OK, summary="not a git checkout")
+
+ health = _git_health(common_dir, _GIT_PACK_WARNING_THRESHOLD)
+ packs_high = health.pack_count > _GIT_PACK_WARNING_THRESHOLD
+ problems = []
+ if health.stale_lock:
+ problems.append("scheduled maintenance disabled by a stale lock")
+ if packs_high:
+ count = f"{health.pack_count}+" if health.packs_capped else str(health.pack_count)
+ problems.append(f"{count} pack files")
+ if health.missing_commit_graph:
+ problems.append("no commit-graph")
+
+ if problems:
+ # The default path repacks in the background but never writes the graph, so
+ # every case that involves a missing graph has to name the command that does.
+ return CheckResult(
+ name="Git housekeeping",
+ status=CheckStatus.WARNING,
+ summary=", ".join(problems),
+ remediation="run `hogli doctor:git --fix`" if health.missing_commit_graph else "run `hogli doctor:git`",
+ )
+ return CheckResult(name="Git housekeeping", status=CheckStatus.OK, summary="clean")
+
+
def _check_docker() -> CheckResult:
"""Check whether the Docker daemon is reachable.
@@ -2378,6 +2510,7 @@ def _run_checks(repo_root: Path) -> list[CheckResult]:
checks: list[Callable[[], CheckResult]] = [
lambda: _check_disk(repo_root),
lambda: _check_zombies(repo_root),
+ lambda: _check_git_health(repo_root),
_check_docker,
_check_migrations,
_check_ports,
@@ -2401,6 +2534,278 @@ def _run_checks(repo_root: Path) -> list[CheckResult]:
return [r for r in results if r is not None]
+# pgrep compiles this as a POSIX extended regular expression, which has no lazy
+# quantifiers, so it must stay portable. Keep it loose on purpose: it is a cheap
+# prefilter over the process table, and _process_belongs_to_repo decides. Encoding
+# repository identity in the pattern is what made earlier versions wrong, because
+# `git` takes global options before the subcommand and paths may contain spaces.
+_GIT_HOUSEKEEPING_PGREP_PATTERN = r"git .*(gc|repack|maintenance|pack-objects)"
+
+
+def _names_path(haystack: str, path: str) -> bool:
+ """Whether text names a path, and not a sibling that merely starts the same way.
+
+ A plain substring test reads `/work/posthog-copy` as `/work/posthog`, and a
+ trailing boundary alone still reads `/tmp/work/posthog` as `/work/posthog`.
+ An option value such as `--git-dir=<path>` puts an equals sign before the path.
+ """
+ return re.search(r"(?<![^\s='\"])" + re.escape(path) + r"(?=$|[\s/'\"])", haystack) is not None
+
+
+def _is_within(candidate: Path, root: Path) -> bool:
+ """Path containment by component, so `posthog-copy` is not inside `posthog`."""
+ return candidate == root or candidate.is_relative_to(root)
+
+
+def _process_cwd(pid: str) -> Path | None:
+ """The working directory of another process, or None when it cannot be read.
+
+ Linux exposes it directly. macOS needs lsof, which is not guaranteed to exist.
+ """
+ try:
+ return Path(f"/proc/{pid}/cwd").resolve(strict=True)
+ except OSError:
+ pass
+ if not shutil.which("lsof"):
+ return None
+ try:
+ out = subprocess.run(
+ ["lsof", "-a", "-p", pid, "-d", "cwd", "-Fn"], capture_output=True, text=True, timeout=5
+ ).stdout
+ except (OSError, subprocess.SubprocessError):
+ return None
+ return next((Path(line[1:]) for line in out.splitlines() if line.startswith("n")), None)
+
+
+def _common_dir_of(cwd: Path) -> Path | None:
+ """The object store a directory belongs to, which is shared across linked worktrees."""
+ try:
+ result = subprocess.run(
+ ["git", "-C", str(cwd), "rev-parse", "--git-common-dir"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return None
+ if result.returncode != 0:
+ return None
+ try:
+ return (cwd / result.stdout.strip()).resolve(strict=True)
+ except OSError:
+ return None
+
+
+def _process_belongs_to_repo(pid: str, repo: str, common_dir: Path) -> bool:
+ """Whether one git process works on this object store.
+
+ Comparing object stores rather than paths catches a sibling linked worktree, which
+ shares the store without naming the owning checkout anywhere.
+ """
+ try:
+ cmdline = subprocess.run(["ps", "-p", pid, "-o", "command="], capture_output=True, text=True, timeout=5)
+ except (OSError, subprocess.SubprocessError):
+ return True # Cannot tell, so claim it and do nothing.
+ if _names_path(cmdline.stdout, repo) or _names_path(cmdline.stdout, str(common_dir)):
+ return True
+ cwd = _process_cwd(pid)
+ if cwd is None:
+ # An unreadable working directory must not disable the repair. Every
+ # invocation this code starts names the path, so an unknown one is not ours.
+ return False
+ return _is_within(cwd, Path(repo)) or _common_dir_of(cwd) == common_dir
+
+
+def _git_housekeeping_running(main_worktree: Path, common_dir: Path) -> bool:
+ """True while git already packs this repository.
+
+ The pattern alone is machine wide, so an unrelated checkout running `git gc` would
+ otherwise make this repository look busy, and the repair would skip itself.
+ """
+ try:
+ result = subprocess.run(
+ ["pgrep", "-f", _GIT_HOUSEKEEPING_PGREP_PATTERN],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return True # Cannot tell, so assume yes and do nothing.
+ if result.returncode > 1:
+ # pgrep exits 1 for no match and 2 or more for its own errors, such as a
+ # pattern its regex engine rejects. Reading that as "nothing is running"
+ # silently disables the guard, so say so instead.
+ click.secho(f"Could not scan for running git processes: {result.stderr.strip()}", fg="yellow", err=True)
+ return True
+ if result.returncode != 0:
+ return False
+ repo = str(main_worktree)
+ return any(_process_belongs_to_repo(pid, repo, common_dir) for pid in result.stdout.split())
+
+
+def _git_main_worktree(repo_root: Path, common_dir: Path) -> Path:
+ """The checkout that owns the object store, which is what maintenance registers.
+
+ Preferring the owner over ``repo_root`` keeps a machine with many linked worktrees
+ from registering each one against the same object store. A separate git directory
+ (``git init --separate-git-dir``) has no work tree above it, so fall back.
+ """
+ return common_dir.parent if common_dir.name == ".git" else repo_root
+
+
+def _git_maintenance_registered(main_worktree: Path) -> bool:
+ try:
+ result = subprocess.run(
+ ["git", "config", "--global", "--get-all", "maintenance.repo"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ except (OSError, subprocess.SubprocessError):
+ return True # Cannot tell, so do not touch the user's global config.
+ registered = {line.strip() for line in result.stdout.splitlines() if line.strip()}
+ return str(main_worktree) in registered or str(main_worktree.resolve()) in registered
+
+
+def _spawn_background_repack(main_worktree: Path, common_dir: Path) -> None:
+ """Start `git repack -ad` detached, at background priority.
+
+ A repack takes minutes, and `hogli start` must not wait for it. Git never does
+ this itself on a partial clone, for the reason given at
+ `_GIT_PACK_WARNING_THRESHOLD`.
+ """
+ cmd = ["git", "-C", str(main_worktree), "repack", "-adl", "--threads=0"]
+ # taskpolicy -b puts the repack in the background QoS band, which throttles its
+ # IO as well as its CPU. Without it the repack competes with the dev stack.
+ if shutil.which("taskpolicy"):
+ cmd = ["taskpolicy", "-b", *cmd]
+ else:
+ cmd = ["nice", "-n", "19", *cmd]
+ log = (common_dir / "hogli-repack.log").open("a")
+ subprocess.Popen(cmd, stdout=log, stderr=log, start_new_session=True)
+
+
+def _run_git(main_worktree: Path, args: list[str], label: str) -> bool:
+ """Run one git repair step and report a failure.
+
+ git writes its own diagnostics to stderr, so this adds only the step name.
+ """
+ result = subprocess.run(["git", "-C", str(main_worktree), *args], check=False)
+ if result.returncode != 0:
+ click.secho(f"{label} failed with exit code {result.returncode}.", fg="red", err=True)
+ return False
+ return True
+
+
+def _write_commit_graph(main_worktree: Path) -> bool:
+ """Backfill unreadable commits, then write the graph.
+
+ `commit-graph write --reachable` stops at the first commit it cannot read, and a
+ partial clone does not lazy-fetch during that walk, so one absent commit leaves
+ the repo with no commit-graph at all.
+ """
+ missing = subprocess.run(
+ ["git", "-C", str(main_worktree), "rev-list", "--all", "--missing=print"],
+ capture_output=True,
+ text=True,
+ env={**os.environ, "GIT_NO_LAZY_FETCH": "1"},
+ check=False,
+ )
+ oids = [line[1:] for line in missing.stdout.splitlines() if line.startswith("?")]
+ if oids:
+ click.echo(f" fetching {len(oids)} missing commits...")
+ for oid in oids:
+ subprocess.run(["git", "-C", str(main_worktree), "cat-file", "-e", oid], check=False, capture_output=True)
+ click.echo(" writing commit-graph...")
+ return _run_git(
+ main_worktree, ["commit-graph", "write", "--reachable", "--split", "--no-progress"], "commit-graph write"
+ )
+
+
+ name="doctor:git",
+ help="Keep git housekeeping healthy so fetch and status stay fast",
+)
[email protected]("--fix", is_flag=True, help="Repack in the foreground and wait for it, instead of in the background")
+def doctor_git(fix: bool) -> None:
+ """Repair git housekeeping, and run the slow part in the background.
+
+ This runs on every ``hogli start``, so each step is instant or detached.
+ ``--fix`` runs the repack in the foreground instead.
+ """
+ common_dir = _git_common_dir(REPO_ROOT)
+ if common_dir is None:
+ click.echo("Not a git checkout, nothing to check.")
+ return
+
+ main_worktree = _git_main_worktree(REPO_ROOT, common_dir)
+ health = _git_health(common_dir, _GIT_PACK_WARNING_THRESHOLD)
+ packs_high = health.pack_count > _GIT_PACK_WARNING_THRESHOLD
+ # Run the process scan only when a result depends on it.
+ # --fix writes the same files scheduled maintenance does, so it needs the scan too.
+ needs_scan = bool(health.stale_lock) or packs_high or fix
+ busy = _git_housekeeping_running(main_worktree, common_dir) if needs_scan else False
+ acted = False
+
+ if health.stale_lock and not busy:
+ try:
+ health.stale_lock.unlink()
+ click.secho("Removed a stale git maintenance lock.", fg="yellow")
+ click.echo("Scheduled git maintenance was disabled for as long as it was there.")
+ acted = True
+ except FileNotFoundError:
+ pass # Another process removed it first.
+ except OSError as e:
+ # Reporting clean here would hide a lock that still disables every
+ # scheduled task, which is the failure this check exists to remove.
+ click.secho(f"Could not remove the stale git maintenance lock: {e}", fg="red", err=True)
+ click.echo(f"Scheduled git maintenance stays disabled until {health.stale_lock} is gone.")
+ acted = True
+
+ # A fresh clone has no registration, so none of git's own scheduled tasks run
+ # and it never gets a commit-graph.
+ if not _git_maintenance_registered(main_worktree):
+ if _run_ok(["git", "-C", str(main_worktree), "maintenance", "start"], timeout=30):
+ click.secho("Registered this repo for scheduled git maintenance.", fg="yellow")
+ acted = True
+ else:
+ click.echo("Could not register scheduled git maintenance. Run `git maintenance start` yourself.")
+
+ count = f"{health.pack_count}+" if health.packs_capped else str(health.pack_count)
+
+ if fix:
+ if busy:
+ click.echo("Git is already packing this repository. Try again when it finishes.")
+ return
+ ok = True
+ if packs_high:
+ click.echo(f"{count} pack files. Repacking in the foreground, which takes minutes.")
+ ok = _run_git(main_worktree, ["repack", "-adl", "--threads=0"], "repack")
+ ok = ok and _write_commit_graph(main_worktree)
+ if ok and health.pack_count:
+ ok = _run_git(main_worktree, ["multi-pack-index", "write", "--no-progress"], "multi-pack-index write")
+ if not ok:
+ click.secho("Repair stopped. The repository still needs work.", fg="red", err=True)
+ raise SystemExit(1)
+ click.secho("Done.", fg="green")
+ hints.record_check_run("doctor:git")
+ return
+
+ if packs_high and busy:
+ click.echo(f"{count} pack files. Git is already packing in the background.")
+ elif packs_high:
+ _spawn_background_repack(main_worktree, common_dir)
+ click.secho(f"{count} pack files. Repacking in the background.", fg="yellow")
+ if health.has_promisor:
+ click.echo("This is a partial clone, so every on-demand blob fetch adds another pack.")
+ click.echo("It runs at background priority and takes minutes. Carry on working.")
+ acted = True
+ elif not acted:
+ click.echo(f"Git housekeeping is clean ({count} pack files).")
+
+ hints.record_check_run("doctor:git")
+
+
@click.command(name="doctor", help="Quick health check for your dev environment")
def doctor() -> None:
"""Run non-destructive checks and print a status summary."""
diff --git a/tools/hogli-commands/hogli_commands/hints.py b/tools/hogli-commands/hogli_commands/hints.py
index 9ff3245b3b17..3b3f78be0e6e 100644
--- a/tools/hogli-commands/hogli_commands/hints.py
+++ b/tools/hogli-commands/hogli_commands/hints.py
@@ -26,6 +26,7 @@ _SKIP_COMMANDS = frozenset(
"doctor",
"doctor:disk",
"doctor:zombies",
+ "doctor:git",
"doctor:report",
"telemetry:off",
"telemetry:on",
@@ -50,6 +51,7 @@ class _HintDef:
_HINT_DEFS: tuple[_HintDef, ...] = (
_HintDef("doctor:disk", 7, "Run `hogli doctor:disk` to check for disk bloat"),
_HintDef("doctor:zombies", 7, "Run `hogli doctor:zombies` to find orphaned processes"),
+ _HintDef("doctor:git", 30, "Run `hogli doctor:git` to check git housekeeping"),
_HintDef("doctor", 14, "Run `hogli doctor` for a quick health check"),
)
diff --git a/tools/hogli-commands/hogli_commands/tests/test_doctor.py b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
index 3e177457e4e3..feefa7ba343f 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_doctor.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_doctor.py
@@ -2,6 +2,7 @@ import os
import json
import time
import fcntl
+import shutil
import hashlib
import threading
import subprocess
@@ -13,9 +14,11 @@ import pytest
from click.testing import CliRunner
from hogli_commands.doctor import (
+ _GIT_HOUSEKEEPING_PGREP_PATTERN,
FLOX_LOG_MAX_AGE_DAYS,
FLOX_LOG_MAX_TOTAL_BYTES,
_binary_arches,
+ _check_git_health,
_collect_import_targets,
_config_procs,
_confirm_stack_teardown,
@@ -26,6 +29,11 @@ from hogli_commands.doctor import (
_format_kv_block,
_generated_config_path,
_get_process_cwds,
+ _git_common_dir,
+ _git_health,
+ _git_housekeeping_running,
+ _git_main_worktree,
+ _git_maintenance_registered,
_is_excluded,
_normalize_arch,
_phrocs_info,
@@ -39,6 +47,7 @@ from hogli_commands.doctor import (
_scan_unheld_via_lsof,
_select_flox_logs_to_remove,
_tail,
+ doctor_git,
doctor_migrate_volumes,
doctor_ports,
)
@@ -1172,3 +1181,488 @@ def test_doctor_migrate_volumes_refuses_symlinked_lock_path(monkeypatch: pytest.
assert result.exit_code == 0
assert victim.read_text() == "precious"
assert calls == [] # bailed before touching docker
+
+
+def _make_pack_dir(common: Path, pack_count: int) -> None:
+ pack_dir = common / "objects" / "pack"
+ pack_dir.mkdir(parents=True, exist_ok=True)
+ for i in range(pack_count):
+ for ext in (".pack", ".idx", ".rev", ".promisor"):
+ (pack_dir / f"pack-{i:040x}{ext}").touch()
+
+
+def test_git_health_stops_counting_packs_past_the_cap(tmp_path: Path) -> None:
+ # The check runs on every `hogli start`. A neglected clone holds tens of
+ # thousands of packs. A full count would put seconds into a command that must
+ # cost the same on a new clone and an old one. A report of exactly cap+1 proves
+ # the scan stopped early.
+ _make_pack_dir(tmp_path, 5000)
+
+ health = _git_health(tmp_path, pack_cap=100)
+
+ assert health.pack_count == 101
+ assert health.packs_capped is True
+ assert health.has_promisor is True
+
+
+def test_git_health_reports_exact_count_below_the_cap(tmp_path: Path) -> None:
+ _make_pack_dir(tmp_path, 7)
+
+ health = _git_health(tmp_path, pack_cap=100)
+
+ assert health.pack_count == 7
+ assert health.packs_capped is False
+
+
+def test_git_common_dir_resolves_a_worktree_to_the_shared_object_store(tmp_path: Path) -> None:
+ # Packs, the commit-graph and the maintenance lock live in the shared .git, not
+ # in the worktree's private directory. A wrong result makes every check pass on
+ # a broken repo.
+ common = tmp_path / "main" / ".git"
+ (common / "worktrees" / "feature").mkdir(parents=True)
+ worktree = tmp_path / "feature"
+ worktree.mkdir()
+ (worktree / ".git").write_text(f"gitdir: {common / 'worktrees' / 'feature'}\n")
+
+ assert _git_common_dir(worktree) == common
+
+
+def test_git_common_dir_handles_a_plain_checkout_and_a_non_repo(tmp_path: Path) -> None:
+ plain = tmp_path / "plain"
+ (plain / ".git").mkdir(parents=True)
+ assert _git_common_dir(plain) == plain / ".git"
+
+ not_a_repo = tmp_path / "nope"
+ not_a_repo.mkdir()
+ assert _git_common_dir(not_a_repo) is None
+
+
+def test_git_maintenance_registered_matches_the_main_worktree(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # A fresh clone has no registration, so none of git's scheduled tasks run.
+ # Without this the check warns but never repairs the cause.
+ repo = tmp_path / "posthog"
+
+ def fake_run(cmd, **kwargs):
+ return SimpleNamespace(stdout=f"{tmp_path / 'other'}\n", returncode=0)
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+ assert _git_maintenance_registered(repo) is False
+
+ def fake_run_registered(cmd, **kwargs):
+ return SimpleNamespace(stdout=f"{tmp_path / 'other'}\n{repo}\n", returncode=0)
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run_registered)
+ assert _git_maintenance_registered(repo) is True
+
+
+def test_git_maintenance_registered_fails_safe_when_git_is_unavailable(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A false "not registered" would rewrite the user's global git config because a
+ # subprocess call failed.
+ def boom(cmd, **kwargs):
+ raise OSError("no git")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", boom)
+ assert _git_maintenance_registered(Path("/repo")) is True
+
+
+def test_git_main_worktree_prefers_the_object_store_owner(tmp_path: Path) -> None:
+ repo = tmp_path / "worktree"
+ assert _git_main_worktree(repo, tmp_path / "posthog" / ".git") == tmp_path / "posthog"
+
+
+def test_git_main_worktree_falls_back_for_a_separate_git_dir(tmp_path: Path) -> None:
+ # `git init --separate-git-dir` puts the metadata outside the tree, so the parent
+ # of the common dir is not a work tree and git commands there fail.
+ repo = tmp_path / "checkout"
+ assert _git_main_worktree(repo, tmp_path / "elsewhere" / "myrepo.git") == repo
+
+
+def test_doctor_git_spawns_the_repack_detached_instead_of_blocking(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # This runs on every `hogli start`. A repack takes minutes, so the command
+ # spawns it and does not wait. A move back to subprocess.run makes start block.
+ repo = tmp_path / "posthog"
+ (repo / ".git" / "objects" / "pack").mkdir(parents=True)
+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", repo)
+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: False)
+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=pack_cap + 1,
+ packs_capped=True,
+ has_promisor=True,
+ stale_lock=None,
+ missing_commit_graph=False,
+ ),
+ )
+ ran: list[list[str]] = []
+ spawned: list[list[str]] = []
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", lambda cmd, **kw: ran.append(cmd))
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.Popen",
+ lambda cmd, **kw: spawned.append(cmd) or SimpleNamespace(pid=1),
+ )
+
+ result = CliRunner().invoke(doctor_git, [])
+
+ assert result.exit_code == 0
+ assert len(spawned) == 1
+ assert "repack" in spawned[0]
+ assert not any("repack" in cmd for cmd in ran)
+
+
[email protected](shutil.which("pgrep") is None, reason="pgrep is not installed")
+def test_housekeeping_pattern_compiles_in_the_real_regex_engine() -> None:
+ # pgrep uses a POSIX extended regular expression, which has no lazy quantifiers.
+ # A pattern it rejects exits 2, which the scan must not read as "nothing running".
+ # Testing this with Python's re passed while the real engine refused to compile.
+ result = subprocess.run(["pgrep", "-f", _GIT_HOUSEKEEPING_PGREP_PATTERN], capture_output=True, text=True)
+ assert result.returncode <= 1, result.stderr
+
+
+ "command_line, expected",
+ [
+ ("git repack -adl --threads=0", True),
+ ("git -C /home/x/posthog repack -adl --threads=0", True),
+ ("git -C /tmp/PostHog Work/posthog repack -adl", True),
+ ("taskpolicy -b git -C /home/x/posthog repack -adl", True),
+ ("git -c gc.auto=0 gc --prune=now", True),
+ ("git maintenance run --schedule=daily", True),
+ ("git status --porcelain", False),
+ ],
+)
[email protected](shutil.which("grep") is None, reason="grep is not installed")
+def test_housekeeping_pattern_selects_candidate_processes(command_line: str, expected: bool) -> None:
+ # The pattern is only a prefilter, so it may over-match. It must not under-match,
+ # because a missed process means a second repack against the same object store.
+ result = subprocess.run(
+ ["grep", "-E", _GIT_HOUSEKEEPING_PGREP_PATTERN], input=command_line, capture_output=True, text=True
+ )
+ assert (result.returncode == 0) is expected
+
+
+def test_housekeeping_scan_reports_a_pgrep_error_instead_of_assuming_idle(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # pgrep exits 2 on a pattern it cannot compile. Reading that as no-match leaves
+ # the guard permanently off, which is how a bad pattern stays invisible.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: SimpleNamespace(returncode=2, stdout="", stderr="cannot compile"),
+ )
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is True
+
+
+def test_git_common_dir_resolves_a_relative_worktree_pointer(tmp_path: Path) -> None:
+ # Git writes this pointer relative to the worktree in some layouts. Resolving it
+ # against the process working directory finds the wrong object store, or none.
+ common = tmp_path / "main" / ".git"
+ (common / "worktrees" / "feature").mkdir(parents=True)
+ worktree = tmp_path / "feature"
+ worktree.mkdir()
+ (worktree / ".git").write_text("gitdir: ../main/.git/worktrees/feature\n")
+
+ assert _git_common_dir(worktree) == common.resolve()
+
+
+def test_git_common_dir_rejects_a_dangling_worktree_pointer(tmp_path: Path) -> None:
+ worktree = tmp_path / "feature"
+ worktree.mkdir()
+ (worktree / ".git").write_text(f"gitdir: {tmp_path / 'gone' / '.git' / 'worktrees' / 'feature'}\n")
+
+ assert _git_common_dir(worktree) is None
+
+
+def test_doctor_git_fix_writes_the_commit_graph_below_the_pack_threshold(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # The check tells people to run --fix when the commit-graph is missing. Gating the
+ # repair on a high pack count made --fix print success and repair nothing.
+ repo = tmp_path / "posthog"
+ (repo / ".git" / "objects" / "pack").mkdir(parents=True)
+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", repo)
+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: False)
+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=3,
+ packs_capped=False,
+ has_promisor=True,
+ stale_lock=None,
+ missing_commit_graph=True,
+ ),
+ )
+ ran: list[list[str]] = []
+
+ def fake_run(cmd, **kwargs):
+ ran.append(cmd)
+ return SimpleNamespace(returncode=0, stdout="", stderr="")
+
+ monkeypatch.setattr("hogli_commands.doctor.subprocess.run", fake_run)
+
+ result = CliRunner().invoke(doctor_git, ["--fix"])
+
+ assert result.exit_code == 0
+ assert any("commit-graph" in cmd for cmd in ran)
+ assert not any("repack" in cmd for cmd in ran)
+
+
+def test_doctor_git_fix_reports_a_failed_step_instead_of_success(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # A repack that runs out of disk used to print a green "Done." and record the check.
+ repo = tmp_path / "posthog"
+ (repo / ".git" / "objects" / "pack").mkdir(parents=True)
+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", repo)
+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: False)
+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=pack_cap + 1,
+ packs_capped=False,
+ has_promisor=True,
+ stale_lock=None,
+ missing_commit_graph=True,
+ ),
+ )
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: SimpleNamespace(returncode=1, stdout="", stderr="no space left on device"),
+ )
+
+ result = CliRunner().invoke(doctor_git, ["--fix"])
+
+ assert result.exit_code == 1
+ assert "Done." not in result.output
+
+
+ "stale_lock, packs_over, missing_graph, expected",
+ [
+ (False, False, True, "run `hogli doctor:git --fix`"),
+ (False, True, True, "run `hogli doctor:git --fix`"),
+ (True, False, True, "run `hogli doctor:git --fix`"),
+ (False, True, False, "run `hogli doctor:git`"),
+ ],
+)
+def test_git_health_remediation_names_a_command_that_repairs_the_problem(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+ stale_lock: bool,
+ packs_over: bool,
+ missing_graph: bool,
+ expected: str,
+) -> None:
+ # Only --fix writes the commit-graph. Sending a graph-only warning to the default
+ # path prints "clean" and leaves the warning standing on the next run.
+ repo = tmp_path / "posthog"
+ (repo / ".git").mkdir(parents=True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=pack_cap + 1 if packs_over else 3,
+ packs_capped=False,
+ has_promisor=True,
+ stale_lock=tmp_path / "lock" if stale_lock else None,
+ missing_commit_graph=missing_graph,
+ ),
+ )
+
+ assert _check_git_health(repo).remediation == expected
+
+
+def test_housekeeping_scan_ignores_git_in_another_repository(monkeypatch: pytest.MonkeyPatch) -> None:
+ # pgrep -f is machine wide. Treating an unrelated checkout's gc as this repo being
+ # busy makes the repair skip itself, including removing a stale lock.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git -C /other/repo gc --prune=now\n", stderr="")
+ if cmd[0] == "ps"
+ else SimpleNamespace(returncode=0, stdout="n/other/repo\n", stderr="")
+ ),
+ )
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is False
+
+
+def test_housekeeping_scan_claims_git_running_in_this_repository(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git -C /home/x/posthog repack -adl\n", stderr="")
+ ),
+ )
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is True
+
+
+def test_housekeeping_scan_is_idle_when_no_git_process_matches(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: SimpleNamespace(returncode=1, stdout="", stderr=""),
+ )
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is False
+
+
+def test_housekeeping_scan_claims_a_sibling_linked_worktree(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A repack started from a sibling worktree without -C names neither the owning
+ # checkout nor its path, but it uses the same object store. Missing it starts a
+ # second repack against that store.
+ common = Path("/home/x/posthog/.git")
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git repack -adl --threads=0\n", stderr="")
+ ),
+ )
+ monkeypatch.setattr("hogli_commands.doctor._process_cwd", lambda pid: Path("/home/x/worktrees/tach"))
+ monkeypatch.setattr("hogli_commands.doctor._common_dir_of", lambda cwd: common)
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), common) is True
+
+
+def test_housekeeping_scan_stays_idle_when_the_working_directory_is_unreadable(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Without lsof and without /proc the cwd cannot be read. Claiming the process
+ # there would disable stale-lock removal and repacking on that machine forever.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git gc --prune=now\n", stderr="")
+ ),
+ )
+ monkeypatch.setattr("hogli_commands.doctor._process_cwd", lambda pid: None)
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is False
+
+
+def test_doctor_git_fix_refuses_while_a_repack_is_already_running(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # --fix used to start a second minutes-long repack against the same object store.
+ repo = tmp_path / "posthog"
+ (repo / ".git" / "objects" / "pack").mkdir(parents=True)
+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", repo)
+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: True)
+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=pack_cap + 1,
+ packs_capped=False,
+ has_promisor=True,
+ stale_lock=None,
+ missing_commit_graph=True,
+ ),
+ )
+ ran: list[list[str]] = []
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: ran.append(cmd) or SimpleNamespace(returncode=0, stdout="", stderr=""),
+ )
+
+ result = CliRunner().invoke(doctor_git, ["--fix"])
+
+ assert result.exit_code == 0
+ assert not any("repack" in cmd for cmd in ran)
+
+
+def test_housekeeping_scan_ignores_a_sibling_clone_with_a_shared_prefix(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # /work/posthog-copy starts with /work/posthog. A substring test claims it, which
+ # suppresses stale-lock removal and repacking for the real repository.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git -C /work/posthog-copy repack -adl\n", stderr="")
+ ),
+ )
+ monkeypatch.setattr("hogli_commands.doctor._process_cwd", lambda pid: Path("/work/posthog-copy"))
+ monkeypatch.setattr("hogli_commands.doctor._common_dir_of", lambda cwd: Path("/work/posthog-copy/.git"))
+
+ assert _git_housekeeping_running(Path("/work/posthog"), Path("/work/posthog/.git")) is False
+
+
+def test_housekeeping_scan_ignores_a_repository_nested_under_another_root(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # /tmp/work/posthog ends with /work/posthog. A trailing boundary alone claims it.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git -C /tmp/work/posthog repack -adl\n", stderr="")
+ ),
+ )
+ monkeypatch.setattr("hogli_commands.doctor._process_cwd", lambda pid: Path("/tmp/work/posthog"))
+ monkeypatch.setattr("hogli_commands.doctor._common_dir_of", lambda cwd: Path("/tmp/work/posthog/.git"))
+
+ assert _git_housekeeping_running(Path("/work/posthog"), Path("/work/posthog/.git")) is False
+
+
+def test_doctor_git_reports_a_stale_lock_it_cannot_remove(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
+ # Swallowing the error printed "clean" while the lock still disabled every
+ # scheduled git task, which is exactly the silent failure this check removes.
+ repo = tmp_path / "posthog"
+ (repo / ".git" / "objects" / "pack").mkdir(parents=True)
+ lock = tmp_path / "maintenance.lock"
+ lock.write_text("")
+ monkeypatch.setattr("hogli_commands.doctor.REPO_ROOT", repo)
+ monkeypatch.setattr("hogli_commands.doctor._git_housekeeping_running", lambda *a: False)
+ monkeypatch.setattr("hogli_commands.doctor._git_maintenance_registered", lambda _: True)
+ monkeypatch.setattr(
+ "hogli_commands.doctor._git_health",
+ lambda common, pack_cap: SimpleNamespace(
+ pack_count=3,
+ packs_capped=False,
+ has_promisor=True,
+ stale_lock=lock,
+ missing_commit_graph=False,
+ ),
+ )
+ monkeypatch.setattr(Path, "unlink", lambda self, **kw: (_ for _ in ()).throw(PermissionError("read-only")))
+
+ result = CliRunner().invoke(doctor_git, [])
+
+ assert "clean" not in result.output
+ assert "stays disabled" in result.output
+
+
+def test_housekeeping_scan_claims_git_dir_given_as_an_option_value(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # `git --git-dir=<path> repack` puts an equals sign before the path, and the
+ # process runs outside the checkout, so the working directory says nothing.
+ monkeypatch.setattr(
+ "hogli_commands.doctor.subprocess.run",
+ lambda cmd, **kw: (
+ SimpleNamespace(returncode=0, stdout="4242\n", stderr="")
+ if cmd[0] == "pgrep"
+ else SimpleNamespace(returncode=0, stdout="git --git-dir=/home/x/posthog/.git repack -adl\n", stderr="")
+ ),
+ )
+ monkeypatch.setattr("hogli_commands.doctor._process_cwd", lambda pid: Path("/somewhere/else"))
+ monkeypatch.setattr("hogli_commands.doctor._common_dir_of", lambda cwd: Path("/somewhere/else/.git"))
+
+ assert _git_housekeeping_running(Path("/home/x/posthog"), Path("/home/x/posthog/.git")) is True
diff --git a/tools/hogli-commands/hogli_commands/tests/test_hints.py b/tools/hogli-commands/hogli_commands/tests/test_hints.py
index 470e4d5f85f7..4adf219e9bc0 100644
--- a/tools/hogli-commands/hogli_commands/tests/test_hints.py
+++ b/tools/hogli-commands/hogli_commands/tests/test_hints.py
@@ -52,13 +52,7 @@ class TestPickHint:
def test_returns_none_when_all_recent(self):
now = datetime.now(UTC)
- state: hints.HintsState = {
- "last_runs": {
- "doctor:disk": now.isoformat(),
- "doctor:zombies": now.isoformat(),
- "doctor": now.isoformat(),
- }
- }
+ state: hints.HintsState = {"last_runs": {h.command: now.isoformat() for h in hints._HINT_DEFS}}
assert hints._pick_hint(state, now) is None
@pytest.mark.parametrize(
@@ -66,13 +60,14 @@ class TestPickHint:
[
("doctor:disk", "doctor:disk"),
("doctor:zombies", "doctor:zombies"),
+ ("doctor:git", "doctor:git"),
("doctor", "hogli doctor"),
],
)
def test_returns_hint_when_stale(self, stale_command: str, expected_fragment: str):
now = datetime.now(UTC)
threshold = next(h.threshold_days for h in hints._HINT_DEFS if h.command == stale_command)
- all_commands = {"doctor:disk", "doctor:zombies", "doctor"}
+ all_commands = {h.command for h in hints._HINT_DEFS}
state: hints.HintsState = {
"last_runs": {
cmd: (now - timedelta(days=threshold + 1 if cmd == stale_command else 0)).isoformat()