The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(lsp,gateway): give servers a grace period after `exit` and keep shutdown diagnostics off GNU-only tools (#72944)
Sasan Sotoodehfar51283072ad55
diff --git a/agent/lsp/client.py b/agent/lsp/client.pyindex b88503c4e86..5a182e99d9a 100644--- a/agent/lsp/client.py+++ b/agent/lsp/client.py@@ -10,6 +10,7 @@ it), and ``ContentModified`` (-32801) errors are retried with exponential backoffrom __future__ import annotationsimport asyncio+import contextlibimport loggingimport osimport sys@@ -33,7 +34,7 @@ DIAGNOSTICS_DOCUMENT_WAIT = 5.0DIAGNOSTICS_FULL_WAIT = 10.0DIAGNOSTICS_REQUEST_TIMEOUT = 3.0PUSH_DEBOUNCE = 0.15-SHUTDOWN_GRACE = 1.0 # seconds between SIGTERM and SIGKILL+SHUTDOWN_GRACE = 1.0 # seconds after `exit` before SIGTERM, and between SIGTERM and SIGKILL# Retry policy for transient ContentModified errors: 0.5, 1.0, 2.0s.MAX_CONTENT_MODIFIED_RETRIES = 3RETRY_BASE_DELAY = 0.5@@ -309,7 +310,8 @@ class LSPClient:await self._send_notification("workspace/didChangeConfiguration", {"settings": self._init_options})async def shutdown(self) -> None:- """Best-effort graceful shutdown: ``shutdown`` + ``exit``, then SIGTERM/SIGKILL. Idempotent."""+ """Best-effort graceful shutdown: ``shutdown`` + ``exit``, wait ``SHUTDOWN_GRACE`` for the+ server to honour ``exit``, then SIGTERM/SIGKILL. Idempotent."""if self._stopping:returnself._stopping = True@@ -323,6 +325,11 @@ class LSPClient:await self._send_notification("exit", None)except Exception: # noqa: BLE001pass+ # Signalling right after ``exit`` races the server's own exit: needless SIGTERM+ # noise for well-behaved servers and, on Darwin, a reaped-and-reused PID target.+ if (proc := self._proc) is not None and proc.returncode is None:+ with contextlib.suppress(asyncio.TimeoutError):+ await asyncio.wait_for(proc.wait(), timeout=SHUTDOWN_GRACE)finally:self._state = "stopped"await self._cleanup_process()diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]new file mode 100644index 00000000000..ec3b9e65437--- /dev/null+++ b/contributors/emails/[email protected]@@ -0,0 +1,2 @@+sasan1200+# PR #72932 salvagediff --git a/gateway/shutdown_forensics.py b/gateway/shutdown_forensics.pyindex e2e8d3720d0..3d1675b7f7d 100644--- a/gateway/shutdown_forensics.py+++ b/gateway/shutdown_forensics.py@@ -10,6 +10,7 @@ from __future__ import annotationsimport jsonimport os+import shutilimport signalimport subprocessimport sys@@ -120,9 +121,10 @@ def _async_diagnostic_script(signal_name: str, self_pid: int) -> str:f"echo '=== shutdown diagnostic @ {signal_name} ==='; ""echo '--- date ---'; date -u +%Y-%m-%dT%H:%M:%SZ; ""echo '--- ps (top 60 by cpu, comm only) ---'; "- "ps -eo pid,ppid,user,pcpu,pmem,stat,comm --sort=-pcpu 2>/dev/null | head -60; "+ # ``sort`` instead of GNU ``--sort=-pcpu`` so BSD ps (macOS) produces a listing too.+ "ps -eo pid,ppid,user,pcpu,pmem,stat,comm 2>/dev/null | sort -nrk4 | head -60; "f"echo '--- pstree of self ---'; pstree -pl {self_pid} 2>/dev/null | head -40 || true; "- "echo '--- /proc/loadavg ---'; cat /proc/loadavg 2>/dev/null || true; "+ "echo '--- loadavg ---'; cat /proc/loadavg 2>/dev/null || sysctl -n vm.loadavg 2>/dev/null || true; ""echo '--- recent dmesg (oom/killed) ---'; ""dmesg -T 2>/dev/null | tail -20 || journalctl --user -n 20 --no-pager 2>/dev/null | tail -20 || true; ""echo '=== end ==='"@@ -150,9 +152,13 @@ def spawn_async_diagnostic(log_path: Path, signal_name: str, *,return Nonewith contextlib.suppress(OSError): # tighten logs created 0644 by earlier releasesos.fchmod(fd, 0o600)+ # GNU ``timeout`` (Homebrew: ``gtimeout``) is absent from stock macOS; without it the detached+ # script still cannot block teardown, so run it unbounded rather than skip the diagnostic.+ timeout_bin = shutil.which("timeout") or shutil.which("gtimeout")+ bound = [timeout_bin, f"{timeout_seconds:.0f}"] if timeout_bin else []try: # start_new_session: outlive systemd killing our cgroup (KillMode=control-group) to flushreturn subprocess.Popen(- ["timeout", f"{timeout_seconds:.0f}", "bash", "-c", script], stdout=fd,+ [*bound, "bash", "-c", script], stdout=fd,stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL, start_new_session=True,close_fds=True).pidexcept OSError:diff --git a/hermes_cli/service_manager.py b/hermes_cli/service_manager.pyindex b79e1d22efd..72b06f7cdd2 100644--- a/hermes_cli/service_manager.py+++ b/hermes_cli/service_manager.py@@ -342,8 +342,8 @@ def _seed_supervise_skeleton(svc_dir: Path) -> None:if path.exists():returnpath.mkdir(parents=False, exist_ok=False)- path.chmod(mode)_chown_hermes(path)+ path.chmod(mode) # after chown: POSIX lets chown() clear the setgid bit event/ relies ondef _seed(root: Path) -> None:# Service-root event/ is the s6-svlisten1 subscription dir, distinct from supervise/event/.@@ -357,8 +357,8 @@ def _seed_supervise_skeleton(svc_dir: Path) -> None:control = supervise / "control"if not control.exists():os.mkfifo(control, 0o660)- control.chmod(0o660)_chown_hermes(control)+ control.chmod(0o660)_seed(svc_dir)log_dir = svc_dir / "log"diff --git a/tests/agent/lsp/test_client_e2e.py b/tests/agent/lsp/test_client_e2e.pyindex 6864008b318..8d954593eeb 100644--- a/tests/agent/lsp/test_client_e2e.py+++ b/tests/agent/lsp/test_client_e2e.py@@ -36,7 +36,7 @@ def _client(workspace: Path, script: str = "clean") -> LSPClient:async def test_client_lifecycle_clean(tmp_path: Path):"""Full lifecycle: spawn, initialize, open, get clean diagnostics, shutdown."""f = tmp_path / "x.py"- f.write_text("print('hi')\n")+ f.write_text("print('hi')\n", encoding="utf-8")client = _client(tmp_path, "clean")await client.start()@@ -55,7 +55,7 @@ async def test_client_lifecycle_clean(tmp_path: Path):@pytest.mark.asyncioasync def test_client_receives_published_errors(tmp_path: Path):f = tmp_path / "x.py"- f.write_text("print('hi')\n")+ f.write_text("print('hi')\n", encoding="utf-8")client = _client(tmp_path, "errors")await client.start()@@ -98,7 +98,7 @@ 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")+ f.write_text("print('hi')\n", encoding="utf-8")client = _client(tmp_path, script)await client.start()@@ -124,3 +124,22 @@ async def test_reader_failure_retires_client_and_rejects_later_work()finally:await client.shutdown()+++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:+ on Darwin the reaped PID can already belong to another process)."""+ client = _client(tmp_path, "clean")+ await client.start()+ proc = client._proc+ assert proc is not None+ signals: list[str] = []+ real_terminate, real_kill = proc.terminate, proc.kill+ proc.terminate = lambda: (signals.append("terminate"), real_terminate()) # type: ignore[method-assign]+ proc.kill = lambda: (signals.append("kill"), real_kill()) # type: ignore[method-assign]++ await client.shutdown()++ assert signals == []+ assert proc.returncode == 0diff --git a/tests/gateway/test_shutdown_forensics.py b/tests/gateway/test_shutdown_forensics.pyindex d6c15b4cea1..54edd00c8c9 100644--- a/tests/gateway/test_shutdown_forensics.py+++ b/tests/gateway/test_shutdown_forensics.py@@ -127,13 +127,17 @@ class TestArgvFreePersistence:# ---------------------------------------------------------------------------class TestSpawnAsyncDiagnostic:- # The diagnostic wraps its script in GNU coreutils ``timeout`` and the script- # body is Linux-only (``ps -eo ... comm``, ``/proc/loadavg``, ``dmesg``,- # ``pstree``). On hosts without ``timeout`` (macOS) Popen raises and the- # producer returns None by design (fail-soft), so the spawn can only be- # observed on Linux.@pytest.mark.linux_onlydef test_spawns_subprocess_and_writes_output(self, tmp_path):+ self._assert_diagnostic_written(tmp_path)++ @pytest.mark.macos_only+ def test_spawns_without_gnu_timeout_on_macos(self, tmp_path):+ """Stock macOS has no ``timeout`` binary and BSD ``ps``; the diagnostic still lands."""+ self._assert_diagnostic_written(tmp_path)++ @staticmethod+ def _assert_diagnostic_written(tmp_path):log_path = tmp_path / "diag.log"pid = sf.spawn_async_diagnostic(log_path, "SIGTERM", timeout_seconds=3.0)assert pid is not None and pid > 0