Skip to content

The agent that grows with you

fix(lsp): one stalled request no longer silences a workspace for good — retry window, cold-root warm-up budget, per-root exclusion

teknium1c54527256832
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 17ee377f84a..e18bb3e190c 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -15,7 +15,7 @@ from __future__ import annotations
import logging
import os
import threading
-from typing import List, Tuple
+from typing import List, Optional, Tuple
# Dedicated logger name so the documented grep recipe survives any
# ``logging.getLogger(__name__)`` rename of internal modules.
@@ -27,7 +27,8 @@ _announced_active: set = set() # keys: (server_id, workspace_root)
_announced_unavailable: set = set() # keys: (server_id, binary_path_or_name)
_announced_no_root: set = set() # keys: (server_id, file_path)
_announced_skipped: set = set() # keys: (server_id, workspace_root)
-_ALL_BUCKETS = (_announced_active, _announced_unavailable, _announced_no_root, _announced_skipped)
+_announced_excluded: set = set() # keys: (server_id, workspace_root)
+_ALL_BUCKETS = (_announced_active, _announced_unavailable, _announced_no_root, _announced_skipped, _announced_excluded)
def _short_path(file_path: str) -> str:
@@ -112,15 +113,26 @@ def log_spawn_failed(server_id: str, workspace_root: str, exc: BaseException) ->
_emit(server_id, logging.WARNING, f"spawn/initialize failed for {workspace_root}: {type(exc).__name__}: {exc}")
-def log_skipped_broken(server_id: str, workspace_root: str, file_path: str) -> None:
+def log_skipped_broken(server_id: str, workspace_root: str, file_path: str, retry_in: Optional[float] = None) -> None:
"""A request was skipped because ``(server_id, root)`` is marked broken. INFO once per root, then DEBUG:
- at default log levels a skipped file and a clean file otherwise look identical (``log_clean`` is DEBUG)."""
+ at default log levels a skipped file and a clean file otherwise look identical (``log_clean`` is DEBUG).
+ ``retry_in`` (seconds, from ``lsp.broken_retry_seconds``) names when the pair gets another try."""
+ until = f"retry in {retry_in:.0f}s" if retry_in is not None else "no diagnostics for this root until restart"
_emit_once(_announced_skipped, (server_id, workspace_root), server_id, logging.INFO,
- f"skipping {_short_path(file_path)}: {workspace_root} marked broken after an earlier failure "
- "(no diagnostics for this root until restart)",
+ f"skipping {_short_path(file_path)}: {workspace_root} marked broken after an earlier failure ({until})",
f"skipping {_short_path(file_path)}: {workspace_root} marked broken")
+def log_root_excluded(server_id: str, workspace_root: str, file_path: str, *, invalid: bool = False) -> None:
+ """``workspace_root`` matches ``lsp.exclude_roots`` (or the key is malformed and every root is skipped).
+ INFO once per root — a deliberate gate must still be visible, or an excluded file looks like a clean one —
+ DEBUG thereafter."""
+ why = "lsp.exclude_roots is not a list (fix the key)" if invalid else "matches lsp.exclude_roots"
+ _emit_once(_announced_excluded, (server_id, workspace_root), server_id, logging.INFO,
+ f"skipping {_short_path(file_path)}: {workspace_root} {why}",
+ f"skipping {_short_path(file_path)}: {workspace_root} excluded")
+
+
def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None:
"""Idle clients were reaped. INFO, one line per sweep.
@@ -151,7 +163,7 @@ def reset_announce_caches() -> None:
__all__ = [
"event_log", "log_clean", "log_disabled", "log_active", "log_diagnostics", "log_no_project_root",
- "log_server_unavailable", "log_timeout", "log_server_error", "log_spawn_failed", "log_skipped_broken", "log_reaped",
+ "log_server_unavailable", "log_timeout", "log_server_error", "log_spawn_failed", "log_skipped_broken", "log_root_excluded", "log_reaped",
"reset_announce_caches",
]
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index 34306cce6af..fb4a7180d23 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -5,14 +5,16 @@
spawned client per ``(server_id, workspace_root)`` — servers flagged ``multi_root`` (pyright) get ONE
client per ``server_id`` and further roots (typically sibling git worktrees) are attached to the running
process via ``workspace/didChangeWorkspaceFolders`` — a **broken-set** of pairs that failed
-to spawn/initialize (never retried for the life of the service), and a **delta baseline**
+to spawn/initialize (retried only after ``lsp.broken_retry_seconds``; never, by default), and a **delta baseline**
per file (``snapshot_baseline()`` runs BEFORE a write; the next ``get_diagnostics_sync()``
returns only diagnostics not in it). Off unless config enables it.
"""
from __future__ import annotations
import asyncio
+import fnmatch
import logging
+import math
import os
import threading
import time
@@ -33,6 +35,27 @@ _Key = Tuple[str, str]
_Diags = List[Dict[str, Any]]
+def _float_or(value: Any, default: float) -> float:
+ try:
+ return float(value) if value is not None else default
+ except (TypeError, ValueError):
+ return default
+
+
+def _parse_exclude_roots(value: Any) -> Optional[List[str]]:
+ """Normalise ``lsp.exclude_roots``; ``None`` (fail closed) with a WARNING for a non-list value."""
+ if value is None:
+ return []
+ if not isinstance(value, list) or not all(isinstance(p, str) for p in value):
+ eventlog.event_log.warning(
+ "lsp.exclude_roots must be a list of glob patterns, e.g. ['~/big-monorepo', '/srv/*/vendor'] "
+ "(got %s); LSP is skipped for every workspace until the key is fixed",
+ type(value).__name__,
+ )
+ return None
+ return [os.path.expanduser(p) for p in value if p]
+
+
def _client_key(srv: ServerDef, root: str) -> _Key:
"""Cache key for the client serving ``root``: multi-root servers share one process per
``server_id``; everything else is keyed per resolved project root."""
@@ -105,6 +128,9 @@ class LSPService:
disabled_servers: Optional[List[str]] = None,
idle_timeout: float = DEFAULT_IDLE_TIMEOUT,
extra_servers: Optional[List[ServerDef]] = None,
+ broken_retry_seconds: float = 0.0,
+ warmup_timeout: float = 0.0,
+ exclude_roots: Any = None,
) -> None:
self._enabled = enabled
self._wait_mode = wait_mode if wait_mode in {"document", "full"} else "document"
@@ -116,6 +142,12 @@ class LSPService:
self._disabled_servers = set(disabled_servers or [])
self._idle_timeout = idle_timeout
self._extra_servers: List[ServerDef] = list(extra_servers or [])
+ self._broken_retry = max(0.0, broken_retry_seconds)
+ self._warmup_timeout = max(0.0, warmup_timeout)
+ # ``None`` = misconfigured → fail closed (every root excluded) until the user fixes the key: a
+ # bare string here means "exclude that workspace", and excluding nothing would re-pay the stall it
+ # was meant to avoid.
+ self._exclude_roots: Optional[List[str]] = _parse_exclude_roots(exclude_roots)
self._loop = _BackgroundLoop()
if self._enabled:
@@ -123,7 +155,8 @@ class LSPService:
# Per-(server_id, workspace_root) state
self._clients: Dict[_Key, LSPClient] = {}
- self._broken: set = set()
+ # (server_id, root) → monotonic deadline after which the pair may be retried (inf = lifetime).
+ self._broken: Dict[_Key, float] = {}
self._spawning: Dict[_Key, asyncio.Future] = {}
self._last_used: Dict[_Key, float] = {}
self._state_lock = threading.Lock()
@@ -169,6 +202,9 @@ class LSPService:
disabled_servers=[n for n, c in servers.items() if c.get("disabled")],
idle_timeout=idle_timeout,
extra_servers=custom_servers(servers),
+ broken_retry_seconds=_float_or(lsp_cfg.get("broken_retry_seconds"), 0.0),
+ warmup_timeout=_float_or(lsp_cfg.get("warmup_timeout"), 0.0),
+ exclude_roots=lsp_cfg.get("exclude_roots"),
)
def _server_for(self, file_path: str) -> Optional[ServerDef]:
@@ -209,11 +245,51 @@ class LSPService:
key = self._broken_key(srv, file_path)
if key is None:
return False
- if key in self._broken:
- eventlog.log_skipped_broken(srv.server_id, key[1], file_path)
+ if self._root_excluded(key[1]):
+ eventlog.log_root_excluded(srv.server_id, key[1], file_path, invalid=self._exclude_roots is None)
+ return False
+ if self._is_broken(key):
+ eventlog.log_skipped_broken(srv.server_id, key[1], file_path, retry_in=self._broken_retry_in(key))
return False
return True
+ def _root_excluded(self, root: str) -> bool:
+ """True iff ``root`` matches an ``lsp.exclude_roots`` glob (or the key is misconfigured)."""
+ if self._exclude_roots is None:
+ return True
+ return any(fnmatch.fnmatchcase(root, pat) or fnmatch.fnmatchcase(root, pat.rstrip(os.sep) + os.sep + "*")
+ for pat in self._exclude_roots)
+
+ def _is_broken(self, key: _Key) -> bool:
+ """Broken-set membership; an entry whose retry deadline passed is dropped so the pair gets one more try."""
+ deadline = self._broken.get(key)
+ if deadline is None:
+ return False
+ if time.monotonic() >= deadline:
+ self._broken.pop(key, None)
+ return False
+ return True
+
+ def _broken_retry_in(self, key: _Key) -> Optional[float]:
+ deadline = self._broken.get(key, math.inf)
+ return None if math.isinf(deadline) else max(0.0, deadline - time.monotonic())
+
+ def _mark_broken(self, key: _Key) -> None:
+ self._broken[key] = time.monotonic() + self._broken_retry if self._broken_retry > 0 else math.inf
+
+ def _wait_budget(self, file_path: str) -> float:
+ """``wait_timeout`` for a root with a running client; ``max(wait_timeout, warmup_timeout)`` for a
+ cold root, whose first request also pays the spawn/initialize and the server's initial program build."""
+ if self._warmup_timeout <= self._wait_timeout:
+ return self._wait_timeout
+ srv = self._server_for(file_path)
+ key = self._broken_key(srv, file_path) if srv is not None else None
+ if key is None:
+ return self._wait_timeout
+ with self._state_lock:
+ client = self._clients.get(_client_key(srv, key[1]))
+ return self._wait_timeout if client is not None and client.is_running else self._warmup_timeout
+
def snapshot_baseline(self, file_path: str) -> None:
"""Snapshot current diagnostics for ``file_path`` as the delta baseline (call BEFORE a write).
Best-effort: failures are swallowed so a flaky server can't break a write, but they mark the pair broken."""
@@ -222,8 +298,9 @@ class LSPService:
try:
# Outer join budget must exceed the inner wait or a slow-but-alive server gets falsely
# marked broken; it is a ceiling only — the inner wait returns as soon as it completes.
- t = max(DIAGNOSTICS_DOCUMENT_WAIT + 3.0, self._wait_timeout + 3.0)
- diags = self._loop.run(self._snapshot_async(file_path), timeout=t)
+ budget = self._wait_budget(file_path)
+ t = max(DIAGNOSTICS_DOCUMENT_WAIT + 3.0, budget + 3.0)
+ diags = self._loop.run(self._snapshot_async(file_path, budget), timeout=t)
except Exception as e: # noqa: BLE001
logger.debug("baseline snapshot failed for %s: %s", file_path, e)
self._mark_broken_for_file(file_path, e)
@@ -254,8 +331,9 @@ class LSPService:
return []
server_id = self._server_for(file_path).server_id # enabled_for guarantees a match
try:
- t = timeout if timeout is not None else self._wait_timeout + 2.0
- diags = self._loop.run(self._open_and_wait_async(file_path), timeout=t)
+ budget = self._wait_budget(file_path)
+ t = timeout if timeout is not None else budget + 2.0
+ diags = self._loop.run(self._open_and_wait_async(file_path, budget=budget), timeout=t)
except Exception as e: # noqa: BLE001
if isinstance(e, asyncio.TimeoutError):
eventlog.log_timeout(server_id, file_path)
@@ -308,8 +386,8 @@ class LSPService:
key = self._broken_key(srv, file_path) if srv is not None else None
if key is None:
return
- already_broken = key in self._broken
- self._broken.add(key)
+ already_broken = self._is_broken(key)
+ self._mark_broken(key)
ckey = _client_key(srv, key[1])
with self._state_lock:
client = self._clients.pop(ckey, None)
@@ -342,25 +420,30 @@ class LSPService:
"workspace_folders": list(c.workspace_folders), "state": c.state, "running": c.is_running}
for c in self._clients.values()
]
- broken = list(self._broken)
+ broken = [key for key, deadline in self._broken.items() if time.monotonic() < deadline]
return {
"enabled": self._enabled, "wait_mode": self._wait_mode, "wait_timeout": self._wait_timeout,
"install_strategy": self._install_strategy, "clients": clients, "broken": broken,
"disabled_servers": sorted(self._disabled_servers),
+ "broken_retry_seconds": self._broken_retry, "warmup_timeout": self._warmup_timeout,
+ "exclude_roots": list(self._exclude_roots) if self._exclude_roots is not None else "INVALID",
}
# ---- async internals ----
- async def _snapshot_async(self, file_path: str) -> _Diags:
+ async def _snapshot_async(self, file_path: str, budget: Optional[float] = None) -> _Diags:
# No fresh data for the pre-edit content → empty baseline. Safe: the delta
# filter then removes less, never more. Never seed from stale stores.
- return await self._open_and_wait_async(file_path, snapshot=True) or []
+ return await self._open_and_wait_async(file_path, snapshot=True, budget=budget) or []
- async def _open_and_wait_async(self, file_path: str, *, snapshot: bool = False) -> Optional[_Diags]:
+ async def _open_and_wait_async(
+ self, file_path: str, *, snapshot: bool = False, budget: Optional[float] = None,
+ ) -> Optional[_Diags]:
"""Open + wait for FRESH diagnostics: ``[]`` = checked clean, ``None`` = no verdict in budget.
- Callers must not substitute stale data for either. ``snapshot`` mode
- (pre-write baseline) skips didSave; both modes wait at most ``lsp.wait_timeout``.
+ Callers must not substitute stale data for either. ``snapshot`` mode (pre-write baseline)
+ skips didSave; both modes wait at most ``budget`` (``lsp.wait_timeout`` unless the caller
+ computed a cold-root warm-up budget via :meth:`_wait_budget`).
"""
client = await self._get_or_spawn(file_path)
if client is None:
@@ -371,7 +454,8 @@ class LSPService:
if not snapshot:
await client.save_file(file_path)
fresh = await client.wait_for_diagnostics(
- file_path, version, mode=self._wait_mode, timeout=self._wait_timeout,
+ file_path, version, mode=self._wait_mode,
+ timeout=budget if budget is not None else self._wait_timeout,
)
except Exception as e: # noqa: BLE001
if snapshot:
@@ -411,7 +495,7 @@ class LSPService:
if root is None:
eventlog.log_disabled(srv.server_id, file_path, "exclude marker hit (server gated off)")
return None
- if (srv.server_id, root) in self._broken:
+ if self._is_broken((srv.server_id, root)):
return None
key = _client_key(srv, root)
with self._state_lock:
@@ -436,7 +520,7 @@ class LSPService:
try:
client = await self._spawn_client(srv, root)
if client is None:
- self._broken.add((srv.server_id, root))
+ self._mark_broken((srv.server_id, root))
else:
with self._state_lock:
self._clients[key] = client
@@ -538,7 +622,7 @@ class LSPService:
# once the future resolves the client is in ``_clients`` and the pass below sees it).
with self._state_lock:
pending = [fut for fut in self._spawning.values() if not fut.done()]
- self._broken = {key for key in self._broken if not _under(key[1])}
+ self._broken = {key: deadline for key, deadline in self._broken.items() if not _under(key[1])}
for path in [p for p in self._delta_baseline if _under(p)]:
del self._delta_baseline[path]
if pending:
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 9b9a2e6acdc..9a7714c8878 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -2319,6 +2319,19 @@ DEFAULT_CONFIG = {
# request workspace-wide diagnostics (slower).
"wait_mode": "document",
"wait_timeout": 5.0,
+ # Budget for the FIRST request against a workspace whose server is not running yet (spawn +
+ # initialize + the server's initial program build; tsserver on a large project can need a
+ # minute). Once the client is up, wait_timeout applies again. 0 = same as wait_timeout.
+ "warmup_timeout": 0.0,
+ # After a server fails (spawn error or outer timeout) its (server, workspace root) pair is
+ # skipped. 0 = for the process lifetime (until `hermes lsp restart`); N = retried after N
+ # seconds, so one transient stall does not silence a workspace forever.
+ "broken_retry_seconds": 0.0,
+ # Workspace roots (glob patterns, ~ expanded; a bare path also matches everything under
+ # it) where no language server runs at all, e.g. one huge monorepo whose server cannot
+ # finish in budget, while every other workspace keeps its diagnostics. Must be a list —
+ # any other shape logs a warning and skips LSP for every workspace until fixed.
+ "exclude_roots": [],
# Missing server binaries: auto = install via npm/go/pip into <HERMES_HOME>/lsp/bin/ on
# first use; manual = only binaries on PATH; off = alias for manual.
"install_strategy": "auto",
diff --git a/tests/agent/lsp/test_broken_set.py b/tests/agent/lsp/test_broken_set.py
index 1b8839e8b7a..6762d368d03 100644
--- a/tests/agent/lsp/test_broken_set.py
+++ b/tests/agent/lsp/test_broken_set.py
@@ -14,6 +14,7 @@ This module verifies:
"""
from __future__ import annotations
+import time
from pathlib import Path
from unittest.mock import patch
@@ -35,7 +36,7 @@ def _make_git_workspace(tmp_path: Path) -> Path:
repo = tmp_path / "repo"
repo.mkdir()
(repo / ".git").mkdir()
- (repo / "pyproject.toml").write_text("[project]\nname='t'\n")
+ (repo / "pyproject.toml").write_text("[project]\nname='t'\n", encoding="utf-8")
return repo
@@ -51,11 +52,11 @@ def test_unrelated_project_not_affected_by_broken(tmp_path, monkeypatch):
repo_b = tmp_path / "repo-b"
repo_b.mkdir()
(repo_b / ".git").mkdir()
- (repo_b / "pyproject.toml").write_text("[project]\nname='b'\n")
+ (repo_b / "pyproject.toml").write_text("[project]\nname='b'\n", encoding="utf-8")
a_src = repo_a / "x.py"
- a_src.write_text("")
+ a_src.write_text("", encoding="utf-8")
b_src = repo_b / "x.py"
- b_src.write_text("")
+ b_src.write_text("", encoding="utf-8")
monkeypatch.chdir(str(repo_a))
svc = LSPService(
@@ -80,7 +81,7 @@ def test_unrelated_project_not_affected_by_broken(tmp_path, monkeypatch):
def test_mark_broken_handles_no_workspace_silently(tmp_path):
"""File outside any git worktree → no workspace → no key to add."""
src = tmp_path / "orphan.py"
- src.write_text("")
+ src.write_text("", encoding="utf-8")
svc = LSPService(
enabled=True,
wait_mode="document",
@@ -101,7 +102,7 @@ def test_snapshot_failure_marks_broken_via_outer_timeout(tmp_path, monkeypatch):
repo = _make_git_workspace(tmp_path)
monkeypatch.chdir(str(repo))
src = repo / "x.py"
- src.write_text("")
+ src.write_text("", encoding="utf-8")
svc = LSPService(
enabled=True,
@@ -133,7 +134,7 @@ def test_skipped_request_on_broken_root_is_logged_at_info(tmp_path, monkeypatch,
repo = _make_git_workspace(tmp_path)
src = repo / "x.py"
- src.write_text("")
+ src.write_text("", encoding="utf-8")
monkeypatch.chdir(str(repo))
eventlog.reset_announce_caches()
svc = LSPService(enabled=True, wait_mode="document", wait_timeout=2.0, install_strategy="manual")
@@ -147,3 +148,30 @@ def test_skipped_request_on_broken_root_is_logged_at_info(tmp_path, monkeypatch,
skipped = [r for r in caplog.records if "marked broken" in r.getMessage()]
assert [r.levelname for r in skipped] == ["INFO"] # once per root; the repeat is DEBUG
assert str(repo) in skipped[0].getMessage() and "x.py" in skipped[0].getMessage()
+
+
+def test_broken_root_is_retried_after_broken_retry_seconds(tmp_path, monkeypatch):
+ """With ``lsp.broken_retry_seconds`` set, a root poisoned by one outer-timeout failure on the pre-write
+ path is re-tried once the window passes instead of staying dark for the process lifetime (#116446).
+ The default (0) keeps the lifetime behaviour."""
+ repo = _make_git_workspace(tmp_path)
+ monkeypatch.chdir(str(repo))
+ src = repo / "x.py"
+ src.write_text("", encoding="utf-8")
+ cfg = {"lsp": {"wait_timeout": 1.0, "install_strategy": "manual", "broken_retry_seconds": 0.2}}
+ with patch("hermes_cli.config.load_config_readonly", return_value=cfg):
+ svc = LSPService.create_from_config()
+ assert svc is not None
+ try:
+ async def boom(*_a, **_k):
+ raise RuntimeError("outer-timeout simulated")
+
+ with patch.object(svc, "_snapshot_async", boom):
+ svc.snapshot_baseline(str(src))
+ assert svc.enabled_for(str(src)) is False
+ assert ("pyright", str(repo)) in svc.get_status()["broken"]
+ time.sleep(0.3)
+ assert svc.enabled_for(str(src)) is True
+ assert svc.get_status()["broken"] == []
+ finally:
+ svc.shutdown()
diff --git a/tests/agent/lsp/test_root_policy.py b/tests/agent/lsp/test_root_policy.py
new file mode 100644
index 00000000000..5e420dd5db1
--- /dev/null
+++ b/tests/agent/lsp/test_root_policy.py
@@ -0,0 +1,121 @@
+"""Per-root policy knobs of :class:`LSPService` (#116446): ``lsp.exclude_roots`` gates a workspace off
+without disabling the server fleet-wide, and ``lsp.warmup_timeout`` gives a cold root one long wait
+instead of the steady-state budget. Both are driven through ``create_from_config`` and the production
+pre-write / post-write entry points, never through the helpers.
+"""
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import patch
+
+import pytest
+
+from agent.lsp import eventlog
+from agent.lsp.manager import LSPService, _client_key
+from agent.lsp.servers import find_server_for_file
+from agent.lsp.workspace import clear_cache
+
+
[email protected](autouse=True)
+def _clear_caches():
+ clear_cache()
+ eventlog.reset_announce_caches()
+ yield
+ clear_cache()
+
+
+def _git_repo(tmp_path: Path, name: str) -> Path:
+ repo = tmp_path / name
+ repo.mkdir()
+ (repo / ".git").mkdir()
+ (repo / "pyproject.toml").write_text("[project]\nname='t'\n", encoding="utf-8")
+ (repo / "x.py").write_text("", encoding="utf-8")
+ return repo
+
+
+def _service_from(lsp_cfg: dict) -> LSPService:
+ with patch("hermes_cli.config.load_config_readonly", return_value={"lsp": lsp_cfg}):
+ svc = LSPService.create_from_config()
+ assert svc is not None
+ return svc
+
+
+def test_exclude_roots_skips_matching_root_only(tmp_path, monkeypatch, caplog):
+ """A root matching ``lsp.exclude_roots`` never reaches the server — the pre-write snapshot does not
+ spawn or wait — while a sibling workspace keeps its diagnostics. A non-list value fails closed
+ (every root skipped) with a WARNING naming the expected shape instead of silently excluding nothing."""
+ big = _git_repo(tmp_path, "big")
+ small = _git_repo(tmp_path, "small")
+ monkeypatch.chdir(str(tmp_path))
+ svc = _service_from({"wait_timeout": 1.0, "install_strategy": "manual",
+ "exclude_roots": [str(tmp_path / "bi*")]})
+ try:
+ async def must_not_run(*_a, **_k):
+ raise AssertionError("excluded root reached the server")
+
+ with patch.object(svc, "_snapshot_async", must_not_run), caplog.at_level("INFO", logger=eventlog.event_log.name):
+ svc.snapshot_baseline(str(big / "x.py"))
+ assert svc.enabled_for(str(big / "x.py")) is False
+ assert svc.enabled_for(str(small / "x.py")) is True
+ assert any("exclude_roots" in r.getMessage() and str(big) in r.getMessage() for r in caplog.records)
+ finally:
+ svc.shutdown()
+
+ with caplog.at_level("WARNING", logger=eventlog.event_log.name):
+ bad = _service_from({"install_strategy": "manual", "exclude_roots": str(big)})
+ try:
+ assert bad.enabled_for(str(small / "x.py")) is False
+ warned = [r for r in caplog.records if r.levelno >= 30 and "exclude_roots" in r.getMessage()]
+ assert warned and "list" in warned[0].getMessage() and "str" in warned[0].getMessage()
+ finally:
+ bad.shutdown()
+
+
+def test_warmup_timeout_applies_to_cold_root_only(tmp_path, monkeypatch):
+ """The first request against a root with no running client waits up to ``lsp.warmup_timeout``;
+ once the client is up the steady-state ``wait_timeout`` applies again (#116446: a 55 s cold build
+ was being cut off at the 5 s steady-state budget, then the root was poisoned)."""
+ repo = _git_repo(tmp_path, "repo")
+ src = repo / "x.py"
+ monkeypatch.chdir(str(repo))
+ svc = _service_from({"wait_timeout": 1.0, "warmup_timeout": 30.0, "install_strategy": "manual"})
+ budgets: list = []
+
+ class FakeClient:
+ server_id = "pyright"
+ workspace_root = str(repo)
+ workspace_folders = (str(repo),)
+ state = "running"
+ is_running = True
+
+ async def open_file(self, *_a, **_k):
+ return 1
+
+ async def save_file(self, *_a, **_k):
+ return None
+
+ async def wait_for_diagnostics(self, *_a, timeout=None, **_k):
+ budgets.append(timeout)
+ return True
+
+ def diagnostics_for(self, *_a, **_k):
+ return []
+
+ async def shutdown(self):
+ return None
+
+ fake = FakeClient()
+
+ async def spawn(_path):
+ return fake
+
+ try:
+ with patch.object(svc, "_get_or_spawn", spawn):
+ svc.snapshot_baseline(str(src)) # cold: no client registered for the root yet
+ key = _client_key(find_server_for_file(str(src)), str(repo))
+ with svc._state_lock:
+ svc._clients[key] = fake
+ assert svc.get_diagnostics_sync(str(src)) == [] # warm
+ finally:
+ svc.shutdown()
+ assert budgets == [30.0, 1.0]
diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.py
index d3bf9e1abf5..fcfa9d1797f 100644
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@ -2017,6 +2017,18 @@ def test_empty_dict_default_sections_are_open_containers():
assert suggestion == "compression.model_thresholds"
+def test_lsp_root_policy_keys_are_recognized_and_off_by_default():
+ """``lsp.warmup_timeout`` / ``broken_retry_seconds`` / ``exclude_roots`` (#116446) must be settable via
+ ``hermes config set`` and must default to today's behaviour (no grace, lifetime broken set, no exclusion)."""
+ from hermes_cli.config import _validate_config_key
+ from hermes_cli.config_defaults import DEFAULT_CONFIG
+ assert DEFAULT_CONFIG["lsp"]["warmup_timeout"] == 0.0
+ assert DEFAULT_CONFIG["lsp"]["broken_retry_seconds"] == 0.0
+ assert DEFAULT_CONFIG["lsp"]["exclude_roots"] == []
+ for key in ("lsp.warmup_timeout", "lsp.broken_retry_seconds", "lsp.exclude_roots"):
+ assert _validate_config_key(key) == (True, None)
+
+
class TestSaveConfigExplicitPathAuthority:
"""#113301: the explicit-path evidence that keeps user-set defaults through the strip pass
must come from the fail-closed read, not from a second cached read that can yield ``{}``."""
diff --git a/website/docs/user-guide/features/lsp.md b/website/docs/user-guide/features/lsp.md
index 0a77a35e771..77847baebe6 100644
--- a/website/docs/user-guide/features/lsp.md
+++ b/website/docs/user-guide/features/lsp.md
@@ -188,6 +188,30 @@ lsp:
# projects (tsserver, rust-analyzer mid-indexing).
wait_timeout: 5.0
+ # Budget for the FIRST request against a workspace whose server is
+ # not running yet — spawn, initialize and the server's initial program
+ # build all happen inside it (tsserver on a 10k-file project can need
+ # a minute). Once the client is up, wait_timeout applies again.
+ # 0 = no extra grace (same as wait_timeout).
+ warmup_timeout: 0
+
+ # After a server fails for a workspace (spawn error, or the request
+ # outran its budget) that (server, root) pair is skipped. 0 = for the
+ # rest of the process (until `hermes lsp restart`); N = retried after
+ # N seconds, so one transient stall does not silence a workspace
+ # forever. Skips are logged once per root at INFO with the retry time.
+ broken_retry_seconds: 0
+
+ # Workspace roots where no language server runs at all — glob
+ # patterns matched against the resolved project root (~ expanded; a
+ # bare path also matches everything beneath it). Use it for the one
+ # huge monorepo whose server cannot finish in budget while every other
+ # workspace keeps its diagnostics — unlike servers.<id>.disabled,
+ # which switches the server off everywhere. Must be a list; any other
+ # shape logs a warning and skips LSP for every workspace until fixed.
+ exclude_roots: []
+ # exclude_roots: ["~/work/huge-monorepo", "/srv/checkouts/*/vendor"]
+
# How to handle missing server binaries.
# auto — install via npm/pip/go install into <HERMES_HOME>/lsp/bin
# manual — only use binaries already on PATH
@@ -292,6 +316,21 @@ tens of milliseconds for pyright/tsserver and a few seconds for
rust-analyzer mid-indexing. Each edit waits twice (a pre-edit
baseline snapshot for the delta, then the post-edit re-check), so a
server that never answers costs at most `2 × wait_timeout` per edit.
+The very first request against a workspace also pays the spawn and the
+server's initial program build; give large projects room with
+`lsp.warmup_timeout` (only that first, cold request uses it — the
+steady-state budget is unchanged) rather than raising `wait_timeout`,
+which would let every later edit block for the cold-build duration.
+
+A server that fails for a workspace — spawn error, or a request that
+outran its budget — marks that `(server, root)` pair broken and every
+later request for it is skipped (logged once per root at INFO). By
+default the pair stays broken until `hermes lsp restart` or process
+exit; `lsp.broken_retry_seconds: N` retries it after N seconds so one
+transient stall does not cost the workspace its diagnostics for good.
+A root you never want served — one monorepo whose server cannot finish
+in any budget — goes in `lsp.exclude_roots`; other workspaces keep
+their servers.
Diagnostics are **freshness-gated**: a result only counts when the
server produced it for the content of the current edit (a