The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cron): serialise the tick's worktree prune sweeps
qby2420c0d599d7
diff --git a/cron/scheduler.py b/cron/scheduler.pyindex 4ced0e7e1c3..2092d1179e3 100644--- a/cron/scheduler.py+++ b/cron/scheduler.py@@ -4081,7 +4081,8 @@ def _maybe_run_worktree_maintenance() -> None:"""Throttled worktree prune from the cron tick, on a daemon thread so the tick never waits ongit. Same pruner as ``hermes -w`` startup (idle dirty/unpushed trees archived before removal,live trees untouched). Discovery is throttled per profile home, the prune once per repo across- served profiles. Runs in a copy of the caller's context (profile-home override); never raises."""+ served profiles, and ``cron.scheduler_worktree_maintenance`` runs one sweep at a time per+ process. Runs in a copy of the caller's context (profile-home override); never raises."""global _last_worktree_maintenance_atimport contextvars@@ -4097,20 +4098,10 @@ def _maybe_run_worktree_maintenance() -> None:_last_worktree_maintenance_at = {**stamps, home: now}def _run() -> None:- try:- from cron.scheduler_worktree_maintenance import claim_due_worktree_repos as claim- repos = claim(_worktree_maintenance_repos(), _WORKTREE_MAINTENANCE_INTERVAL_SECONDS)- if not repos:- return- from hermes_cli.worktree_ops import _prune_stale_worktrees+ from cron.scheduler_worktree_maintenance import run_sweep- for repo in repos:- try:- _prune_stale_worktrees(repo)- except Exception:- logger.debug("Cron worktree maintenance failed for %s", repo, exc_info=True)- except Exception:- logger.debug("Cron worktree maintenance skipped", exc_info=True)+ run_sweep(_worktree_maintenance_repos,+ interval_seconds=_WORKTREE_MAINTENANCE_INTERVAL_SECONDS)threading.Thread(target=contextvars.copy_context().run, args=(_run,), name="cron-worktree-prune",daemon=True).start()diff --git a/cron/scheduler_worktree_maintenance.py b/cron/scheduler_worktree_maintenance.pyindex 9879fa81bac..50f50db6673 100644--- a/cron/scheduler_worktree_maintenance.py+++ b/cron/scheduler_worktree_maintenance.py@@ -1,27 +1,83 @@-"""Per-repo claim for the cron worktree prune.+"""Process-wide coordination for the cron tick's worktree prune (``cron.scheduler`` runs in here).-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. One process claims each repo once per interval.+One process ticks every served profile (``cron/AGENTS.md``), so the per-profile throttle in+``cron.scheduler`` legitimately lets each profile decide it is due, and each due profile gets its+own ``cron-worktree-prune`` thread. Those threads used to fork ``git`` side by side, which starved a+338-profile gateway's event loop until the liveness watchdog exited 75 (#143255). Two guards:++- **One sweep at a time.** The tick is sequential, the sweeps it dispatches are not; serialising+ them (discovery included) keeps the number of concurrent ``git`` children at one regardless of+ profile count. A waiting sweep holds no resources, so the wait is capped rather than unbounded.+- **One prune per repo per interval.** 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 the second profile to reach a shared repo within the interval has nothing to do."""+import loggingimport osimport threadingimport time+from typing import Callable, Iterable, Optional++logger = logging.getLogger(__name__)-_last_worktree_prune_at: dict[str, float] = {} # resolved repo root -> monotonic stamp+# Bounded so a wedged sweep cannot park a profile's thread forever; a normal sweep is one git pass+# over a handful of repos.+SWEEP_WAIT_SECONDS = 120.0++_sweep_slot = threading.Semaphore(1)+_last_worktree_prune_at: dict[str, float] = {} # canonical repo path -> monotonic stamp_lock = threading.Lock()-def claim_due_worktree_repos(repos: list[str], interval_s: float) -> list[str]:- """The subset of *repos* no served profile pruned within *interval_s*, stamped as claimed."""+def claim_sweep_slot(wait_seconds: Optional[float] = None) -> bool:+ """Take the process-wide prune slot, waiting for the sweep ahead of us (bounded)."""+ return _sweep_slot.acquire(timeout=SWEEP_WAIT_SECONDS if wait_seconds is None else wait_seconds)+++def release_sweep_slot() -> None:+ _sweep_slot.release()+++def claim_due_worktree_repos(repos: Iterable[str], interval_s: float) -> list[str]:+ """The subset of *repos* no served profile pruned within *interval_s*, stamped as claimed.++ Keyed on the path ``git`` resolves to, case-folded where the filesystem is (Windows).+ """now = time.monotonic()due = []with _lock:for repo in repos:- key = os.path.realpath(repo)+ key = os.path.normcase(os.path.realpath(repo))last = _last_worktree_prune_at.get(key)if last is None or now - last >= interval_s:_last_worktree_prune_at[key] = nowdue.append(repo)return due+++def run_sweep(discover: Callable[[], Iterable[str]], *, interval_seconds: float,+ wait_seconds: Optional[float] = None) -> None:+ """Prune the repos ``discover()`` reports that are due, from the cron tick's daemon thread.++ ``discover`` stays in the caller so a per-profile repo lookup (and anything a test patches) is+ read where it is defined. Errors never propagate: GC is hygiene, not scheduling.+ """+ if not claim_sweep_slot(wait_seconds):+ logger.debug("Cron worktree maintenance skipped: another sweep is still running")+ return+ try:+ repos = claim_due_worktree_repos(discover() or [], interval_seconds)+ if not repos:+ return+ from hermes_cli.worktree_ops import _prune_stale_worktrees++ for repo in repos:+ try:+ _prune_stale_worktrees(repo)+ except Exception:+ logger.debug("Cron worktree maintenance failed for %s", repo, exc_info=True)+ except Exception:+ logger.debug("Cron worktree maintenance skipped", exc_info=True)+ finally:+ release_sweep_slot()diff --git a/tests/cron/test_worktree_maintenance_shared_repo.py b/tests/cron/test_worktree_maintenance_shared_repo.pynew file mode 100644index 00000000000..74a200b14a0--- /dev/null+++ b/tests/cron/test_worktree_maintenance_shared_repo.py@@ -0,0 +1,129 @@+"""The cron tick's worktree prune must not fan its git work out with the profile count (#143255).++A multiplexed gateway ticks every served profile from one process, and each of those ticks pruned+the SAME repos (the Hermes checkout is in the list for every profile) — hundreds of concurrent+``cron-worktree-prune`` threads forking ``git`` against one repo until the liveness watchdog gave up.+"""++import threading+import time++import pytest++from cron import scheduler++try: # the base revision has no process-wide coordination layer+ from cron import scheduler_worktree_maintenance as maintenance+except ImportError: # pragma: no cover - only on the base revision+ maintenance = None+++def _join_prune_threads(timeout: float = 30.0) -> None:+ """Join the sweeps this test dispatched (they run on daemon threads)."""+ deadline = time.monotonic() + timeout+ for thread in threading.enumerate():+ if thread.name == "cron-worktree-prune":+ thread.join(max(0.0, deadline - time.monotonic()))+++def _new_prune_threads(known):+ return [t for t in threading.enumerate()+ if t.name == "cron-worktree-prune" and t.ident not in known]+++def test_a_shared_repo_is_pruned_once_however_many_profiles_tick(tmp_path, monkeypatch):+ repo = tmp_path / "shared-repo"+ (repo / ".worktrees").mkdir(parents=True)+ pruned = []++ monkeypatch.setattr(scheduler, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(scheduler, "_worktree_maintenance_repos", lambda: [str(repo)])+ monkeypatch.setattr("hermes_cli.worktree_ops._prune_stale_worktrees", pruned.append)++ for index in range(3):+ home = tmp_path / f"profile-{index}"+ home.mkdir()+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda home=home: home)+ scheduler._maybe_run_worktree_maintenance()++ _join_prune_threads()++ assert pruned == [str(repo)], "every profile's tick pruned the same shared repo"+++def test_a_sweep_waits_instead_of_forking_git_beside_the_running_one(tmp_path, monkeypatch):+ entered = threading.Event()+ release = threading.Event()+ discoveries = []++ def discover():+ discoveries.append(len(discoveries) + 1)+ entered.set()+ release.wait(30)+ return []++ monkeypatch.setattr(scheduler, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(scheduler, "_worktree_maintenance_repos", discover)+ if maintenance is not None:+ # The queue-ahead sweep stays blocked; the one behind it must give up, not run beside it.+ monkeypatch.setattr(maintenance, "SWEEP_WAIT_SECONDS", 0.05)++ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path / "first")+ try:+ scheduler._maybe_run_worktree_maintenance()+ assert entered.wait(30), "the first sweep never started"++ known = {t.ident for t in threading.enumerate() if t.name == "cron-worktree-prune"}+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path / "second")+ scheduler._maybe_run_worktree_maintenance()+ for thread in _new_prune_threads(known):+ thread.join(30)++ assert len(discoveries) == 1, "a second sweep forked git beside the running one"+ finally:+ release.set()+ _join_prune_threads()+++def test_a_profiles_own_repo_is_still_pruned(tmp_path, monkeypatch):+ first = tmp_path / "first-repo"+ second = tmp_path / "second-repo"+ for repo in (first, second):+ (repo / ".worktrees").mkdir(parents=True)+ pruned = []+ current = {"repos": [str(first)]}++ monkeypatch.setattr(scheduler, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(scheduler, "_worktree_maintenance_repos", lambda: current["repos"])+ monkeypatch.setattr("hermes_cli.worktree_ops._prune_stale_worktrees", pruned.append)++ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path / "a")+ scheduler._maybe_run_worktree_maintenance()+ _join_prune_threads()++ current["repos"] = [str(second)]+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path / "b")+ scheduler._maybe_run_worktree_maintenance()+ _join_prune_threads()++ assert pruned == [str(first), str(second)]+++def test_the_sweep_slot_is_released_when_discovery_raises(tmp_path, monkeypatch):+ module = maintenance+ if module is None:+ pytest.skip("no process-wide sweep slot on this revision")+ return++ def discover():+ raise RuntimeError("repo lookup blew up")++ monkeypatch.setattr(scheduler, "_last_worktree_maintenance_at", None)+ monkeypatch.setattr(scheduler, "_worktree_maintenance_repos", discover)+ monkeypatch.setattr("hermes_constants.get_hermes_home", lambda: tmp_path / "a")++ scheduler._maybe_run_worktree_maintenance()+ _join_prune_threads()++ assert maintenance.claim_sweep_slot(0.1), "a failed sweep parked the process-wide slot"+ maintenance.release_sweep_slot()