The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lsp): retire clients when the protocol reader exits
fangliquanflq2f506c2023e1
diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex 3411f5300b3..12f263f1e7f 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -207,6 +207,7 @@ class LSPClient:self._proc: Optional[asyncio.subprocess.Process] = Noneself._stderr_task: Optional[asyncio.Task] = Noneself._reader_task: Optional[asyncio.Task] = None+ self._cleanup_lock = asyncio.Lock()# Request/response correlationself._next_id: int = 0@@ -255,7 +256,20 @@ class LSPClient:@propertydef is_running(self) -> bool:- return self._state == "running" and self._proc is not None and self._proc.returncode is None+ return self._state == "running" and self._connection_is_open()++ def _connection_is_open(self) -> bool:+ proc = self._proc+ reader = self._reader_task+ return (+ self._state in {"starting", "running"}+ and proc is not None+ and proc.returncode is None+ and proc.stdin is not None+ and not proc.stdin.is_closing()+ and reader is not None+ and not reader.done()+ )@propertydef state(self) -> str:@@ -274,6 +288,8 @@ class LSPClient:try:await self._spawn()await self._initialize()+ if not self._connection_is_open():+ raise LSPProtocolError("server connection closed during initialization")self._state = "running"except Exception:self._state = "error"@@ -370,11 +386,16 @@ class LSPClient:except (asyncio.CancelledError, OSError):passfinally:+ unexpected_close = not self._stopping and self._state in {"starting", "running"}+ if unexpected_close:+ self._state = "error"# Wake up any pending requests so they can fail fast.for fut in list(self._pending.values()):if not fut.done():fut.set_exception(LSPProtocolError("server connection closed"))self._pending.clear()+ if unexpected_close:+ await self._cleanup_process()async def _initialize(self) -> None:params = {@@ -474,43 +495,54 @@ class LSPClient:await self._cleanup_process()async def _cleanup_process(self) -> None:- if self._reader_task is not None and not self._reader_task.done():- self._reader_task.cancel()- try:- await self._reader_task- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass- if self._stderr_task is not None and not self._stderr_task.done():- self._stderr_task.cancel()- try:- await self._stderr_task- except (asyncio.CancelledError, Exception): # noqa: BLE001- pass- proc = self._proc- self._proc = None- if proc is None:- return- if proc.returncode is None:- try:- proc.terminate()+ async with self._cleanup_lock:+ current_task = asyncio.current_task()+ reader_task = self._reader_task+ self._reader_task = None+ if (+ reader_task is not None+ and reader_task is not current_task+ and not reader_task.done()+ ):+ reader_task.cancel()+ try:+ await reader_task+ except (asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ stderr_task = self._stderr_task+ self._stderr_task = None+ if stderr_task is not None and not stderr_task.done():+ stderr_task.cancel()+ try:+ await stderr_task+ except (asyncio.CancelledError, Exception): # noqa: BLE001+ pass+ proc = self._proc+ self._proc = None+ if proc is None:+ return+ if proc.returncode is None:try:- await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)- except asyncio.TimeoutError:+ proc.terminate()try:- proc.kill()- await proc.wait()- except ProcessLookupError:- pass- except ProcessLookupError:- pass+ await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)+ except asyncio.TimeoutError:+ try:+ proc.kill()+ await proc.wait()+ except ProcessLookupError:+ pass+ except ProcessLookupError:+ pass# ------------------------------------------------------------------# request / notification plumbing# ------------------------------------------------------------------async def _send_request(self, method: str, params: Any) -> Any:- if self._proc is None or self._proc.stdin is None or self._proc.stdin.is_closing():- raise LSPProtocolError(f"cannot send {method!r}: stdin closed")+ if not self._connection_is_open():+ raise LSPProtocolError(f"cannot send {method!r}: server connection closed")+ assert self._proc is not None and self._proc.stdin is not Noneloop = asyncio.get_running_loop()req_id = self._next_idself._next_id += 1@@ -544,8 +576,9 @@ class LSPClient:raiseasync def _send_notification(self, method: str, params: Any) -> None:- if self._proc is None or self._proc.stdin is None or self._proc.stdin.is_closing():- return+ if not self._connection_is_open():+ raise LSPProtocolError(f"cannot send {method!r}: server connection closed")+ assert self._proc is not None and self._proc.stdin is not Nonetry:self._proc.stdin.write(encode_message(make_notification(method, params)))await self._proc.stdin.drain()diff --git a/tests/agent/lsp/_mock_lsp_server.py b/tests/agent/lsp/_mock_lsp_server.pyindex 316e914569a..d7ce4101515 100644--- a/tests/agent/lsp/_mock_lsp_server.py+++ b/tests/agent/lsp/_mock_lsp_server.py@@ -25,6 +25,10 @@ Behaviour (all behaviours selectable via env var ``MOCK_LSP_SCRIPT``):``didChange`` sleeps ``MOCK_LSP_PUSH_DELAY`` seconds (default 1.0)and then pushes EMPTY diagnostics. Models a server that fixesthe ghost if you actually wait for it. Pull endpoint rejects.+- ``"clean_eof"`` — closes stdout after ``didOpen`` but keeps the+ process and stdin alive.+- ``"malformed_frame"`` — writes an invalid frame after ``didOpen``,+ then keeps the process and stdin alive.The script writes JSON-RPC framed messages to stdout and reads fromstdin. No third-party dependencies — uses only stdlib so it runs@@ -105,6 +109,14 @@ def main():uri = td.get("uri", "")version = td.get("version", 0)is_change = msg.get("method") == "textDocument/didChange"+ if not is_change and script in {"clean_eof", "malformed_frame"}:+ if script == "malformed_frame":+ sys.stdout.buffer.write(b"Content-Length: invalid\r\n\r\n")+ sys.stdout.buffer.flush()+ os.close(sys.stdout.fileno())+ while read_message() is not None:+ pass+ return 0error_diag = [{"range": {diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.pyindex 322c91ed91f..9a9cde8f076 100644--- a/tests/agent/lsp/test_client_e2e.py+++ b/tests/agent/lsp/test_client_e2e.py@@ -15,6 +15,7 @@ from pathlib import Pathimport pytestfrom agent.lsp.client import LSPClient+from agent.lsp.protocol import LSPProtocolErrorMOCK_SERVER = str(Path(__file__).parent / "_mock_lsp_server.py")@@ -72,9 +73,49 @@ async def test_client_receives_published_errors(tmp_path: Path):await client.shutdown()+async def test_reader_exit_at_end_of_initialization_retires_client(tmp_path: Path):+ client = _client(tmp_path, "crash")+ try:+ await client.start()+ except LSPProtocolError:+ pass+ else:+ reader_task = client._reader_task+ if reader_task is not None:+ await asyncio.wait_for(asyncio.shield(reader_task), timeout=3.0)++ assert client.state == "error"+ assert not client.is_running+ assert client._proc is None+ await client.shutdown()[email protected]("script", ["clean_eof", "malformed_frame"])+async def test_reader_failure_retires_client_and_rejects_later_work(+ tmp_path: Path, script: str+):+ f = tmp_path / "x.py"+ f.write_text("print('hi')\n")--+ client = _client(tmp_path, script)+ await client.start()+ proc = client._proc+ reader_task = client._reader_task+ assert proc is not None+ assert reader_task is not None+ try:+ await client.open_file(str(f), language_id="python")+ await asyncio.wait_for(asyncio.shield(reader_task), timeout=3.0)++ assert not client.is_running+ await asyncio.wait_for(proc.wait(), timeout=3.0)+ with pytest.raises(LSPProtocolError):+ await asyncio.wait_for(+ client.open_file(str(f), language_id="python"),+ timeout=0.5,+ )+ finally:+ await client.shutdown()diff --git a/tests/agent/lsp/test_service.py b/tests/agent/lsp/test_service.pyindex 9dd7468ca9c..ef5ab70adc0 100644--- a/tests/agent/lsp/test_service.py+++ b/tests/agent/lsp/test_service.py@@ -7,6 +7,7 @@ on."""from __future__ import annotations+import asyncioimport sysimport timefrom pathlib import Path@@ -25,7 +26,9 @@ from agent.lsp.servers import (MOCK_SERVER = str(Path(__file__).parent / "_mock_lsp_server.py")-def _install_mock_server(monkeypatch, script: str = "errors", server_id: str = "pyright"):+def _install_mock_server(+ monkeypatch, script: str | list[str] = "errors", server_id: str = "pyright"+):"""Replace one registered server with a wrapper that spawns the mock.We reuse ``pyright`` so .py files route to it. This keeps the@@ -33,9 +36,13 @@ def _install_mock_server(monkeypatch, script: str = "errors", server_id: str = """"target_index = next(i for i, s in enumerate(SERVERS) if s.server_id == server_id)original = SERVERS[target_index]+ scripts = [script] if isinstance(script, str) else script+ spawn_count = {"value": 0}def _spawn(root: str, ctx: ServerContext) -> SpawnSpec:- env = {"MOCK_LSP_SCRIPT": script}+ index = min(spawn_count["value"], len(scripts) - 1)+ spawn_count["value"] += 1+ env = {"MOCK_LSP_SCRIPT": scripts[index]}return SpawnSpec(command=[sys.executable, MOCK_SERVER],workspace_root=root,@@ -55,7 +62,7 @@ def _install_mock_server(monkeypatch, script: str = "errors", server_id: str = "# Patch the SERVERS list element directly + restore on teardown.SERVERS[target_index] = replacement- yield+ yield spawn_countSERVERS[target_index] = original@@ -104,6 +111,54 @@ def test_service_e2e_delta_filter(mock_pyright):svc.shutdown()[email protected]("failed_script", ["clean_eof", "malformed_frame"])+def test_service_replaces_client_after_reader_failure(+ tmp_path, monkeypatch, failed_script+):+ repo = tmp_path / "repo"+ repo.mkdir()+ (repo / ".git").mkdir()+ (repo / "pyproject.toml").write_text("")+ source = repo / "x.py"+ source.write_text("print('hi')\n")+ monkeypatch.chdir(str(repo))+ server = _install_mock_server(+ monkeypatch, [failed_script, "clean"], "pyright"+ )+ spawn_count = next(server)++ svc = LSPService(+ enabled=True,+ wait_mode="document",+ wait_timeout=0.5,+ install_strategy="manual",+ )+ try:+ async def _break_first_client():+ client = await svc._get_or_spawn(str(source))+ assert client is not None+ reader_task = client._reader_task+ assert reader_task is not None+ await client.open_file(str(source), language_id="python")+ await asyncio.wait_for(asyncio.shield(reader_task), timeout=3.0)+ return client++ first = svc._loop.run(_break_first_client(), timeout=5.0)+ replacement = svc._loop.run(svc._get_or_spawn(str(source)), timeout=5.0)++ assert not first.is_running+ assert replacement is not None+ assert replacement is not first+ assert replacement.is_running+ assert spawn_count["value"] == 2+ finally:+ svc.shutdown()+ try:+ next(server)+ except StopIteration:+ pass++def test_service_e2e_delta_filter_with_line_shift(mock_pyright):"""End-to-end: an edit that shifts the diagnostic's line stillfilters correctly when ``line_shift`` is supplied.