Skip to content

The agent that grows with you

fix(lsp): reap servers cancelled during startup

fangliquanbf52a9519a15
diff --git a/agent/lsp/client.py b/agent/lsp/client.py
index a286160d74a..6aa2cf18256 100644
--- a/agent/lsp/client.py
+++ b/agent/lsp/client.py
@@ -13,6 +13,7 @@ import asyncio
import contextlib
import logging
import os
+import signal
import sys
from dataclasses import dataclass, field
from pathlib import Path
@@ -207,9 +208,12 @@ class LSPClient:
if not self._connection_is_open():
raise LSPProtocolError("server connection closed during initialization")
self._state = "running"
- except Exception:
+ except BaseException:
self._state = "error"
- await self._cleanup_process()
+ # ``_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())
raise
async def _spawn(self) -> None:
@@ -352,11 +356,18 @@ class LSPClient:
if proc is None or proc.returncode is not None:
return
try:
- proc.terminate()
+ # The server owns a process group (``start_new_session=True``). Kill the
+ # whole tree so JVM/Gradle and launcher grandchildren cannot survive the
+ # client that owned them. Windows maps both signals to taskkill /T /F.
+ from agent.deadline import kill_process_tree
+
+ if not kill_process_tree(proc.pid, sig=signal.SIGTERM):
+ proc.terminate()
try:
await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)
except asyncio.TimeoutError:
- proc.kill()
+ if not kill_process_tree(proc.pid, sig=getattr(signal, "SIGKILL", signal.SIGTERM)):
+ proc.kill()
await proc.wait()
except ProcessLookupError:
pass
diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.py
index a42cb1f4bba..ff005cfc037 100644
--- a/tests/agent/lsp/test_client_e2e.py
+++ b/tests/agent/lsp/test_client_e2e.py
@@ -92,6 +92,24 @@ async def test_reader_exit_at_end_of_initialization_retires_client(tmp_path: Pat
await client.shutdown()
+async def test_cancelled_start_terminates_spawned_server(tmp_path: Path):
+ """An outer startup budget may cancel initialize before the manager registers the client."""
+ client = _client(tmp_path, "slow")
+ start = asyncio.create_task(client.start())
+ while client._proc is None:
+ await asyncio.sleep(0)
+ proc = client._proc
+
+ with pytest.raises(asyncio.TimeoutError):
+ await asyncio.wait_for(start, timeout=0.05)
+
+ assert proc is not None
+ await asyncio.wait_for(proc.wait(), timeout=3.0)
+ assert client.state == "error"
+ assert client._proc is None
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize("script", ["clean_eof", "malformed_frame"])
async def test_reader_failure_retires_client_and_rejects_later_work(