Skip to content

The agent that grows with you

fix(worktree): prune each repo once per interval, skip the whole-tree du when the count decides

Tekniumadc330b18547
diff --git a/cron/scheduler.py b/cron/scheduler.py
index f4fc491f773..6134e3bb0af 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -4038,6 +4038,7 @@ _last_dead_owner_reap_at: dict[str, float] = {}
# Worktree prune throttle: the cron tick is the only reliably periodic process on gateway boxes.
_WORKTREE_MAINTENANCE_INTERVAL_SECONDS = 6 * 3600.0
_last_worktree_maintenance_at: Optional[dict] = None # profile home -> monotonic stamp
+_last_worktree_prune_at: dict[str, float] = {} # resolved repo root -> monotonic stamp
_worktree_maintenance_lock = threading.Lock()
@@ -4077,11 +4078,29 @@ def _worktree_maintenance_repos() -> list[str]:
return [r for r in sorted(repos) if (Path(r) / ".worktrees").is_dir()]
+def _claim_due_worktree_repos(repos: list[str]) -> list[str]:
+ """The subset of *repos* not pruned within the interval by ANY profile this process serves,
+ stamped as claimed. Served profiles mostly resolve the same repos (the hermes checkout at
+ least), and every prune pass ends in a footprint probe of the whole ``.worktrees/``, so a
+ per-profile pass multiplied that disk walk by the profile count at the same second."""
+ now = time.monotonic()
+ due = []
+ with _worktree_maintenance_lock:
+ for repo in repos:
+ key = os.path.realpath(repo)
+ last = _last_worktree_prune_at.get(key)
+ if last is None or now - last >= _WORKTREE_MAINTENANCE_INTERVAL_SECONDS:
+ _last_worktree_prune_at[key] = now
+ due.append(repo)
+ return due
+
+
def _maybe_run_worktree_maintenance() -> None:
"""Throttled worktree prune from the cron tick, on a daemon thread so the tick never waits on
git. Same pruner as ``hermes -w`` startup (idle dirty/unpushed trees archived before removal,
- live trees untouched). Throttled per profile home: a multiplexed tick runs once per served
- profile, and each must sweep its own registered repos under its own config. The thread runs in
+ live trees untouched). Repo discovery is throttled per profile home (each profile has its own
+ registry and jobs); the prune itself runs once per repo per interval across every served
+ profile, under the config of the profile that claims it first. The thread runs in
a copy of the caller's context so the profile-home override travels with it. Errors never
propagate: GC is hygiene, not scheduling."""
global _last_worktree_maintenance_at
@@ -4100,7 +4119,7 @@ def _maybe_run_worktree_maintenance() -> None:
def _run() -> None:
try:
- repos = _worktree_maintenance_repos()
+ repos = _claim_due_worktree_repos(_worktree_maintenance_repos())
if not repos:
return
from hermes_cli.worktree_ops import _prune_stale_worktrees
diff --git a/hermes_cli/worktree_gc.py b/hermes_cli/worktree_gc.py
index 8fdfe8458c9..cd715150f5f 100644
--- a/hermes_cli/worktree_gc.py
+++ b/hermes_cli/worktree_gc.py
@@ -86,10 +86,14 @@ def _git(args: list, cwd: str, timeout: int = 15) -> subprocess.CompletedProcess
def _tree_size_mb(path: Path, timeout: int = 30) -> Optional[int]:
- """Cheap directory size via ``du -sm`` — best-effort, None on failure."""
+ """Cheap directory size via ``du -sm`` — best-effort, None on failure or timeout. Not
+ ``subprocess.run``: its post-kill ``wait()`` never returns for a ``du`` stuck in uninterruptible
+ disk I/O, so the caller (a ``hermes -w`` launch, the cron prune thread) would hang with it."""
+ from hermes_cli._subprocess_compat import bounded_probe_run
+
try:
- result = _run(["du", "-sm", str(path)], timeout)
- return int(result.stdout.split()[0]) if result.returncode == 0 and result.stdout.strip() else None
+ result = bounded_probe_run(["du", "-sm", str(path)], timeout=timeout)
+ return int(result.stdout.split()[0]) if result and result.returncode == 0 and result.stdout.strip() else None
except Exception:
return None
@@ -422,8 +426,10 @@ def reclaim_branches(
return actions
-def worktrees_summary(repo_root: str) -> tuple[int, Optional[int]]:
- """(tree_count, total_size_mb) for the escalation notice; size is best-effort with a timeout."""
+def worktrees_summary(repo_root: str, *, size_below_count: Optional[int] = None) -> tuple[int, Optional[int]]:
+ """(tree_count, total_size_mb) for the escalation notice; size is best-effort with a timeout,
+ and skipped (None) once the count reaches *size_below_count*: sizing walks every file of every
+ tree, node_modules included."""
worktrees_dir = Path(repo_root) / ".worktrees"
if not worktrees_dir.exists():
return 0, None
@@ -431,4 +437,6 @@ def worktrees_summary(repo_root: str) -> tuple[int, Optional[int]]:
count = sum(1 for e in worktrees_dir.iterdir() if e.is_dir())
except Exception:
return 0, None
+ if size_below_count is not None and count >= size_below_count:
+ return count, None
return count, _tree_size_mb(worktrees_dir, timeout=20)
diff --git a/hermes_cli/worktree_ops.py b/hermes_cli/worktree_ops.py
index d23d5d1cc5f..44ab64d90e5 100644
--- a/hermes_cli/worktree_ops.py
+++ b/hermes_cli/worktree_ops.py
@@ -1223,10 +1223,10 @@ def _warn_worktree_footprint(repo_root: str) -> None:
try:
from hermes_cli.worktree_gc import worktrees_summary
- count, size_mb = worktrees_summary(repo_root)
+ count, size_mb = worktrees_summary(repo_root, size_below_count=10)
if count >= 10 or (size_mb or 0) >= 5120:
- size_txt = f"{size_mb / 1024:.1f}GB" if size_mb else "unknown size"
- logger.warning(".worktrees/ holds %d tree(s) (%s) — run `hermes worktree list` "
+ size_txt = f" ({size_mb / 1024:.1f}GB)" if size_mb else ""
+ logger.warning(".worktrees/ holds %d tree(s)%s — run `hermes worktree list` "
"to audit and `hermes worktree prune` to reclaim safely.", count, size_txt)
except Exception:
logger.debug("worktree summary failed", exc_info=True)
diff --git a/tests/cron/test_worktree_maintenance_once_per_repo.py b/tests/cron/test_worktree_maintenance_once_per_repo.py
new file mode 100644
index 00000000000..80f09fb7753
--- /dev/null
+++ b/tests/cron/test_worktree_maintenance_once_per_repo.py
@@ -0,0 +1,97 @@
+"""Worktree maintenance must not multiply whole-``.worktrees/`` disk walks.
+
+A multiplexed gateway ticks cron once per served profile, and every profile resolves the hermes
+checkout; each prune pass ends in a footprint probe that used to ``du`` the entire ``.worktrees/``
+(millions of node_modules inodes) even when the tree count alone decided the warning.
+"""
+
+import logging
+import os
+import stat
+import subprocess
+
+import pytest
+
+
+def _git_repo(path):
+ path.mkdir()
+ subprocess.run(["git", "init", "--initial-branch=main", str(path)], check=True,
+ capture_output=True, timeout=15)
+ (path / ".worktrees").mkdir()
+ return path
+
+
+def test_profiles_sharing_a_repo_prune_it_once_per_interval(tmp_path, monkeypatch):
+ import cron.scheduler as sched
+ from hermes_cli import worktree_ops
+ from hermes_cli.worktree_registry import record_worktree_repo
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ shared = _git_repo(tmp_path / "shared")
+ private = _git_repo(tmp_path / "private")
+ homes = {name: tmp_path / name for name in ("default", "ops", "lab")}
+ for name, home in homes.items():
+ home.mkdir()
+ token = set_hermes_home_override(home)
+ try:
+ record_worktree_repo(shared)
+ if name == "lab":
+ record_worktree_repo(private)
+ finally:
+ reset_hermes_home_override(token)
+
+ pruned = []
+ monkeypatch.setattr(worktree_ops, "_prune_stale_worktrees", lambda repo: pruned.append(repo))
+ monkeypatch.setattr(sched, "_last_worktree_maintenance_at", None)
+ monkeypatch.setattr(sched, "_last_worktree_prune_at", {}, raising=False)
+
+ class _InlineThread:
+ def __init__(self, target, args=(), **_kw):
+ self._run = lambda: target(*args)
+
+ def start(self):
+ self._run()
+
+ monkeypatch.setattr(sched.threading, "Thread", _InlineThread)
+
+ for home in homes.values(): # one multiplexed tick: each served profile in its own scope
+ token = set_hermes_home_override(home)
+ try:
+ sched._maybe_run_worktree_maintenance()
+ finally:
+ reset_hermes_home_override(token)
+
+ ours = [os.path.realpath(r) for r in pruned if os.path.realpath(r) in
+ {os.path.realpath(shared), os.path.realpath(private)}]
+ assert sorted(ours) == sorted([os.path.realpath(shared), os.path.realpath(private)])
+
+
+def test_footprint_warning_sizes_the_tree_only_when_the_count_does_not_decide(
+ tmp_path, monkeypatch, caplog):
+ from hermes_cli import worktree_ops
+
+ shim_dir = tmp_path / "bin"
+ shim_dir.mkdir()
+ du_log = tmp_path / "du.log"
+ du = shim_dir / "du"
+ du.write_text(f'#!/bin/sh\necho "$@" >> "{du_log}"\necho "6000\t$2"\n')
+ du.chmod(du.stat().st_mode | stat.S_IXUSR)
+ monkeypatch.setenv("PATH", f"{shim_dir}{os.pathsep}{os.environ['PATH']}")
+
+ crowded = _git_repo(tmp_path / "crowded")
+ for i in range(10):
+ (crowded / ".worktrees" / f"lane-{i}").mkdir()
+ sparse = _git_repo(tmp_path / "sparse")
+ for i in range(2):
+ (sparse / ".worktrees" / f"lane-{i}").mkdir()
+
+ with caplog.at_level(logging.WARNING, logger=worktree_ops.logger.name):
+ worktree_ops._warn_worktree_footprint(str(crowded))
+ assert not du_log.exists(), "the count alone decides: no walk of .worktrees/"
+ assert "holds 10 tree(s)" in caplog.text
+
+ caplog.clear()
+ worktree_ops._warn_worktree_footprint(str(sparse))
+ assert du_log.read_text().count("-sm") == 1
+ assert "holds 2 tree(s) (5.9GB)" in caplog.text