The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lsp): hard-kill failed server trees before reaping
fangliquanb773bcf271e6
diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex 6aa2cf18256..cc1b343bc4d 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -13,7 +13,6 @@ import asyncioimport contextlibimport loggingimport os-import signalimport sysfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -356,19 +355,16 @@ class LSPClient:if proc is None or proc.returncode is not None:returntry:- # 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.+ # ``shutdown`` has already given the protocol a grace period. Hard-kill+ # the tree while its ancestry is still observable: waiting for the launcher+ # after SIGTERM can let an ignoring descendant become reparented and escape.+ # Windows maps this to taskkill /T /F.from agent.deadline import kill_process_tree- if not kill_process_tree(proc.pid, sig=signal.SIGTERM):- proc.terminate()- try:+ if not kill_process_tree(proc.pid):+ proc.kill()+ with contextlib.suppress(asyncio.TimeoutError):await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)- except asyncio.TimeoutError:- if not kill_process_tree(proc.pid, sig=getattr(signal, "SIGKILL", signal.SIGTERM)):- proc.kill()- await proc.wait()except ProcessLookupError:passdiff --git a/tests/agent/lsp/_mock_lsp_server.py b/tests/agent/lsp/_mock_lsp_server.pyindex 15d468d2fa7..86bb4b9482a 100644--- a/tests/agent/lsp/_mock_lsp_server.py+++ b/tests/agent/lsp/_mock_lsp_server.py@@ -17,6 +17,8 @@ Behaviour (all behaviours selectable via env var ``MOCK_LSP_SCRIPT``):(simulates a crashing server).- ``"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+ a launcher that exits on SIGTERM (tests hard process-tree cleanup).- ``"stale"`` — pushes one error on ``didOpen``, then goes SILENT on``didChange`` (no push) and rejects the pull endpoint withmethod-not-found. Models a slow tsserver that hasn't re-checked@@ -44,6 +46,8 @@ from __future__ import annotationsimport jsonimport os+import signal+import subprocessimport sysimport time@@ -75,6 +79,22 @@ def write_message(obj):def main():script = os.environ.get("MOCK_LSP_SCRIPT", "clean")documents = {}+ if script == "slow_tree":+ subprocess.Popen(+ [+ sys.executable,+ "-c",+ "import os, pathlib, signal, time; "+ "signal.signal(signal.SIGTERM, signal.SIG_IGN); "+ "pathlib.Path(os.environ['MOCK_LSP_CHILD_PID']).write_text(str(os.getpid())); "+ "time.sleep(60)",+ ],+ env=os.environ,+ stdin=subprocess.DEVNULL,+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))while True:msg = read_message()@@ -82,7 +102,7 @@ def main():return 0if "id" in msg and msg.get("method") == "initialize":- if script == "slow":+ if script in {"slow", "slow_tree"}:time.sleep(1.0)write_message({diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.pyindex ff005cfc037..26fa08cd966 100644--- a/tests/agent/lsp/test_client_e2e.py+++ b/tests/agent/lsp/test_client_e2e.py@@ -110,6 +110,42 @@ async def test_cancelled_start_terminates_spawned_server(tmp_path: Path):assert client._proc is None[email protected]_only+async def test_cancelled_start_hard_kills_sigterm_ignoring_descendant(tmp_path: Path):+ """A launcher exiting on SIGTERM must not let an ignoring server child escape cleanup."""+ import psutil++ child_pid_file = tmp_path / "child.pid"+ client = _client(tmp_path, "slow_tree")+ assert client._env is not None+ client._env["MOCK_LSP_CHILD_PID"] = str(child_pid_file)+ start = asyncio.create_task(client.start())+ child = None+ try:+ ready_deadline = asyncio.get_running_loop().time() + 3.0+ while not child_pid_file.exists():+ assert asyncio.get_running_loop().time() < ready_deadline+ await asyncio.sleep(0.01)+ child = psutil.Process(int(child_pid_file.read_text(encoding="utf-8")))++ with pytest.raises(asyncio.TimeoutError):+ await asyncio.wait_for(start, timeout=0.05)++ deadline = asyncio.get_running_loop().time() + 3.0+ while child.is_running() and child.status() != psutil.STATUS_ZOMBIE:+ assert asyncio.get_running_loop().time() < deadline+ await asyncio.sleep(0.01)+ assert client.state == "error"+ assert client._proc is None+ finally:+ if not start.done():+ start.cancel()+ await asyncio.gather(start, return_exceptions=True)+ if child is not None and child.is_running():+ child.kill()++@pytest.mark.asyncio@pytest.mark.parametrize("script", ["clean_eof", "malformed_frame"])async def test_reader_failure_retires_client_and_rejects_later_work(