Skip to content

The agent that grows with you

fix: bound the LSP document cache, delta baselines, TUI fuzzy cache and the tool-call logger (#62950)

Tikkanaditya Siddartha Jyothi539b82698ea0
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 5a182e99d9a..c6072955777 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -38,6 +38,11 @@ SHUTDOWN_GRACE = 1.0 # seconds after `exit` before SIGTERM, and between SIGTERM
# Retry policy for transient ContentModified errors: 0.5, 1.0, 2.0s.
MAX_CONTENT_MODIFIED_RETRIES = 3
RETRY_BASE_DELAY = 0.5
+# Cap on tracked documents: each _DocState pins the file's full text here AND the server mirrors
+# every open document, so an uncapped dict pins everything a long session ever touched on both
+# sides of the pipe until the idle reaper kills the whole client (#62950). 64 covers an active
+# edit loop's working set; evicted files are didClose'd and re-didOpen'ed on their next touch.
+MAX_TRACKED_FILES = 64
_WRITE_ERRORS = (BrokenPipeError, ConnectionResetError, OSError)
_LIVE_STATES = {"starting", "running"}
@@ -508,12 +513,16 @@ class LSPClient:
)
if doc is None:
# Fresh state: anything a pre-open push stashed under this path (relatedDocuments spillover) is discarded.
+ self._docs.pop(abs_path, None)
self._docs[abs_path] = _DocState(version=0, text=text)
await self._send_notification(
"textDocument/didOpen",
{"textDocument": {"uri": uri, "languageId": language_id, "version": 0, "text": text}},
)
+ await self._evict_lru_docs()
return 0
+ # pop + reinsert refreshes LRU recency (dicts are insertion-ordered).
+ self._docs[abs_path] = self._docs.pop(abs_path)
change: Dict[str, Any] = {"text": text}
if self._sync_kind == 2:
change["range"] = {"start": {"line": 0, "character": 0}, "end": _end_position(doc.text)}
@@ -530,6 +539,15 @@ class LSPClient:
)
return new_version
+ async def _evict_lru_docs(self) -> None:
+ """Drop least-recently-touched documents beyond MAX_TRACKED_FILES; didClose the ones the server
+ has open so it releases its mirror too (version -1 entries were never opened)."""
+ while len(self._docs) > MAX_TRACKED_FILES:
+ old_path, old = next(iter(self._docs.items()))
+ del self._docs[old_path]
+ if old.version >= 0:
+ await self._send_notification("textDocument/didClose", {"textDocument": {"uri": file_uri(old_path)}})
+
async def save_file(self, path: str) -> None:
"""Send didSave for ``path``. Some linters re-scan only on save."""
if self.is_running:
diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py
index fa41767072b..ff7a427a69c 100644
--- a/agent/lsp/manager.py
+++ b/agent/lsp/manager.py
@@ -26,6 +26,7 @@ from agent.lsp.workspace import clear_cache, resolve_workspace_for_file
logger = logging.getLogger("agent.lsp.manager")
DEFAULT_IDLE_TIMEOUT = 600 # seconds; servers idle for >10min get reaped
+_DELTA_BASELINE_CAP = 256 # per-file pre-write snapshots; paths never written again would otherwise live forever (#62950)
MIN_IDLE_TIMEOUT = 30 # floor for config values; must exceed any per-op wait budget
_Key = Tuple[str, str]
@@ -222,7 +223,14 @@ class LSPService:
logger.debug("baseline snapshot failed for %s: %s", file_path, e)
self._mark_broken_for_file(file_path, e)
diags = []
- self._delta_baseline[os.path.abspath(file_path)] = diags or []
+ self._set_delta_baseline(os.path.abspath(file_path), diags or [])
+
+ def _set_delta_baseline(self, abs_path: str, diags: _Diags) -> None:
+ """Store a baseline, refreshing recency (pop + reinsert) so eviction tracks write order."""
+ self._delta_baseline.pop(abs_path, None)
+ self._delta_baseline[abs_path] = diags
+ while len(self._delta_baseline) > _DELTA_BASELINE_CAP:
+ del self._delta_baseline[next(iter(self._delta_baseline))]
def get_diagnostics_sync(
self, file_path: str, *, delta: bool = True, timeout: Optional[float] = None,
@@ -281,7 +289,7 @@ class LSPService:
except Exception: # noqa: BLE001
fresh = []
if fresh:
- self._delta_baseline[abs_path] = fresh
+ self._set_delta_baseline(abs_path, fresh)
return diags
def _mark_broken_for_file(self, file_path: str, exc: BaseException) -> None:
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index e32afc3e44c..7fecca5fd0b 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -45,6 +45,33 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+_tool_call_logger_lock = threading.Lock()
+
+
+def _tool_call_logger() -> logging.Logger:
+ """Process-wide ``hermes.tool_calls`` Logger + one RotatingFileHandler on logs/tool_calls.log.
+ Named Loggers live in ``logging.Logger.manager.loggerDict`` forever, so the former per-turn name
+ (``hermes.tool_calls.<id(log_queue)>``) leaked one Logger per logged turn (#62950); a single
+ shared handler also keeps concurrent turns from double-writing lines."""
+ tool_logger = logging.getLogger("hermes.tool_calls")
+ with _tool_call_logger_lock:
+ if not tool_logger.handlers:
+ from logging.handlers import RotatingFileHandler
+ from agent.redact import RedactingFormatter
+ from gateway.run import _hermes_home
+
+ log_dir = _hermes_home / "logs"
+ log_dir.mkdir(parents=True, exist_ok=True)
+ handler = RotatingFileHandler(
+ log_dir / "tool_calls.log", maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8",
+ )
+ handler.setFormatter(RedactingFormatter("%(message)s"))
+ tool_logger.setLevel(logging.INFO)
+ tool_logger.propagate = False
+ tool_logger.addHandler(handler)
+ return tool_logger
+
+
_CONTEXT_OVERFLOW_ERROR_PHRASES = (
"context length", "context size", "context window",
@@ -3097,22 +3124,9 @@ class GatewayTurnMixin:
"""Drain log_queue and append tool-call lines to tool_calls.log (tool_progress=log).
RotatingFileHandler (5MB × 3) bounds the log; RedactingFormatter keeps secrets off disk."""
- from gateway.run import _hermes_home
if log_queue is None:
return
- from logging.handlers import RotatingFileHandler
- from agent.redact import RedactingFormatter
-
- log_dir = _hermes_home / "logs"
- log_dir.mkdir(parents=True, exist_ok=True)
- file_handler = RotatingFileHandler(
- log_dir / "tool_calls.log", maxBytes=5 * 1024 * 1024, backupCount=3, encoding="utf-8",
- )
- file_handler.setFormatter(RedactingFormatter("%(message)s"))
- tool_logger = logging.getLogger(f"hermes.tool_calls.{id(log_queue)}")
- tool_logger.setLevel(logging.INFO)
- tool_logger.propagate = False
- tool_logger.addHandler(file_handler)
+ tool_logger = _tool_call_logger()
try:
while True:
try:
@@ -3129,10 +3143,9 @@ class GatewayTurnMixin:
with suppress(Exception):
while True:
tool_logger.info("%s", log_queue.get_nowait())
- tool_logger.removeHandler(file_handler)
with suppress(Exception):
- file_handler.flush()
- file_handler.close()
+ for handler in tool_logger.handlers:
+ handler.flush()
def _run_agent_start_streaming_tts(
self, source: SessionSource, message_type: Optional[str],
diff --git a/tui_gateway/methods_complete_helpers.py b/tui_gateway/methods_complete_helpers.py
index b4ea31533ae..d64d64e152f 100644
--- a/tui_gateway/methods_complete_helpers.py
+++ b/tui_gateway/methods_complete_helpers.py
@@ -70,6 +70,10 @@ def _list_repo_files(root: str) -> list[str]:
if not files:
files = list(islice(_walk_repo_files(root), _FUZZY_CACHE_MAX_FILES))
with _fuzzy_cache_lock:
+ # The TTL is only consulted on read, so a root that stops being queried (one .worktrees/<id>
+ # root per worktree flow, MBs each) would stay pinned for the process lifetime (#62950).
+ for stale in [r for r, (ts, _) in _fuzzy_cache.items() if now - ts >= _FUZZY_CACHE_TTL_S]:
+ del _fuzzy_cache[stale]
_fuzzy_cache[root] = (now, files)
return files