The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lsp): expose lsp.idle_timeout in config, harden reaper, log reaps
kshitijk4poor24a56f027c23
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.pyindex b38627504b4..f118ccf0ace 100644--- a/agent/lsp/eventlog.py+++ b/agent/lsp/eventlog.py@@ -40,7 +40,7 @@ from __future__ import annotationsimport loggingimport osimport threading-from typing import Tuple+from typing import List, Tuple# Dedicated logger name so the documented grep recipe survives a# ``logging.getLogger(__name__)`` rename of any internal module.@@ -188,6 +188,25 @@ def log_spawn_failed(server_id: str, workspace_root: str, exc: BaseException) ->)+def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:+ """Idle clients were shut down by the reaper. INFO — one line per+ sweep so users can correlate memory drops with LSP activity.++ Also clears the ``log_active`` announce cache for the reaped keys so+ a later respawn re-announces at INFO instead of logging a misleading+ DEBUG "reused client".+ """+ with _announce_lock:+ for key in keys:+ _announced_active.discard(key)+ summary = ", ".join(f"{sid} ({root})" for sid, root in keys)+ _emit(+ "reaper",+ logging.INFO,+ f"reaped {len(keys)} idle client(s) after {idle_timeout:.0f}s: {summary}",+ )++def reset_announce_caches() -> None:"""Test-only: clear the dedup caches. Production code never calls this."""with _announce_lock:@@ -209,5 +228,6 @@ __all__ = ["log_timeout","log_server_error","log_spawn_failed",+ "log_reaped","reset_announce_caches",]diff --git a/agent/lsp/manager.py b/agent/lsp/manager.pyindex 9c0ce2abfa0..757f7ebc7b9 100644--- a/agent/lsp/manager.py+++ b/agent/lsp/manager.py@@ -59,6 +59,7 @@ from agent.lsp.workspace import (logger = logging.getLogger("agent.lsp.manager")DEFAULT_IDLE_TIMEOUT = 600 # seconds; servers idle for >10min get reaped+MIN_IDLE_TIMEOUT = 30 # floor for config values; must exceed any per-op wait budgetclass _BackgroundLoop:@@ -209,6 +210,16 @@ class LSPService:wait_mode = lsp_cfg.get("wait_mode", "document")wait_timeout = float(lsp_cfg.get("wait_timeout", DIAGNOSTICS_DOCUMENT_WAIT))install_strategy = lsp_cfg.get("install_strategy", "auto")+ try:+ idle_timeout = float(lsp_cfg.get("idle_timeout", DEFAULT_IDLE_TIMEOUT))+ except (TypeError, ValueError):+ idle_timeout = DEFAULT_IDLE_TIMEOUT+ if 0 < idle_timeout < MIN_IDLE_TIMEOUT:+ # A timeout below the per-operation wait budget could reap a+ # client mid-flight; the resulting outer timeout would then+ # mark the (server, workspace) pair broken for the process+ # lifetime. Clamp to a safe floor (0 still disables).+ idle_timeout = MIN_IDLE_TIMEOUTservers_cfg = lsp_cfg.get("servers") or {}disabled = []binary_overrides: Dict[str, List[str]] = {}@@ -239,6 +250,7 @@ class LSPService:env_overrides=env_overrides,init_overrides=init_overrides,disabled_servers=disabled,+ idle_timeout=idle_timeout,)# ------------------------------------------------------------------@@ -438,6 +450,7 @@ class LSPService:# ``_clients`` with a half-initialized state.with self._state_lock:client = self._clients.pop(key, None)+ self._last_used.pop(key, None)if client is not None:try:# Fire-and-forget shutdown — give it a second to cleanup,@@ -474,7 +487,7 @@ class LSPService:except Exception as e: # noqa: BLE001logger.debug("snapshot open/wait failed: %s", e)return []- self._last_used[(client.server_id, client.workspace_root)] = time.time()+ self._touch(client)if not fresh:# No fresh data for the pre-edit content — an empty baseline# is safe: worst case the delta filter removes less, never@@ -503,7 +516,7 @@ class LSPService:except Exception as e: # noqa: BLE001logger.debug("open/wait failed for %s: %s", file_path, e)return None- self._last_used[(client.server_id, client.workspace_root)] = time.time()+ self._touch(client)if not fresh:return Nonereturn list(client.diagnostics_for(file_path, fresh_only=True))@@ -594,7 +607,7 @@ class LSPService:return Nonewith self._state_lock:self._clients[key] = client- self._last_used[key] = time.time()+ self._last_used[key] = time.time()eventlog.log_active(srv.server_id, per_server_root)spawn_future.set_result(client)return client@@ -605,25 +618,53 @@ class LSPService:async def _start_idle_reaper(self) -> None:self._idle_reaper_task = asyncio.create_task(self._idle_reaper_loop())+ def _touch(self, client: LSPClient) -> None:+ """Refresh the last-used timestamp for a client we just used.++ Guarded on membership so a reaped-mid-operation client can't+ resurrect an orphan ``_last_used`` entry after the reaper popped+ the key. All writers and the reaper run on the background loop+ thread; the lock keeps this consistent with the reader anyway.+ """+ key = (client.server_id, client.workspace_root)+ with self._state_lock:+ if key in self._clients:+ self._last_used[key] = time.time()+async def _idle_reaper_loop(self) -> None:interval = min(60.0, self._idle_timeout)while True:await asyncio.sleep(interval)- cutoff = time.time() - self._idle_timeout- with self._state_lock:- idle_keys = [- key- for key in self._clients- if self._last_used.get(key, 0) < cutoff- ]- clients = [self._clients.pop(key) for key in idle_keys]- for key in idle_keys:- self._last_used.pop(key, None)- if clients:- await asyncio.gather(- *(client.shutdown() for client in clients),- return_exceptions=True,- )+ try:+ await self._reap_idle_once()+ except asyncio.CancelledError:+ raise+ except Exception as e: # noqa: BLE001+ # A transient sweep error must not kill the reaper —+ # otherwise one bad shutdown permanently re-opens the+ # unbounded-accumulation leak this loop exists to fix.+ logger.debug("LSP idle reaper sweep error: %s", e)++ async def _reap_idle_once(self) -> None:+ cutoff = time.time() - self._idle_timeout+ with self._state_lock:+ idle_keys = [+ key+ for key in self._clients+ if self._last_used.get(key, 0) < cutoff+ ]+ clients = [self._clients.pop(key) for key in idle_keys]+ for key in idle_keys:+ self._last_used.pop(key, None)+ if clients:+ eventlog.log_reaped(+ [(c.server_id, c.workspace_root) for c in clients],+ self._idle_timeout,+ )+ await asyncio.gather(+ *(client.shutdown() for client in clients),+ return_exceptions=True,+ )async def _shutdown_async(self) -> None:reaper = self._idle_reaper_taskdiff --git a/hermes_cli/config.py b/hermes_cli/config.pyindex b51b4cea4d5..a7d8975ea39 100644--- a/hermes_cli/config.py+++ b/hermes_cli/config.py@@ -3578,6 +3578,14 @@ DEFAULT_CONFIG = {# ``"off"`` — alias for ``manual``."install_strategy": "auto",+ # Idle language servers are shut down automatically after this+ # many seconds with no file activity, then respawned on demand.+ # Prevents long-running gateway/CLI processes from accumulating+ # stale pyright/gopls/tsserver children (hundreds of MB each,+ # plus pipe FDs) as the agent moves across worktrees. Set to 0+ # to disable idle reaping and keep servers for process lifetime.+ "idle_timeout": 600.0,+# Per-server overrides. Each key is a server_id from the# registry (``pyright``, ``typescript``, ``gopls``,# ``rust-analyzer``, etc.) and accepts:diff --git a/tests/agent/lsp/test_service.py b/tests/agent/lsp/test_service.pyindex 90d950f4a70..9a526252a22 100644--- a/tests/agent/lsp/test_service.py+++ b/tests/agent/lsp/test_service.py@@ -205,3 +205,140 @@ def test_service_reaps_client_after_idle_timeout(mock_pyright):assert process.returncode is not Nonefinally:svc.shutdown()+++def test_reused_client_refreshes_last_used_and_survives_reap(mock_pyright):+ """A client re-acquired from the cache must have its ``_last_used``+ timestamp refreshed so a subsequent sweep does NOT evict it.++ Covers the timestamp refresh on the existing-client fast path in+ ``_get_or_spawn`` — without it, a client in constant use would be+ reaped ``idle_timeout`` seconds after its FIRST use.+ """+ repo = mock_pyright+ f = repo / "x.py"+ f.write_text("")+ svc = LSPService(+ enabled=True,+ wait_mode="document",+ wait_timeout=3.0,+ install_strategy="manual",+ idle_timeout=60.0, # sweeps manually below; loop never fires+ )+ try:+ svc.get_diagnostics_sync(str(f))+ key = next(iter(svc._clients))+ first_used = svc._last_used[key]++ # Age the timestamp past the cutoff, then re-acquire the client.+ svc._last_used[key] = first_used - 120.0+ svc.get_diagnostics_sync(str(f))+ assert svc._last_used[key] > first_used - 120.0, (+ "re-acquiring a cached client must refresh _last_used"+ )++ # A sweep right after reuse must keep the client.+ svc._loop.run(svc._reap_idle_once(), timeout=5.0)+ assert key in svc._clients+ assert svc.get_status()["clients"]+ finally:+ svc.shutdown()+++def test_reaper_survives_sweep_error(mock_pyright):+ """One failing sweep must not kill the reaper loop — the loop's+ ``except Exception`` guard must swallow the error and keep sweeping."""+ repo = mock_pyright+ f = repo / "x.py"+ f.write_text("")+ svc = LSPService(+ enabled=True,+ wait_mode="document",+ wait_timeout=3.0,+ install_strategy="manual",+ idle_timeout=0.1,+ )+ try:+ # Sabotage the sweep itself so the reaper-loop except branch+ # actually runs (a failing client.shutdown() would be swallowed+ # by gather(return_exceptions=True) and never reach the loop).+ calls = {"n": 0}+ real_reap = svc._reap_idle_once++ async def _flaky_reap():+ calls["n"] += 1+ if calls["n"] == 1:+ raise RuntimeError("sweep sabotage")+ await real_reap()++ svc._reap_idle_once = _flaky_reap # type: ignore[method-assign]++ svc.get_diagnostics_sync(str(f))+ assert svc.get_status()["clients"]++ # First sweep raises; later sweeps must still reap the client.+ deadline = time.monotonic() + 3.0+ while svc.get_status()["clients"] and time.monotonic() < deadline:+ time.sleep(0.02)++ assert calls["n"] >= 2, "reaper loop died after the failing sweep"+ assert svc.get_status()["clients"] == []+ assert svc._idle_reaper_task is not None+ assert not svc._idle_reaper_task.done()+ finally:+ svc.shutdown()+++def test_create_from_config_reads_idle_timeout(monkeypatch):+ """``lsp.idle_timeout`` in config.yaml reaches the service."""+ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"lsp": {"enabled": False, "idle_timeout": 42}},+ )+ svc = LSPService.create_from_config()+ assert svc is not None+ assert svc._idle_timeout == 42.0+++def test_create_from_config_invalid_idle_timeout_falls_back(monkeypatch):+ from agent.lsp.manager import DEFAULT_IDLE_TIMEOUT++ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"lsp": {"enabled": False, "idle_timeout": "not-a-number"}},+ )+ svc = LSPService.create_from_config()+ assert svc is not None+ assert svc._idle_timeout == DEFAULT_IDLE_TIMEOUT+++def test_create_from_config_clamps_tiny_idle_timeout(monkeypatch):+ """Sub-floor timeouts are clamped (mid-flight reap could otherwise+ escalate an outer timeout into a permanent broken-set entry); 0 still+ means disabled and is not clamped."""+ from agent.lsp.manager import MIN_IDLE_TIMEOUT++ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"lsp": {"enabled": False, "idle_timeout": 2}},+ )+ svc = LSPService.create_from_config()+ assert svc is not None+ assert svc._idle_timeout == MIN_IDLE_TIMEOUT++ monkeypatch.setattr(+ "hermes_cli.config.load_config",+ lambda: {"lsp": {"enabled": False, "idle_timeout": 0}},+ )+ svc = LSPService.create_from_config()+ assert svc is not None+ assert svc._idle_timeout == 0+++def test_default_config_declares_idle_timeout():+ """The canonical default in DEFAULT_CONFIG matches the manager constant+ so config discovery surfaces the knob with the real default value."""+ from agent.lsp.manager import DEFAULT_IDLE_TIMEOUT+ from hermes_cli.config import DEFAULT_CONFIG++ assert float(DEFAULT_CONFIG["lsp"]["idle_timeout"]) == float(DEFAULT_IDLE_TIMEOUT)diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.mdindex 25dce057c0f..8f5830f4791 100644--- a/website/docs/user-guide/features/lsp.md+++ b/website/docs/user-guide/features/lsp.md@@ -164,6 +164,13 @@ lsp:# manual — only use binaries already on PATHinstall_strategy: auto+ # How long an unused language-server client stays alive (seconds).+ # Idle servers are shut down automatically and respawned on the next+ # relevant file operation. Set to 0 to disable idle reaping and keep+ # servers alive for the life of the process. Values below 30s are+ # clamped to 30 so a sweep can never reap a client mid-operation.+ idle_timeout: 600+# Per-server overrides (all optional).servers:pyright:@@ -222,9 +229,13 @@ answered after it). Slow servers that haven't re-checked yet resultin "no data" for that edit — never in yesterday's errors beingre-reported as current.-Servers are kept alive for the life of the Hermes process. There's-no idle-timeout reaper — the cost of restarting the server's index-on every write would be far higher than holding the daemon.+Servers are kept alive while they're being used and shut down after+`lsp.idle_timeout` seconds (default 600) with no file activity — a+long-running gateway that touches many worktrees no longer accumulates+one language-server process per workspace forever. A reaped server is+respawned automatically on the next relevant file operation. Set+`idle_timeout: 0` to disable reaping and hold every server's index warm+for the life of the process.## Disabling