Skip to content

The agent that grows with you

fix(lsp): cap the workspace-root cache and the eventlog announce buckets (#62950)

teknium11c21a5025437
diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py
index 0a8d3b19318..ef9cad99c6b 100644
--- a/agent/lsp/eventlog.py
+++ b/agent/lsp/eventlog.py
@@ -6,7 +6,9 @@ skipped, repeat "no project root" / "server unavailable"); INFO for once-per-ses
transitions (first ``active for <root>``, first ``no project root`` per file) and every
diagnostic event; WARNING for action-required failures (first ``server unavailable`` per
(server_id, binary), every timeout / unexpected error). Dedup uses module-level sets bounded
-by the distinct pairs touched in one process — a bounded LRU would re-fire suppressed lines.
+by the distinct pairs touched in one process, each capped at ``_ANNOUNCE_CAP`` keys: past it the
+bucket resets and the first-seen line re-fires once, so per-file keys can't grow for the life of
+a gateway process (#62950).
"""
from __future__ import annotations
@@ -20,6 +22,7 @@ from typing import List, Tuple
event_log = logging.getLogger("hermes.lint.lsp")
_announce_lock = threading.Lock()
+_ANNOUNCE_CAP = 512
_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)
@@ -47,6 +50,8 @@ def _emit_once(bucket: set, key: Tuple, server_id: str, level: int, first: str,
"""Log *first* at *level* the first time *key* is seen, *repeat* at DEBUG thereafter."""
with _announce_lock:
is_first = key not in bucket
+ if is_first and len(bucket) >= _ANNOUNCE_CAP:
+ bucket.clear()
bucket.add(key)
_emit(server_id, level if is_first else logging.DEBUG, first if is_first else repeat)
diff --git a/agent/lsp/workspace.py b/agent/lsp/workspace.py
index 8543c35135a..b1115d5ec94 100644
--- a/agent/lsp/workspace.py
+++ b/agent/lsp/workspace.py
@@ -15,8 +15,10 @@ from typing import Iterable, Iterator, Optional, Tuple
logger = logging.getLogger("agent.lsp.workspace")
-# Cache: start dir → (worktree_root, is_git) so repeated calls don't re-stat. Cleared on shutdown.
+# Cache: start dir → (worktree_root, is_git) so repeated calls don't re-stat. Cleared on shutdown; capped
+# because every distinct file dir a long gateway session touches lands here (#62950).
_workspace_cache: dict = {}
+_WORKSPACE_CACHE_CAP = 512
# Walk cap: the deepest reasonable monorepo is well under 64 levels; bounds a
# pathological cwd or symlink cycle even though parent-equality normally stops us.
@@ -60,16 +62,18 @@ def find_git_worktree(start: str) -> Optional[str]:
cached = _workspace_cache.get(str(start_path))
if cached is not None:
return cached[0]
+ resolved = None
for cur in _walk_up(start_path):
try:
if (cur / ".git").exists():
resolved = str(cur)
- _workspace_cache[str(start_path)] = (resolved, True)
- return resolved
+ break
except OSError:
break # permission error on a parent dir — bail out cleanly
- _workspace_cache[str(start_path)] = (None, False)
- return None
+ _workspace_cache[str(start_path)] = (resolved, resolved is not None)
+ if len(_workspace_cache) > _WORKSPACE_CACHE_CAP:
+ _workspace_cache.clear() # a stat cache: resetting is a few re-stats, and one atomic op is thread-safe
+ return resolved
def is_inside_workspace(path: str, workspace_root: str) -> bool:
diff --git a/tests/agent/lsp/test_eventlog.py b/tests/agent/lsp/test_eventlog.py
index e0de352d475..d7016c43db5 100644
--- a/tests/agent/lsp/test_eventlog.py
+++ b/tests/agent/lsp/test_eventlog.py
@@ -134,3 +134,15 @@ def test_short_path_keeps_absolute_when_outside(tmp_path, monkeypatch):
assert out == "/var/log/foo.txt" or not out.startswith("..")
+
+
+def test_announce_bucket_is_capped(caplog_lsp, monkeypatch):
+ """Per-file dedup keys stop at _ANNOUNCE_CAP: the bucket resets (re-firing the first-seen line once)
+ rather than holding every file path a long-running process ever touched."""
+ monkeypatch.setattr(eventlog, "_ANNOUNCE_CAP", 4)
+ for i in range(6):
+ eventlog.log_no_project_root("pyright", f"/proj/f{i}.py")
+ assert len(eventlog._announced_no_root) <= 4
+ eventlog.log_no_project_root("pyright", "/proj/f5.py") # still deduped after the reset
+ info = [r.getMessage() for r in caplog_lsp.records if r.levelno == logging.INFO]
+ assert info.count("lsp[pyright] no project root for /proj/f5.py") == 1
diff --git a/tests/agent/lsp/test_workspace.py b/tests/agent/lsp/test_workspace.py
index 252a2903fae..e9051d95482 100644
--- a/tests/agent/lsp/test_workspace.py
+++ b/tests/agent/lsp/test_workspace.py
@@ -36,7 +36,7 @@ def test_nearest_root_finds_first_marker(tmp_path: Path):
root = tmp_path / "p"
deep = root / "src" / "pkg"
deep.mkdir(parents=True)
- (root / "pyproject.toml").write_text("")
+ (root / "pyproject.toml").write_text("", encoding="utf-8")
found = nearest_root(str(deep / "mod.py"), ["pyproject.toml"])
assert found == str(root)
@@ -47,9 +47,9 @@ def test_nearest_root_skips_package_dirs(tmp_path: Path):
root = tmp_path / "p"
pkg = root / "hermes_cli"
pkg.mkdir(parents=True)
- (root / "pyproject.toml").write_text("")
- (pkg / "__init__.py").write_text("")
- (pkg / "setup.py").write_text("")
+ (root / "pyproject.toml").write_text("", encoding="utf-8")
+ (pkg / "__init__.py").write_text("", encoding="utf-8")
+ (pkg / "setup.py").write_text("", encoding="utf-8")
found = nearest_root(str(pkg / "main.py"), ["pyproject.toml", "setup.py"])
assert found == str(root)
@@ -58,7 +58,7 @@ def test_resolve_workspace_for_file_uses_cwd_first(tmp_path: Path, monkeypatch):
repo = tmp_path / "repo"
(repo / ".git").mkdir(parents=True)
file_path = repo / "x.py"
- file_path.write_text("")
+ file_path.write_text("", encoding="utf-8")
# cwd is inside the repo
monkeypatch.chdir(str(repo))
root, gated = resolve_workspace_for_file(str(file_path))
@@ -96,3 +96,15 @@ def test_normalize_path_expands_tilde(monkeypatch):
monkeypatch.setenv("HOME", "/home/user")
p = normalize_path("~/x.py")
assert p == os.path.abspath("/home/user/x.py")
+
+
+def test_find_git_worktree_cache_is_capped(tmp_path: Path, monkeypatch):
+ """The start-dir cache resets past _WORKSPACE_CACHE_CAP instead of growing per distinct dir touched."""
+ import agent.lsp.workspace as ws
+
+ monkeypatch.setattr(ws, "_WORKSPACE_CACHE_CAP", 4)
+ for i in range(6):
+ d = tmp_path / f"d{i}"
+ d.mkdir()
+ assert find_git_worktree(str(d)) is None
+ assert len(ws._workspace_cache) <= 4