Skip to content

The agent that grows with you

fix(lsp): raise LSP subprocess StreamReader limit to 16 MiB

konsisumerd516575df3f8
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 8d268b41eeb..1ab02a660bf 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -19,6 +19,7 @@ from pathlib import Path
from typing import Any, Awaitable, Callable, Dict, List, Optional, Set
from urllib.parse import quote, unquote
+from agent.subprocess_utils import create_subprocess
from hermes_cli._subprocess_compat import windows_hide_flags
from agent.lsp.protocol import (
@@ -252,7 +253,7 @@ class LSPClient:
# the gateway's pgid and mcp_tool's orphan sweeper can killpg() the TUI parent with it.
# windows_hide_flags() suppresses the console window a .cmd shim would flash from a
# console-less host (CREATE_NO_WINDOW; 0 on POSIX).
- self._proc = await asyncio.create_subprocess_exec(
+ self._proc = await create_subprocess(
cmd[0], *cmd[1:],
stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,
env=delegated_child_subprocess_env({**os.environ, **(self._env or {})}), cwd=self._cwd,
@@ -267,8 +268,23 @@ class LSPClient:
async def _drain_stderr(self) -> None:
if self._proc is None or self._proc.stderr is None:
return
+ stderr = self._proc.stderr
try:
- while line := await self._proc.stderr.readline():
+ while True:
+ try:
+ line = await stderr.readline()
+ except ValueError:
+ # StreamReader.readline() translates LimitOverrunError to
+ # ValueError after discarding the oversized buffer. Continue
+ # draining so a pathological stderr line cannot leave the
+ # pipe unread and block the server.
+ logger.warning(
+ "[%s] stderr: line exceeded stream limit, discarding",
+ self.server_id,
+ )
+ continue
+ if not line:
+ break
if text := line.decode("utf-8", errors="replace").rstrip():
logger.debug("[%s] stderr: %s", self.server_id, text[:1000])
self._stderr_tail.append(text[:1000])
diff --git a/agent/subprocess_utils.py b/agent/subprocess_utils.py
new file mode 100644
index 00000000000..dfef78d9034
--- /dev/null
+++ b/agent/subprocess_utils.py
@@ -0,0 +1,23 @@
+"""asyncio subprocess helper with a larger default StreamReader limit."""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+
+# asyncio's default is 64 KiB, tuned for network protocols. Local subprocess
+# output (LSP diagnostics, base64 blobs, quoted source files) can easily exceed
+# that on a single line, causing readline() to raise LimitOverrunError and
+# deadlocking the pipe. 16 MiB covers realistic agent workloads while bounding
+# unbounded growth.
+SUBPROCESS_STREAM_LIMIT = 16 * 1024 * 1024 # 16 MiB
+
+
+async def create_subprocess(
+ *args: str,
+ stream_limit: int = SUBPROCESS_STREAM_LIMIT,
+ **kwargs: Any,
+) -> asyncio.subprocess.Process:
+ """asyncio.create_subprocess_exec with a larger default StreamReader limit."""
+ return await asyncio.create_subprocess_exec(*args, limit=stream_limit, **kwargs)
diff --git a/tests/agent/lsp/_mock_lsp_server.py b/tests/agent/lsp/_mock_lsp_server.py
index d00e3121173..1488e452dad 100644
--- a/tests/agent/lsp/_mock_lsp_server.py
+++ b/tests/agent/lsp/_mock_lsp_server.py
@@ -108,6 +108,21 @@ def main():
sys.stderr.flush()
os.abort()
+ if script == "large_stderr":
+ # Emit a single stderr line larger than asyncio's 64 KiB default limit
+ # to verify the client drain task doesn't crash or deadlock.
+ sys.stderr.write("X" * 131_072 + "\n") # 128 KiB
+ sys.stderr.flush()
+ script = "clean"
+
+ if script == "oversized_stderr":
+ # Exceed the client's 16 MiB StreamReader limit. readline() converts
+ # this into ValueError after discarding the buffered line; the client
+ # must keep draining stderr and serve requests normally.
+ sys.stderr.write("X" * (16 * 1024 * 1024 + 1) + "\n")
+ sys.stderr.flush()
+ script = "clean"
+
while True:
msg = read_message()
if msg is None:
diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.py
index 121d85f9a1f..c578974c2cf 100644
--- a/tests/agent/lsp/test_client_e2e.py
+++ b/tests/agent/lsp/test_client_e2e.py
@@ -18,6 +18,9 @@ from agent.lsp.client import LSPClient
from agent.lsp.protocol import LSPProtocolError, LSPRequestError
+pytestmark = pytest.mark.live_system_guard_bypass
+
+
MOCK_SERVER = str(Path(__file__).parent / "_mock_lsp_server.py")
@@ -221,8 +224,6 @@ async def test_reader_failure_retires_client_and_rejects_later_work(
)
finally:
await client.shutdown()
-
-
@pytest.mark.asyncio
async def test_shutdown_never_signals_a_server_that_honours_exit(tmp_path: Path):
"""A server that exits on the protocol ``exit`` must not be SIGTERMed on top of it (#72944:
@@ -278,3 +279,41 @@ async def test_docs_cache_is_lru_bounded_and_reopens_evicted(tmp_path: Path, mon
assert client.diagnostics_for(str(files[0]))
finally:
await client.shutdown()
+
+
+async def test_client_handles_large_stderr_line(tmp_path: Path):
+ """LSP stderr drain must not crash or deadlock when the server emits a line
+ larger than asyncio's old 64 KiB default StreamReader limit."""
+ f = tmp_path / "x.py"
+ f.write_text("print('hi')\n", encoding="utf-8")
+
+ client = _client(tmp_path, "large_stderr")
+ await client.start()
+ try:
+ assert client.is_running
+ version = await client.open_file(str(f), language_id="python")
+ await client.wait_for_diagnostics(str(f), version, mode="document")
+ diags = client.diagnostics_for(str(f))
+ assert diags == []
+ finally:
+ await client.shutdown()
+ assert not client.is_running
+
+
+async def test_client_handles_stderr_line_over_stream_limit(tmp_path: Path):
+ """An over-limit stderr line must not terminate the drain task."""
+ f = tmp_path / "x.py"
+ f.write_text("print('hi')\n", encoding="utf-8")
+
+ client = _client(tmp_path, "oversized_stderr")
+ await client.start()
+ try:
+ assert client.is_running
+ version = await client.open_file(str(f), language_id="python")
+ await client.wait_for_diagnostics(str(f), version, mode="document")
+ assert client.diagnostics_for(str(f)) == []
+ finally:
+ await client.shutdown()
+ assert not client.is_running