Skip to content

The agent that grows with you

fix(lsp): report server exit status and stderr tail on a failed initialize (#116446)

Konstantin Khlopkovb4f0553f8e83
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index 4e73aeef642..360c063b12b 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -38,6 +38,10 @@ 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
+# Last server stderr lines kept for failure reports; the V8 heap-abort trace that explains a
+# tsserver SIGABRT is otherwise only visible at DEBUG, so the WARNING a user actually reads
+# cannot distinguish "binary missing" from "server ran out of memory".
+STDERR_TAIL_LINES = 30
# 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
@@ -148,6 +152,9 @@ class LSPClient:
self._proc: Optional[asyncio.subprocess.Process] = None
self._stderr_task: Optional[asyncio.Task] = None
+ # Ring buffer of the most recent server stderr lines, surfaced when spawn/initialize fails.
+ self._stderr_tail: List[str] = []
+ self._exit_code: Optional[int] = None
self._reader_task: Optional[asyncio.Task] = None
self._cleanup_lock = asyncio.Lock()
self._next_id: int = 0
@@ -207,12 +214,29 @@ class LSPClient:
if not self._connection_is_open():
raise LSPProtocolError("server connection closed during initialization")
self._state = "running"
- except BaseException:
+ except BaseException as e:
self._state = "error"
+ # Reap the server now so the failure report can name the exit status (a Node heap
+ # abort dies on SIGABRT; without this the caller logs an opaque JSON-RPC error).
+ # The reader loop may have run ``_cleanup_process`` first — it records the code
+ # too, so both orderings leave ``failure_details`` populated.
+ proc = self._proc
+ if proc is not None:
+ with contextlib.suppress(Exception):
+ await asyncio.wait_for(proc.wait(), timeout=1.0)
+ if proc.returncode is not None:
+ self._exit_code = proc.returncode
+ stderr_task = self._stderr_task
+ if stderr_task is not None: # brief window to collect the abort trace
+ with contextlib.suppress(Exception):
+ await asyncio.wait_for(asyncio.shield(stderr_task), timeout=0.5)
# ``_BackgroundLoop.run`` cancels this task when its outer budget expires.
# CancelledError is a BaseException on supported Python versions, and cleanup
# must outlive that cancellation or the spawned server escapes all tracking.
await asyncio.shield(self._cleanup_process())
+ details = self.failure_details()
+ if details and isinstance(e, Exception):
+ raise type(e)(f"{e} ({details})") from e
raise
async def _spawn(self) -> None:
@@ -244,9 +268,33 @@ class LSPClient:
while line := await self._proc.stderr.readline():
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])
+ del self._stderr_tail[:-STDERR_TAIL_LINES]
except (asyncio.CancelledError, OSError):
pass
+ def _describe_exit(self) -> str:
+ """Human rendering of the server exit status; empty when the process is still live."""
+ proc = self._proc
+ if self._exit_code is not None:
+ code = self._exit_code
+ elif proc is not None and proc.returncode is not None:
+ code = proc.returncode
+ else:
+ return ""
+ if code < 0:
+ return f"server exited on signal {-code}"
+ return f"server exited with code {code}"
+
+ def failure_details(self) -> str:
+ """Exit status + last stderr lines for a failed spawn/initialize; empty for a live server."""
+ parts: List[str] = []
+ if exit_desc := self._describe_exit():
+ parts.append(exit_desc)
+ if self._stderr_tail:
+ parts.append("last stderr lines: " + " | ".join(self._stderr_tail))
+ return "; ".join(parts)
+
def _dispatch(self, msg: dict) -> None:
kind, key = classify_message(msg)
if kind == "response":
@@ -352,7 +400,11 @@ class LSPClient:
for t in live:
t.cancel()
await asyncio.gather(*live, return_exceptions=True)
- if proc is None or proc.returncode is not None:
+ if proc is None:
+ return
+ if proc.returncode is not None:
+ if self._exit_code is None:
+ self._exit_code = proc.returncode
return
try:
# ``shutdown`` has already given the protocol a grace period. Hard-kill
@@ -368,6 +420,8 @@ class LSPClient:
await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)
except ProcessLookupError:
pass
+ if self._exit_code is None and proc.returncode is not None:
+ self._exit_code = proc.returncode
# ---- request / notification plumbing ----
diff --git a/tests/agent/lsp/_mock_lsp_server.py b/tests/agent/lsp/_mock_lsp_server.py
index 86bb4b9482a..67b1d9a5a92 100644
--- a/tests/agent/lsp/_mock_lsp_server.py
+++ b/tests/agent/lsp/_mock_lsp_server.py
@@ -15,6 +15,9 @@ Behaviour (all behaviours selectable via env var ``MOCK_LSP_SCRIPT``):
carry one severity-1 entry pointing at line 0:0.
- ``"crash"`` — exit immediately after responding to ``initialize``
(simulates a crashing server).
+- ``"oom_abort"`` — prints a V8-style out-of-memory trace to stderr and
+ aborts (SIGABRT) before answering ``initialize`` — models a Node
+ language-server whose heap ceiling is too small for the workspace.
- ``"slow"`` — same as ``clean`` but sleeps 1s before responding to
``initialize`` (lets us test timeout behaviour).
- ``"slow_tree"`` — like ``slow``, with a child that ignores SIGTERM and
@@ -95,6 +98,15 @@ def main():
stderr=subprocess.DEVNULL,
)
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
+ if script == "oom_abort":
+ sys.stderr.write(
+ "<oproject>:28982 ms: Mark-Compact 2041.4 (2055.6) -> 2038.4 (2058.4) MB\n"
+ " 1317.07 ms (average mu = 0.307, current mu = 0.134)\n"
+ "<--- Last few GCs --->\n"
+ "FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory\n"
+ )
+ sys.stderr.flush()
+ os.abort()
while True:
msg = read_message()
diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.py
index 26fa08cd966..d1bab3b7eb8 100644
--- a/tests/agent/lsp/test_client_e2e.py
+++ b/tests/agent/lsp/test_client_e2e.py
@@ -73,6 +73,39 @@ async def test_client_receives_published_errors(tmp_path: Path):
await client.shutdown()
+async def test_aborted_start_reports_exit_status_and_stderr_tail(tmp_path: Path):
+ """A server that dies mid-initialize must not fail as an opaque protocol error.
+
+ A Node language server that exhausts its heap aborts (SIGABRT) before answering
+ ``initialize``; the failure the caller logs should carry the exit status and the
+ stderr trace instead of a bare JSON-RPC error text.
+ """
+ client = _client(tmp_path, "oom_abort")
+
+ with pytest.raises(LSPProtocolError) as excinfo:
+ await client.start()
+
+ assert client.state == "error"
+ assert client._proc is None
+ message = str(excinfo.value)
+ # negative returncode rendered as a signal, not a bare code
+ assert "signal" in message
+ # stderr tail reached the failure report
+ assert "JavaScript heap out of memory" in message
+ await client.shutdown()
+
+
+async def test_failure_details_empty_for_live_server(tmp_path: Path):
+ client = _client(tmp_path, "clean")
+ await client.start()
+ try:
+ assert client.failure_details() == ""
+ finally:
+ await client.shutdown()
+
+
@pytest.mark.asyncio
async def test_reader_exit_at_end_of_initialization_retires_client(tmp_path: Path):
client = _client(tmp_path, "crash")