|
| 1 | +"""E2E tests for Extension Runner lifecycle.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +import socket |
| 7 | +import subprocess |
| 8 | +import sys |
| 9 | +import time |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import pytest |
| 13 | + |
| 14 | +psutil = pytest.importorskip("psutil") |
| 15 | + |
| 16 | +from tests.e2e.conftest import kill_group, sigint_group, start_server, wait_for_file, wait_for_port |
| 17 | + |
| 18 | + |
| 19 | +# --------------------------------------------------------------------------- |
| 20 | +# Minimal WM JSON-RPC client helpers |
| 21 | +# --------------------------------------------------------------------------- |
| 22 | + |
| 23 | + |
| 24 | +def _send_request(sock: socket.socket, method: str, params: dict, req_id: int) -> None: |
| 25 | + """Send a Content-Length-framed JSON-RPC request to the WM server.""" |
| 26 | + body = json.dumps( |
| 27 | + {"jsonrpc": "2.0", "id": req_id, "method": method, "params": params} |
| 28 | + ).encode() |
| 29 | + header = f"Content-Length: {len(body)}\r\n\r\n".encode() |
| 30 | + sock.sendall(header + body) |
| 31 | + |
| 32 | + |
| 33 | +def _read_response(sock: socket.socket, timeout: float = 30.0) -> dict: |
| 34 | + """Read a single Content-Length-framed JSON-RPC response from the WM server.""" |
| 35 | + sock.settimeout(timeout) |
| 36 | + raw = b"" |
| 37 | + while b"\r\n\r\n" not in raw: |
| 38 | + chunk = sock.recv(1) |
| 39 | + if not chunk: |
| 40 | + raise EOFError("Connection closed while reading response header") |
| 41 | + raw += chunk |
| 42 | + header_part, body_start = raw.split(b"\r\n\r\n", 1) |
| 43 | + length = int(header_part.split(b"Content-Length: ")[1]) |
| 44 | + body = body_start |
| 45 | + while len(body) < length: |
| 46 | + chunk = sock.recv(length - len(body)) |
| 47 | + if not chunk: |
| 48 | + raise EOFError("Connection closed while reading response body") |
| 49 | + body += chunk |
| 50 | + return json.loads(body) |
| 51 | + |
| 52 | + |
| 53 | +# --------------------------------------------------------------------------- |
| 54 | +# Fixtures |
| 55 | +# --------------------------------------------------------------------------- |
| 56 | + |
| 57 | + |
| 58 | +@pytest.fixture |
| 59 | +def workspace_dir_with_er(tmp_path: Path) -> Path: |
| 60 | + """Workspace with a dev_workspace env symlinked to the current Python venv. |
| 61 | +
|
| 62 | + Symlinking the active venv avoids creating a separate virtual environment: |
| 63 | + ``finecode_extension_runner`` is already installed here (it is a dev |
| 64 | + dependency of finecode itself), so the WM can start a real ER immediately. |
| 65 | +
|
| 66 | + The workspace declares one action backed by a built-in handler so that WM |
| 67 | + can validate the config and start the dev_workspace ER on ``workspace/addDir``. |
| 68 | + """ |
| 69 | + (tmp_path / "pyproject.toml").write_text( |
| 70 | + "[tool.finecode]\n\n" |
| 71 | + "[[tool.finecode.actions]]\n" |
| 72 | + 'name = "test_action"\n\n' |
| 73 | + "[[tool.finecode.actions.handlers]]\n" |
| 74 | + 'handler = "finecode_builtin_handlers.DumpConfigHandler"\n' |
| 75 | + 'env = "dev_workspace"\n' |
| 76 | + ) |
| 77 | + # Symlink current venv as the dev_workspace env. |
| 78 | + venvs_dir = tmp_path / ".venvs" |
| 79 | + venvs_dir.mkdir() |
| 80 | + current_venv = Path(sys.executable).parent.parent |
| 81 | + (venvs_dir / "dev_workspace").symlink_to(current_venv) |
| 82 | + return tmp_path |
| 83 | + |
| 84 | + |
| 85 | +# --------------------------------------------------------------------------- |
| 86 | +# Tests |
| 87 | +# --------------------------------------------------------------------------- |
| 88 | + |
| 89 | + |
| 90 | +def test_extension_runners_cleaned_up_on_wm_shutdown(workspace_dir_with_er, tmp_path): |
| 91 | + """Extension Runner subprocesses are terminated when the WM shuts down cleanly. |
| 92 | +
|
| 93 | + The WM's ``on_shutdown()`` hook sends ``shutdown`` + ``exit`` JSON-RPC |
| 94 | + messages to every running ER so they stop gracefully. Without this, ERs |
| 95 | + would be orphaned (re-parented to PID 1) when the WM exits — a ghost-process |
| 96 | + scenario that silently consumes resources. |
| 97 | +
|
| 98 | + Sequence: |
| 99 | + 1. Start WM in a workspace that has a dev_workspace ER configured. |
| 100 | + 2. Connect to WM and call ``workspace/addDir``, which discovers the project |
| 101 | + and starts the dev_workspace Extension Runner subprocess. |
| 102 | + 3. Poll via psutil until the ER child process appears. |
| 103 | + 4. Close the client connection, then send SIGINT to the WM process group. |
| 104 | + 5. Assert every ER PID recorded in step 3 is no longer alive. |
| 105 | + """ |
| 106 | + port_file = tmp_path / "wm_port" |
| 107 | + |
| 108 | + proc = start_server( |
| 109 | + [ |
| 110 | + "start-wm-server", |
| 111 | + "--port-file", str(port_file), |
| 112 | + "--disconnect-timeout", "10", |
| 113 | + ], |
| 114 | + cwd=workspace_dir_with_er, |
| 115 | + ) |
| 116 | + er_pids: set[int] = set() |
| 117 | + try: |
| 118 | + assert wait_for_file(port_file), ( |
| 119 | + "WM server did not write port file within 15 s — server failed to start" |
| 120 | + ) |
| 121 | + |
| 122 | + port = int(port_file.read_text().strip()) |
| 123 | + assert wait_for_port("127.0.0.1", port), ( |
| 124 | + f"WM server not accepting connections on port {port}" |
| 125 | + ) |
| 126 | + |
| 127 | + with socket.create_connection(("127.0.0.1", port)) as sock: |
| 128 | + # Tell WM to load the workspace directory. This discovers the |
| 129 | + # project, reads its config, and starts the dev_workspace ER. |
| 130 | + _send_request( |
| 131 | + sock, |
| 132 | + "workspace/addDir", |
| 133 | + {"dir_path": str(workspace_dir_with_er)}, |
| 134 | + req_id=1, |
| 135 | + ) |
| 136 | + _read_response(sock, timeout=30.0) |
| 137 | + |
| 138 | + # Poll until the ER child process appears in WM's process tree. |
| 139 | + wm_process = psutil.Process(proc.pid) |
| 140 | + deadline = time.monotonic() + 30.0 |
| 141 | + while time.monotonic() < deadline: |
| 142 | + try: |
| 143 | + children = wm_process.children(recursive=True) |
| 144 | + er_procs = [ |
| 145 | + c for c in children |
| 146 | + if "finecode_extension_runner" in " ".join(c.cmdline()) |
| 147 | + ] |
| 148 | + if er_procs: |
| 149 | + er_pids = {p.pid for p in er_procs} |
| 150 | + break |
| 151 | + except psutil.NoSuchProcess: |
| 152 | + break |
| 153 | + time.sleep(0.5) |
| 154 | + |
| 155 | + assert er_pids, ( |
| 156 | + "Extension Runner process did not start within 30 s after " |
| 157 | + "workspace/addDir — check that finecode_extension_runner is " |
| 158 | + "installed in the active venv" |
| 159 | + ) |
| 160 | + |
| 161 | + # Connection closed; SIGINT WM before the disconnect timer fires. |
| 162 | + sigint_group(proc) |
| 163 | + |
| 164 | + try: |
| 165 | + proc.wait(timeout=15) |
| 166 | + except subprocess.TimeoutExpired: |
| 167 | + pytest.fail("WM did not exit within 15 s after SIGINT") |
| 168 | + finally: |
| 169 | + kill_group(proc) |
| 170 | + |
| 171 | + # Every ER that was alive before shutdown must be gone now. |
| 172 | + for pid in er_pids: |
| 173 | + assert not psutil.pid_exists(pid), ( |
| 174 | + f"Extension Runner PID {pid} is still alive after WM shutdown — " |
| 175 | + "on_shutdown() may not have sent exit to all runners" |
| 176 | + ) |
0 commit comments