| # Copyright 2026 The Fuchsia Authors. All rights reserved. | |
| # Use of this source code is governed by a BSD-style license that can be | |
| # found in the LICENSE file. | |
| import asyncio | |
| import contextlib | |
| import json | |
| import os | |
| import shutil | |
| import signal | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import threading | |
| import types | |
| import unittest | |
| from collections.abc import AsyncIterator, Callable | |
| from pathlib import Path | |
| from typing import Any | |
| from unittest import mock | |
| from unittest.mock import AsyncMock, MagicMock, Mock, patch | |
| import daemon_manager.manager as manager_mod | |
| from daemon_manager import ( | |
| DaemonAlreadyRunningError, | |
| DaemonConnectionError, | |
| DaemonCrashError, | |
| DaemonHandshakeError, | |
| DaemonManager, | |
| DaemonStartupTimeoutError, | |
| ) | |
| from daemon_manager.manager import _cleanup_process, _send_signal_and_wait | |
| from shared.protocol import PROTOCOL_VERSION | |
| def spawn_fake_daemon(write_fd: int) -> subprocess.Popen[bytes]: | |
| """Spawns a lightweight python fake process that simulates the daemon's startup behavior. | |
| This fake process will: | |
| 1. Mark the write end of the pipe (write_fd) as inheritable. | |
| 2. Write a single byte ("1") to the pipe to signal that it is ready. | |
| 3. Sleep indefinitely (or for a long time) simulating a running daemon. | |
| Why: | |
| We spawn a real Python subprocess rather than using low-level mocks (like os.killpg, | |
| os.getpgid, or subprocess.Popen mock objects). This provides high-fidelity test coverage | |
| because: | |
| - It verifies the actual OS-level process group signal delivery (SIGTERM/SIGKILL to the PGID). | |
| - It avoids host process collisions (using real, active PIDs/PGIDs instead of fake integer mocks). | |
| - It accurately tests the interaction of raw file descriptors, pipes, and the asyncio event loop. | |
| Trade-offs: | |
| - Spawning a new Python interpreter process adds a tiny overhead of 10-20ms per test run. | |
| - This minor overhead is vastly outweighed by the massive gains in safety, realism, and | |
| prevention of fragile mock configurations. | |
| """ | |
| # We want a portable python one-liner that can be executed on any host system. | |
| # The code must set write_fd as inheritable, write b"1" to it, and sleep. | |
| code = ( | |
| f"import os, time; " | |
| f"os.set_inheritable({write_fd}, True); " | |
| f"os.write({write_fd}, b'1'); " | |
| f"time.sleep(100)" | |
| ) | |
| # We set start_new_session=True so it gets its own PGID (critical for process group signaling). | |
| return subprocess.Popen( | |
| [sys.executable, "-c", code], | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| start_new_session=True, | |
| pass_fds=[write_fd], | |
| ) | |
| class _FakeClock: | |
| def __init__(self, initial: float) -> None: | |
| self.now = initial | |
| def monotonic(self) -> float: | |
| return self.now | |
| def advance(self, seconds: float) -> None: | |
| self.now += seconds | |
| def sleep(self, seconds: float) -> None: | |
| self.now += seconds | |
| def _advance_clock(clock: _FakeClock, seconds: float) -> Callable[..., None]: | |
| def _effect(*_args: object, **_kwargs: object) -> None: | |
| clock.advance(seconds) | |
| return _effect | |
| def _make_asyncio_overlay(**overrides: Any) -> types.SimpleNamespace: | |
| attrs = { | |
| name: getattr(asyncio, name) | |
| for name in dir(asyncio) | |
| if not name.startswith("__") | |
| } | |
| attrs.update(overrides) | |
| return types.SimpleNamespace(**attrs) | |
| def _make_mock_popen( | |
| *, | |
| pid: int | None = None, | |
| poll_return: int | None = None, | |
| returncode: int | None = None, | |
| spec_set: bool = True, | |
| ) -> mock.NonCallableMock: | |
| mock_proc = mock.create_autospec( | |
| subprocess.Popen, | |
| instance=True, | |
| spec_set=spec_set if pid is None and returncode is None else False, | |
| ) | |
| assert isinstance(mock_proc, mock.NonCallableMock) | |
| if pid is not None: | |
| mock_proc.pid = pid | |
| if returncode is not None: | |
| mock_proc.returncode = returncode | |
| mock_proc.poll.return_value = poll_return | |
| return mock_proc | |
| class TestDaemonManager(unittest.IsolatedAsyncioTestCase): | |
| def setUp(self) -> None: | |
| super().setUp() | |
| self.spawned_processes: list[subprocess.Popen[bytes]] = [] | |
| def tearDown(self) -> None: | |
| patch.stopall() | |
| for proc in self.spawned_processes: | |
| if proc.poll() is None: | |
| try: | |
| pgid = os.getpgid(proc.pid) | |
| if pgid != os.getpgrp(): | |
| os.killpg(pgid, signal.SIGKILL) | |
| else: | |
| proc.kill() | |
| except Exception: | |
| try: | |
| proc.kill() | |
| except Exception: | |
| pass | |
| proc.wait() | |
| super().tearDown() | |
| def tracking_spawn(self, write_fd: int) -> subprocess.Popen[bytes]: | |
| """Spawns a fake daemon process and tracks it for cleanup.""" | |
| proc = spawn_fake_daemon(write_fd) | |
| self.spawned_processes.append(proc) | |
| return proc | |
| def _make_mock_uds_connection( | |
| self, response: dict[str, Any] | bytes = b'{"success": true}\n' | |
| ) -> tuple[AsyncMock, MagicMock]: | |
| """Creates a mock reader and writer pair simulating a UDS response.""" | |
| mock_reader = AsyncMock() | |
| mock_writer = MagicMock() | |
| mock_writer.drain = AsyncMock() | |
| mock_writer.wait_closed = AsyncMock() | |
| if isinstance(response, bytes): | |
| mock_reader.readline.return_value = response | |
| else: | |
| mock_reader.readline.return_value = ( | |
| json.dumps(response).encode("utf-8") + b"\n" | |
| ) | |
| return mock_reader, mock_writer | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("asyncio.open_unix_connection") | |
| async def test_connect_to_running_daemon_success( | |
| self, mock_connect: Mock, mock_uds_path: Mock | |
| ) -> None: | |
| """Tests that connect_to_running_daemon succeeds silently when UDS responds success.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_reader, mock_writer = self._make_mock_uds_connection( | |
| {"success": True} | |
| ) | |
| mock_connect.return_value = (mock_reader, mock_writer) | |
| manager = DaemonManager(socket_path=mock_uds_path, port=1234) | |
| await manager.connect_to_running_daemon() | |
| mock_connect.assert_called_once() | |
| mock_writer.write.assert_called_once() | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("asyncio.open_unix_connection") | |
| async def test_connect_to_running_daemon_failure( | |
| self, mock_connect: Mock, mock_uds_path: Mock | |
| ) -> None: | |
| """Tests that connect_to_running_daemon raises DaemonConnectionError when daemon returns success=False.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_reader, mock_writer = self._make_mock_uds_connection( | |
| {"success": False, "message": "Connect failed"} | |
| ) | |
| mock_connect.return_value = (mock_reader, mock_writer) | |
| manager = DaemonManager(socket_path=mock_uds_path, port=1234) | |
| with self.assertRaises(DaemonConnectionError) as ctx: | |
| await manager.connect_to_running_daemon() | |
| self.assertIn("Connect failed", str(ctx.exception)) | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("asyncio.open_unix_connection") | |
| async def test_connect_to_running_daemon_connection_error( | |
| self, mock_connect: Mock, mock_uds_path: Mock | |
| ) -> None: | |
| """Tests that connect_to_running_daemon raises DaemonConnectionError on connection failure.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_connect.side_effect = ConnectionRefusedError("Connection refused") | |
| manager = DaemonManager(socket_path=mock_uds_path, port=1234) | |
| with self.assertRaises(DaemonConnectionError) as ctx: | |
| await manager.connect_to_running_daemon() | |
| self.assertIn("Connection refused", str(ctx.exception)) | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("daemon_manager.manager.DaemonManager.do_handshake_and_connect") | |
| @patch("daemon_manager.manager.DaemonManager.connect_to_running_daemon") | |
| async def test_start_daemon_already_running_connect_success( | |
| self, | |
| mock_connect_helper: Mock, | |
| mock_handshake: Mock, | |
| mock_uds_path: Mock, | |
| ) -> None: | |
| """Tests that start returns None when connect_to_existing is True and helper succeeds.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_handshake.return_value = True # Active daemon | |
| mock_connect_helper.return_value = None # Success | |
| manager = DaemonManager( | |
| socket_path=mock_uds_path, port=1234, connect_to_existing=True | |
| ) | |
| res = await manager.start() | |
| self.assertIsNone(res) | |
| mock_connect_helper.assert_called_once() | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("daemon_manager.manager.DaemonManager.do_handshake_and_connect") | |
| @patch("daemon_manager.manager.DaemonManager.connect_to_running_daemon") | |
| async def test_start_daemon_already_running_connect_failure( | |
| self, | |
| mock_connect_helper: Mock, | |
| mock_handshake: Mock, | |
| mock_uds_path: Mock, | |
| ) -> None: | |
| """Tests that start propagates DaemonConnectionError.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_handshake.return_value = True | |
| mock_connect_helper.side_effect = DaemonConnectionError( | |
| "Failed to connect" | |
| ) | |
| manager = DaemonManager( | |
| socket_path=mock_uds_path, port=1234, connect_to_existing=True | |
| ) | |
| with self.assertRaises(DaemonConnectionError): | |
| await manager.start() | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("daemon_manager.manager.DaemonManager.do_handshake_and_connect") | |
| async def test_start_daemon_already_running_no_connect( | |
| self, mock_handshake: Mock, mock_uds_path: Mock | |
| ) -> None: | |
| """Tests that start raises DaemonAlreadyRunningError when connect_to_existing is False.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_handshake.return_value = True | |
| manager = DaemonManager( | |
| socket_path=mock_uds_path, port=1234, connect_to_existing=False | |
| ) | |
| with self.assertRaises(DaemonAlreadyRunningError): | |
| await manager.start() | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("daemon_manager.manager.DaemonManager.do_handshake_and_connect") | |
| @patch("daemon_manager.manager.DaemonManager._spawn_daemon_process") | |
| async def test_start_daemon_stale_socket_cleanup( | |
| self, | |
| mock_spawn: Mock, | |
| mock_handshake: Mock, | |
| mock_uds_path: Mock, | |
| ) -> None: | |
| """Tests that start unlinks UDS socket when handshake returns None (stale socket).""" | |
| mock_uds_path.exists.return_value = True | |
| mock_handshake.return_value = None # Stale socket | |
| # Mock spawn to stop execution after cleanup | |
| mock_spawn.side_effect = RuntimeError("Stop execution") | |
| manager = DaemonManager(socket_path=mock_uds_path, port=1234) | |
| with self.assertRaises(RuntimeError) as ctx: | |
| await manager.start() | |
| self.assertEqual(str(ctx.exception), "Stop execution") | |
| mock_uds_path.unlink.assert_called_once_with(missing_ok=True) | |
| @patch("daemon_manager.manager.FxCmd") | |
| @patch("os.set_inheritable") | |
| @patch("subprocess.Popen") | |
| def test_spawn_daemon_process( | |
| self, | |
| mock_popen: Mock, | |
| mock_set_inheritable: Mock, | |
| mock_fx_cmd_class: Mock, | |
| ) -> None: | |
| """Tests that _spawn_daemon_process spawns Popen process group with correct pass_fds.""" | |
| mock_fx_cmd = mock_fx_cmd_class.return_value | |
| mock_fx_cmd.command_line.return_value = [ | |
| "fx", | |
| "zxdb-daemon", | |
| "--port", | |
| "1234", | |
| "--ready-fd=5", | |
| ] | |
| mock_proc = Mock() | |
| mock_popen.return_value = mock_proc | |
| manager = DaemonManager(port=1234) | |
| proc = manager._spawn_daemon_process(5) | |
| self.assertEqual(proc, mock_proc) | |
| mock_fx_cmd.command_line.assert_called_once_with( | |
| "zxdb-daemon", "--port", "1234", "--ready-fd=5" | |
| ) | |
| mock_set_inheritable.assert_called_once_with(5, True) | |
| mock_popen.assert_called_once_with( | |
| ["fx", "zxdb-daemon", "--port", "1234", "--ready-fd=5"], | |
| stdout=subprocess.DEVNULL, | |
| stderr=subprocess.DEVNULL, | |
| start_new_session=True, | |
| pass_fds=[5], | |
| ) | |
| async def test_wait_for_ready_signal_success(self) -> None: | |
| """Tests _wait_for_ready_signal completes successfully when sync byte is written.""" | |
| r, w = os.pipe() | |
| try: | |
| manager = DaemonManager() | |
| task = asyncio.create_task(manager._wait_for_ready_signal(r)) | |
| os.write(w, b"1") | |
| await task | |
| finally: | |
| os.close(w) | |
| try: | |
| os.close(r) | |
| except OSError: | |
| pass | |
| async def test_wait_for_ready_signal_timeout(self) -> None: | |
| """Tests _wait_for_ready_signal raises DaemonStartupTimeoutError on timeout.""" | |
| r, w = os.pipe() | |
| try: | |
| manager = DaemonManager(startup_timeout=0.01) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager._wait_for_ready_signal(r) | |
| finally: | |
| os.close(w) | |
| try: | |
| os.close(r) | |
| except OSError: | |
| pass | |
| async def test_wait_for_ready_signal_premature_eof(self) -> None: | |
| """Tests _wait_for_ready_signal raises DaemonCrashError when pipe is closed prematurely (EOF).""" | |
| r, w = os.pipe() | |
| try: | |
| manager = DaemonManager() | |
| task = asyncio.create_task(manager._wait_for_ready_signal(r)) | |
| await asyncio.sleep(0) | |
| os.close(w) | |
| w = -1 | |
| with self.assertRaises(DaemonCrashError) as ctx: | |
| await task | |
| self.assertIn("Daemon exited prematurely", str(ctx.exception)) | |
| finally: | |
| if w != -1: | |
| os.close(w) | |
| try: | |
| os.close(r) | |
| except OSError: | |
| pass | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| @patch("asyncio.open_unix_connection") | |
| @patch("daemon_manager.manager.DaemonManager.do_handshake_and_connect") | |
| @patch("daemon_manager.manager.DaemonManager._wait_for_ready_signal") | |
| async def test_start_new_daemon_success( | |
| self, | |
| mock_wait_ready: Mock, | |
| mock_handshake: Mock, | |
| mock_open_connection: Mock, | |
| mock_uds_path: Mock, | |
| ) -> None: | |
| """Tests starting a new daemon process successfully.""" | |
| mock_uds_path.exists.return_value = False | |
| mock_proc = _make_mock_popen() | |
| mock_spawn_fn = Mock(return_value=mock_proc) | |
| mock_reader, mock_writer = self._make_mock_uds_connection( | |
| {"success": True} | |
| ) | |
| mock_open_connection.return_value = (mock_reader, mock_writer) | |
| mock_handshake.return_value = True | |
| manager = DaemonManager( | |
| socket_path=mock_uds_path, | |
| port=1234, | |
| spawn_fn=mock_spawn_fn, | |
| ) | |
| proc = await manager.start() | |
| self.assertEqual(proc, mock_proc) | |
| mock_spawn_fn.assert_called_once() | |
| mock_wait_ready.assert_called_once() | |
| mock_handshake.assert_called_once() | |
| mock_open_connection.assert_called_once_with(mock_uds_path) | |
| mock_writer.write.assert_called_once() | |
| async def test_start_new_daemon_handshake_failure(self) -> None: | |
| """Tests startup failure because handshake fails after signaling ready.""" | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| fake_socket = ( | |
| Path(temp_dir) / "non_existent_handshake_failure_test.sock" | |
| ) | |
| manager = DaemonManager( | |
| socket_path=fake_socket, | |
| port=1234, | |
| spawn_fn=self.tracking_spawn, | |
| ) | |
| # Startup naturally raises DaemonHandshakeError since connecting to fake_socket fails. | |
| with self.assertRaises(DaemonHandshakeError) as ctx: | |
| await manager.start() | |
| self.assertIn( | |
| "Daemon started but failed to respond to handshake in time.", | |
| str(ctx.exception), | |
| ) | |
| # Verify that the fake process is terminated and cleaned up cleanly. | |
| self.assertEqual(len(self.spawned_processes), 1) | |
| spawned_proc = self.spawned_processes[0] | |
| self.assertIsNotNone( | |
| spawned_proc.poll() | |
| ) # It should have exited (terminated) | |
| @patch("asyncio.open_unix_connection") | |
| async def test_start_new_daemon_session_startup_timeout( | |
| self, | |
| mock_open_connection: Mock, | |
| ) -> None: | |
| """Tests startup failure when connecting/establishing session times out.""" | |
| mock_reader = AsyncMock() | |
| mock_writer = MagicMock() | |
| mock_writer.drain = AsyncMock() | |
| mock_writer.wait_closed = AsyncMock() | |
| mock_reader.readline.return_value = f'{{"success": true, "body": {{"protocol_version": {PROTOCOL_VERSION}}}}}\n'.encode( | |
| "utf-8" | |
| ) | |
| # Mock the first connection (handshake) to succeed, and the second | |
| # connection (session start request) to timeout. | |
| mock_open_connection.side_effect = [ | |
| (mock_reader, mock_writer), | |
| asyncio.TimeoutError("Connection timeout"), | |
| ] | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| fake_socket = Path(temp_dir) / "non_existent_timeout_test.sock" | |
| manager = DaemonManager( | |
| socket_path=fake_socket, | |
| port=1234, | |
| spawn_fn=self.tracking_spawn, | |
| ) | |
| with self.assertRaises(DaemonConnectionError): | |
| await manager.start() | |
| # Verify that the fake process is terminated and cleaned up cleanly. | |
| self.assertEqual(len(self.spawned_processes), 1) | |
| spawned_proc = self.spawned_processes[0] | |
| self.assertIsNotNone(spawned_proc.poll()) | |
| @patch("socket.socket") | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| def test_stop_sync_socket_does_not_exist( | |
| self, mock_uds_path: Mock, mock_socket_class: Mock | |
| ) -> None: | |
| """Tests that stop_sync() returns silently when the UDS socket file does not exist.""" | |
| mock_uds_path.exists.return_value = False | |
| manager = DaemonManager(socket_path=mock_uds_path) | |
| manager.stop_sync() | |
| mock_uds_path.exists.assert_called_once() | |
| mock_socket_class.assert_not_called() | |
| @patch("socket.socket") | |
| @patch("daemon_manager.manager.UDS_PATH") | |
| def test_stop_sync_stale_socket( | |
| self, mock_uds_path: Mock, mock_socket_class: Mock | |
| ) -> None: | |
| """Tests that stop_sync() unlinks the stale socket file and returns when connection is refused.""" | |
| mock_uds_path.exists.return_value = True | |
| mock_socket = MagicMock() | |
| mock_socket.__enter__.return_value = mock_socket | |
| mock_socket_class.return_value = mock_socket | |
| mock_socket.connect.side_effect = ConnectionRefusedError( | |
| "Connection refused" | |
| ) | |
| manager = DaemonManager(socket_path=mock_uds_path) | |
| manager.stop_sync() | |
| mock_socket_class.assert_called_once() | |
| mock_socket.connect.assert_called_once_with(str(mock_uds_path)) | |
| mock_uds_path.unlink.assert_called_once_with(missing_ok=True) | |
| @patch("daemon_manager.manager.DaemonManager.stop_sync") | |
| async def test_stop_delegates_to_stop_sync( | |
| self, mock_stop_sync: Mock | |
| ) -> None: | |
| """Tests that async stop() delegates stop_sync to asyncio.to_thread.""" | |
| manager = DaemonManager() | |
| await manager.stop(timeout=3.0) | |
| mock_stop_sync.assert_called_once_with(3.0) | |
| @patch("daemon_manager.manager._cleanup_process") | |
| def test_stop_sync_does_not_delegate_cleanup_when_proc_absent( | |
| self, mock_cleanup: Mock | |
| ) -> None: | |
| """Tests that stop_sync does not call _cleanup_process if _proc is None.""" | |
| mock_socket_path = MagicMock() | |
| mock_socket_path.exists.return_value = False | |
| manager = DaemonManager(socket_path=mock_socket_path) | |
| manager._proc = None | |
| manager.stop_sync() | |
| mock_cleanup.assert_not_called() | |
| @patch("daemon_manager.manager._send_signal_and_wait") | |
| def test_cleanup_process_already_dead(self, mock_send_signal: Mock) -> None: | |
| """Tests that _cleanup_process does nothing if the process is already dead.""" | |
| mock_proc = MagicMock(spec=subprocess.Popen) | |
| mock_proc.poll.return_value = 0 | |
| _cleanup_process(mock_proc) | |
| mock_send_signal.assert_not_called() | |
| @patch("daemon_manager.manager._send_signal_and_wait") | |
| def test_cleanup_process_graceful_exit( | |
| self, mock_send_signal: Mock | |
| ) -> None: | |
| """Tests that _cleanup_process tries SIGTERM first and succeeds.""" | |
| mock_proc = MagicMock(spec=subprocess.Popen) | |
| mock_proc.poll.return_value = None | |
| mock_send_signal.return_value = True | |
| _cleanup_process(mock_proc) | |
| mock_send_signal.assert_called_once_with( | |
| mock_proc, signal.SIGTERM, mock_proc.terminate, 20.0, pgid=None | |
| ) | |
| @patch("daemon_manager.manager._send_signal_and_wait") | |
| def test_cleanup_process_fallback_to_sigkill( | |
| self, mock_send_signal: Mock | |
| ) -> None: | |
| """Tests that _cleanup_process falls back to SIGKILL if SIGTERM fails or raises.""" | |
| cases = ( | |
| ("sigterm_returns_false", False), | |
| ("sigterm_raises_exception", RuntimeError("signal failed")), | |
| ) | |
| for case_name, sigterm_outcome in cases: | |
| with self.subTest(case=case_name): | |
| mock_send_signal.reset_mock() | |
| mock_proc = MagicMock(spec=subprocess.Popen) | |
| mock_proc.poll.return_value = None | |
| mock_send_signal.side_effect = (sigterm_outcome, True) | |
| _cleanup_process(mock_proc) | |
| self.assertEqual(mock_send_signal.call_count, 2) | |
| mock_send_signal.assert_any_call( | |
| mock_proc, | |
| signal.SIGTERM, | |
| mock_proc.terminate, | |
| 20.0, | |
| pgid=None, | |
| ) | |
| mock_send_signal.assert_any_call( | |
| mock_proc, signal.SIGKILL, mock_proc.kill, 2.0, pgid=None | |
| ) | |
| def _configure_blocking_cleanup( | |
| self, | |
| mock_cleanup: mock.Mock, | |
| ) -> tuple[threading.Event, threading.Event]: | |
| cleanup_entered = threading.Event() | |
| release_cleanup = threading.Event() | |
| self.addCleanup(release_cleanup.set) | |
| def cleanup(_proc: subprocess.Popen[bytes]) -> None: | |
| cleanup_entered.set() | |
| release_cleanup.wait(timeout=5.0) | |
| mock_cleanup.side_effect = cleanup | |
| return cleanup_entered, release_cleanup | |
| def _make_socket_spawn_manager( | |
| self, | |
| mock_proc: mock.NonCallableMock, | |
| *, | |
| write_ready: bool = True, | |
| ) -> tuple[Path, DaemonManager, asyncio.Event]: | |
| temp_dir = self.enterContext(tempfile.TemporaryDirectory()) | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| ready_written = asyncio.Event() | |
| def spawn_with_socket(write_fd: int) -> subprocess.Popen[bytes]: | |
| if write_ready: | |
| sock_path.touch() | |
| os.write(write_fd, b"1") | |
| ready_written.set() | |
| return mock_proc | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=5.0, | |
| spawn_fn=spawn_with_socket, | |
| ) | |
| return sock_path, manager, ready_written | |
| @contextlib.asynccontextmanager | |
| async def _cancelled_start_during_handshake( | |
| self, | |
| manager: DaemonManager, | |
| ready_written: asyncio.Event, | |
| cleanup_entered: asyncio.Event | threading.Event, | |
| release_cleanup: asyncio.Event | threading.Event, | |
| ) -> AsyncIterator[asyncio.Task[subprocess.Popen[bytes] | None]]: | |
| handshake_entered = asyncio.Event() | |
| async def blocked_handshake( | |
| timeout: float | None = None, | |
| ) -> bool | None: | |
| del timeout | |
| handshake_entered.set() | |
| await asyncio.Event().wait() | |
| return True | |
| with mock.patch.object( | |
| manager, | |
| "do_handshake_and_connect", | |
| autospec=True, | |
| side_effect=blocked_handshake, | |
| ): | |
| start_task = asyncio.create_task(manager.start()) | |
| try: | |
| await asyncio.wait_for(ready_written.wait(), timeout=1.0) | |
| await asyncio.wait_for(handshake_entered.wait(), timeout=1.0) | |
| start_task.cancel() | |
| if isinstance(cleanup_entered, asyncio.Event): | |
| await asyncio.wait_for(cleanup_entered.wait(), timeout=1.0) | |
| else: | |
| self.assertTrue( | |
| await asyncio.to_thread(cleanup_entered.wait, 5.0) | |
| ) | |
| yield start_task | |
| finally: | |
| release_cleanup.set() | |
| if not start_task.done(): | |
| start_task.cancel() | |
| await asyncio.gather(start_task, return_exceptions=True) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| async def test_start_failure_offloads_cleanup_process_to_thread( | |
| self, mock_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that start() runs _cleanup_process on a worker thread without blocking the event loop.""" | |
| cleanup_entered, release_cleanup = self._configure_blocking_cleanup( | |
| mock_cleanup | |
| ) | |
| mock_proc = _make_mock_popen() | |
| _sock_path, manager, _ready_written = self._make_socket_spawn_manager( | |
| mock_proc, write_ready=False | |
| ) | |
| start_task = asyncio.create_task(manager.start()) | |
| self.assertTrue(await asyncio.to_thread(cleanup_entered.wait, 5.0)) | |
| # Event loop remains responsive while _cleanup_process blocks. | |
| await asyncio.wait_for(asyncio.sleep(0), timeout=0.5) | |
| self.assertFalse(start_task.done()) | |
| release_cleanup.set() | |
| with self.assertRaises(DaemonCrashError): | |
| await asyncio.wait_for(start_task, timeout=1.0) | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| async def test_start_cancellation_waits_for_cleanup_and_unlinks_socket( | |
| self, mock_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that repeated cancellation of start() waits for _cleanup_process and unlinks socket_path.""" | |
| cleanup_entered, release_cleanup = self._configure_blocking_cleanup( | |
| mock_cleanup | |
| ) | |
| mock_proc = _make_mock_popen() | |
| sock_path, manager, ready_written = self._make_socket_spawn_manager( | |
| mock_proc | |
| ) | |
| async with self._cancelled_start_during_handshake( | |
| manager, ready_written, cleanup_entered, release_cleanup | |
| ) as start_task: | |
| # Send repeated cancellations while _cleanup_process is blocked. | |
| start_task.cancel() | |
| await asyncio.sleep(0) | |
| start_task.cancel() | |
| await asyncio.sleep(0) | |
| self.assertFalse(start_task.done()) | |
| self.assertTrue(sock_path.exists()) | |
| release_cleanup.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(start_task, timeout=1.0) | |
| self.assertFalse(sock_path.exists()) | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| async def test_start_failure_preserves_primary_error_when_unlink_raises_oserror( | |
| self, mock_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that non-ENOENT OSError from socket_path.unlink does not mask startup errors.""" | |
| temp_dir = self.enterContext(tempfile.TemporaryDirectory()) | |
| blocking_file = Path(temp_dir) / "not_a_dir" | |
| blocking_file.touch() | |
| bad_sock_path = blocking_file / "daemon.sock" | |
| mock_proc = _make_mock_popen() | |
| def spawn_ready(write_fd: int) -> subprocess.Popen[bytes]: | |
| os.write(write_fd, b"1") | |
| return mock_proc | |
| manager = DaemonManager( | |
| socket_path=bad_sock_path, | |
| startup_timeout=5.0, | |
| spawn_fn=spawn_ready, | |
| ) | |
| with mock.patch.object( | |
| manager, | |
| "do_handshake_and_connect", | |
| autospec=True, | |
| return_value=None, | |
| ), self.assertLogs(manager_mod._LOGGER, level="WARNING") as logs: | |
| with self.assertRaises(DaemonHandshakeError): | |
| await manager.start() | |
| self.assertIn("Failed to unlink daemon socket", "\n".join(logs.output)) | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| async def test_start_cancellation_logs_unlink_error_before_reraising( | |
| self, mock_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that socket_path.unlink OSError logs a warning and does not mask CancelledError.""" | |
| temp_dir = self.enterContext(tempfile.TemporaryDirectory()) | |
| blocking_file = Path(temp_dir) / "not_a_dir" | |
| blocking_file.touch() | |
| bad_sock_path = blocking_file / "daemon.sock" | |
| cleanup_entered, release_cleanup = self._configure_blocking_cleanup( | |
| mock_cleanup | |
| ) | |
| ready_written = asyncio.Event() | |
| mock_proc = _make_mock_popen() | |
| def spawn_ready(write_fd: int) -> subprocess.Popen[bytes]: | |
| os.write(write_fd, b"1") | |
| ready_written.set() | |
| return mock_proc | |
| manager = DaemonManager( | |
| socket_path=bad_sock_path, | |
| startup_timeout=5.0, | |
| spawn_fn=spawn_ready, | |
| ) | |
| async with self._cancelled_start_during_handshake( | |
| manager, ready_written, cleanup_entered, release_cleanup | |
| ) as start_task: | |
| with self.assertLogs(manager_mod._LOGGER, level="WARNING") as logs: | |
| release_cleanup.set() | |
| with self.assertRaises(asyncio.CancelledError): | |
| await asyncio.wait_for(start_task, timeout=1.0) | |
| self.assertIn("Failed to unlink daemon socket", "\n".join(logs.output)) | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| async def test_start_failure_unlinks_socket_after_cleanup( | |
| self, mock_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that failed start() unlinks socket_path only after _cleanup_process completes.""" | |
| events: list[str] = [] | |
| mock_proc = _make_mock_popen() | |
| sock_path, manager, _ready_written = self._make_socket_spawn_manager( | |
| mock_proc | |
| ) | |
| def record_cleanup(_proc: subprocess.Popen[bytes]) -> None: | |
| self.assertTrue(sock_path.exists()) | |
| events.append("cleanup") | |
| mock_cleanup.side_effect = record_cleanup | |
| orig_unlink = Path.unlink | |
| def record_unlink(self_path: Path, missing_ok: bool = False) -> None: | |
| if self_path == sock_path: | |
| events.append("unlink") | |
| orig_unlink(self_path, missing_ok=missing_ok) | |
| with mock.patch.object( | |
| manager, | |
| "do_handshake_and_connect", | |
| autospec=True, | |
| return_value=None, | |
| ), mock.patch.object( | |
| Path, "unlink", autospec=True, side_effect=record_unlink | |
| ): | |
| with self.assertRaises(DaemonHandshakeError): | |
| await manager.start() | |
| self.assertFalse(sock_path.exists()) | |
| self.assertSequenceEqual(events, ("cleanup", "unlink")) | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_send_signal_and_wait_separate_group( | |
| self, mock_os: mock.Mock, mock_time: mock.Mock | |
| ) -> None: | |
| """Tests that _send_signal_and_wait signals PGID and waits for group exit.""" | |
| mock_proc = _make_mock_popen() | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| mock_time.sleep.side_effect = clock.sleep | |
| killpg_calls = 0 | |
| def killpg_effect(_pgid: int, sig: int) -> None: | |
| nonlocal killpg_calls | |
| killpg_calls += 1 | |
| if sig == signal.SIGTERM: | |
| clock.advance(0.5) | |
| return | |
| if killpg_calls >= 3: | |
| raise ProcessLookupError() | |
| mock_os.killpg.side_effect = killpg_effect | |
| mock_proc.wait.side_effect = _advance_clock(clock, 0.5) | |
| fallback = Mock() | |
| exited = _send_signal_and_wait( | |
| mock_proc, signal.SIGTERM, fallback, 3.0, pgid=456 | |
| ) | |
| self.assertTrue(exited) | |
| self.assertSequenceEqual( | |
| mock_os.killpg.call_args_list, | |
| ( | |
| mock.call(456, signal.SIGTERM), | |
| mock.call(456, 0), | |
| mock.call(456, 0), | |
| ), | |
| ) | |
| fallback.assert_not_called() | |
| mock_proc.wait.assert_called_once_with(timeout=2.5) | |
| mock_time.sleep.assert_called_once_with(0.02) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_send_signal_and_wait_same_group(self, mock_os: mock.Mock) -> None: | |
| """Tests that _send_signal_and_wait uses fallback when pgid is None.""" | |
| mock_proc = _make_mock_popen() | |
| fallback = Mock() | |
| exited = _send_signal_and_wait( | |
| mock_proc, signal.SIGTERM, fallback, 3.0, pgid=None | |
| ) | |
| self.assertTrue(exited) | |
| mock_os.killpg.assert_not_called() | |
| fallback.assert_called_once_with() | |
| mock_proc.wait.assert_called_once_with(timeout=3.0) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_send_signal_and_wait_returns_poll_status_on_probe_permission_error( | |
| self, mock_os: mock.Mock, mock_time: mock.Mock | |
| ) -> None: | |
| """Tests that PermissionError while probing PGID stops polling and returns proc exit status.""" | |
| mock_time.monotonic.return_value = 100.0 | |
| fallback = Mock() | |
| with self.subTest(case="exited_process"): | |
| mock_os.killpg.reset_mock() | |
| mock_time.sleep.reset_mock() | |
| mock_proc = _make_mock_popen(poll_return=0) | |
| mock_proc.wait.return_value = 0 | |
| mock_os.killpg.side_effect = ( | |
| None, | |
| PermissionError("Operation not permitted"), | |
| ) | |
| exited = _send_signal_and_wait( | |
| mock_proc, signal.SIGTERM, fallback, 3.0, pgid=456 | |
| ) | |
| self.assertTrue(exited) | |
| mock_time.sleep.assert_not_called() | |
| mock_proc.wait.assert_called_once_with(timeout=3.0) | |
| mock_proc.poll.assert_called_once_with() | |
| with self.subTest(case="running_process"): | |
| mock_os.killpg.reset_mock() | |
| mock_time.sleep.reset_mock() | |
| mock_proc = _make_mock_popen(poll_return=None) | |
| mock_proc.wait.side_effect = subprocess.TimeoutExpired( | |
| cmd="zxdb-daemon", timeout=3.0 | |
| ) | |
| mock_os.killpg.side_effect = ( | |
| None, | |
| PermissionError("Operation not permitted"), | |
| ) | |
| exited = _send_signal_and_wait( | |
| mock_proc, signal.SIGTERM, fallback, 3.0, pgid=456 | |
| ) | |
| self.assertFalse(exited) | |
| mock_time.sleep.assert_not_called() | |
| mock_proc.wait.assert_called_once_with(timeout=3.0) | |
| mock_proc.poll.assert_called_once_with() | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_cleanup_process_waits_for_child_pgid_and_escalates_on_timeout( | |
| self, mock_os: mock.Mock, mock_time: mock.Mock | |
| ) -> None: | |
| """Tests that _cleanup_process escalates to SIGKILL on captured PGID even if wrapper exits early.""" | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=None) | |
| mock_os.getpgid.return_value = 43210 | |
| mock_os.getpgrp.return_value = 11111 | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| mock_time.sleep.side_effect = clock.sleep | |
| sigkill_sent = False | |
| def wait_effect(**_kwargs: Any) -> int: | |
| if not sigkill_sent: | |
| clock.advance(2.0) | |
| else: | |
| clock.advance(0.1) | |
| return 0 | |
| mock_proc.wait.side_effect = wait_effect | |
| def killpg_effect(pgid: int, sig: int) -> None: | |
| nonlocal sigkill_sent | |
| if sig == signal.SIGKILL: | |
| sigkill_sent = True | |
| return | |
| if sig == 0 and sigkill_sent: | |
| raise ProcessLookupError() | |
| mock_os.killpg.side_effect = killpg_effect | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| self.assertSequenceEqual( | |
| mock_os.killpg.call_args_list, | |
| ( | |
| mock.call(43210, signal.SIGTERM), | |
| mock.call(43210, 0), | |
| mock.call(43210, signal.SIGKILL), | |
| mock.call(43210, 0), | |
| ), | |
| ) | |
| mock_proc.terminate.assert_not_called() | |
| mock_proc.kill.assert_not_called() | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_cleanup_process_resolves_pgid_before_poll_and_cleans_lingering_group( | |
| self, mock_os: mock.Mock, mock_time: mock.Mock | |
| ) -> None: | |
| """Tests that _cleanup_process captures pgid before poll() and cleans up lingering group members.""" | |
| mock_os.getpgrp.return_value = 11111 | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| mock_time.sleep.side_effect = clock.sleep | |
| with self.subTest(case="lingering_members_signaled_after_leader_exits"): | |
| events: list[str] = [] | |
| leader_reaped = False | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=0) | |
| def getpgid_effect(pid: int) -> int: | |
| events.append("getpgid") | |
| if leader_reaped: | |
| raise ProcessLookupError("leader already reaped") | |
| self.assertEqual(pid, 43210) | |
| return 43210 | |
| def poll_effect() -> int: | |
| nonlocal leader_reaped | |
| events.append("poll") | |
| leader_reaped = True | |
| return 0 | |
| sigterm_sent = False | |
| def killpg_effect(pgid: int, sig: int) -> None: | |
| nonlocal sigterm_sent | |
| self.assertEqual(pgid, 43210) | |
| if sig == 0 and not sigterm_sent: | |
| return | |
| if sig == signal.SIGTERM: | |
| sigterm_sent = True | |
| return | |
| if sig == 0 and sigterm_sent: | |
| raise ProcessLookupError() | |
| mock_os.getpgid.side_effect = getpgid_effect | |
| mock_proc.poll.side_effect = poll_effect | |
| mock_os.killpg.side_effect = killpg_effect | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| self.assertSequenceEqual(events, ("getpgid", "poll")) | |
| self.assertSequenceEqual( | |
| mock_os.killpg.call_args_list, | |
| ( | |
| mock.call(43210, 0), | |
| mock.call(43210, signal.SIGTERM), | |
| mock.call(43210, 0), | |
| ), | |
| ) | |
| mock_proc.terminate.assert_not_called() | |
| with self.subTest(case="no_lingering_members_skips_signal"): | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_os.getpgid.side_effect = None | |
| mock_os.getpgid.return_value = 43210 | |
| mock_os.killpg.side_effect = ProcessLookupError() | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=0) | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| mock_os.killpg.assert_called_once_with(43210, 0) | |
| mock_proc.terminate.assert_not_called() | |
| mock_proc.kill.assert_not_called() | |
| @mock.patch.object(manager_mod, "socket", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_stop_sync_captures_pgid_before_wait_and_cleans_lingering_group( | |
| self, | |
| mock_os: mock.Mock, | |
| mock_time: mock.Mock, | |
| mock_socket_mod: mock.Mock, | |
| ) -> None: | |
| """Tests that stop_sync captures pgid before wait() reaps the leader and cleans lingering group members.""" | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| mock_time.sleep.side_effect = clock.sleep | |
| mock_os.getpgrp.return_value = 11111 | |
| mock_socket = mock_socket_mod.socket.return_value.__enter__.return_value | |
| mock_socket.recv.return_value = b"" | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| with self.subTest( | |
| case="reaped_leader_with_lingering_group_members" | |
| ): | |
| sock_path.touch() | |
| events: list[str] = [] | |
| leader_reaped = False | |
| sigterm_sent = False | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=None) | |
| def getpgid_effect(pid: int) -> int: | |
| events.append("getpgid") | |
| if leader_reaped: | |
| raise ProcessLookupError("leader already reaped") | |
| self.assertEqual(pid, 43210) | |
| return 43210 | |
| def wait_effect(**_kwargs: Any) -> int: | |
| nonlocal leader_reaped | |
| events.append("wait") | |
| leader_reaped = True | |
| mock_proc.poll.return_value = 0 | |
| return 0 | |
| def killpg_effect(pgid: int, sig: int) -> None: | |
| nonlocal sigterm_sent | |
| self.assertEqual(pgid, 43210) | |
| if sig == 0 and not sigterm_sent: | |
| return | |
| if sig == signal.SIGTERM: | |
| events.append("sigterm") | |
| sigterm_sent = True | |
| return | |
| if sig == 0 and sigterm_sent: | |
| raise ProcessLookupError() | |
| mock_os.getpgid.side_effect = getpgid_effect | |
| mock_proc.wait.side_effect = wait_effect | |
| mock_os.killpg.side_effect = killpg_effect | |
| manager = DaemonManager(socket_path=sock_path) | |
| manager._proc = mock_proc | |
| manager.stop_sync(timeout=5.0) | |
| self.assertSequenceEqual( | |
| events, ("getpgid", "wait", "sigterm", "wait") | |
| ) | |
| mock_os.getpgid.assert_called_once_with(43210) | |
| self.assertSequenceEqual( | |
| mock_os.killpg.call_args_list, | |
| ( | |
| mock.call(43210, 0), | |
| mock.call(43210, signal.SIGTERM), | |
| mock.call(43210, 0), | |
| ), | |
| ) | |
| mock_proc.terminate.assert_not_called() | |
| self.assertFalse(sock_path.exists()) | |
| self.assertIsNone(manager._proc) | |
| with self.subTest( | |
| case="preresolved_none_does_not_requery_getpgid_after_wait" | |
| ): | |
| sock_path.touch() | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_os.getpgid.side_effect = None | |
| mock_os.getpgid.return_value = 11111 | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=None) | |
| def wait_reaps(**_kwargs: Any) -> int: | |
| mock_proc.poll.return_value = 0 | |
| return 0 | |
| mock_proc.wait.side_effect = wait_reaps | |
| manager = DaemonManager(socket_path=sock_path) | |
| manager._proc = mock_proc | |
| manager.stop_sync(timeout=5.0) | |
| mock_os.getpgid.assert_called_once_with(43210) | |
| mock_os.killpg.assert_not_called() | |
| mock_proc.terminate.assert_not_called() | |
| self.assertFalse(sock_path.exists()) | |
| self.assertIsNone(manager._proc) | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_cleanup_process_ignores_unsafe_pids_and_shared_pgid( | |
| self, mock_os: mock.Mock | |
| ) -> None: | |
| """Tests host-safety guards against unsafe PIDs and non-isolated PGIDs.""" | |
| mock_os.getpgrp.return_value = 11111 | |
| cases = ( | |
| ("none_pid", None, 43210, False), | |
| ("bool_true_pid", True, 43210, False), | |
| ("bool_false_pid", False, 43210, False), | |
| ("init_pid", 1, 43210, False), | |
| ("zero_pid", 0, 43210, False), | |
| ("negative_pid", -5, 43210, False), | |
| ("str_pid", "123", 43210, False), | |
| ("shared_pgid", 43210, 11111, True), | |
| ("non_leader_pgid", 43210, 43211, True), | |
| ("init_pgid", 43210, 1, True), | |
| ("zero_pgid", 43210, 0, True), | |
| ) | |
| for case_name, pid_value, pgid_value, expect_getpgid in cases: | |
| with self.subTest(case=case_name): | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_os.getpgid.return_value = pgid_value | |
| mock_proc = _make_mock_popen(poll_return=None, spec_set=False) | |
| mock_proc.pid = pid_value | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| if expect_getpgid: | |
| mock_os.getpgid.assert_called_once_with(pid_value) | |
| else: | |
| mock_os.getpgid.assert_not_called() | |
| mock_os.killpg.assert_not_called() | |
| mock_proc.terminate.assert_called_once_with() | |
| with self.subTest(case="already_reaped_returncode"): | |
| mock_os.getpgid.reset_mock() | |
| mock_os.killpg.reset_mock() | |
| mock_os.getpgid.return_value = 43210 | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=0, returncode=0) | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| mock_os.getpgid.assert_not_called() | |
| mock_os.killpg.assert_not_called() | |
| mock_proc.terminate.assert_not_called() | |
| @mock.patch.object(manager_mod, "os", autospec=True, spec_set=True) | |
| def test_cleanup_process_handles_permission_errors( | |
| self, mock_os: mock.Mock | |
| ) -> None: | |
| """Tests that PermissionError in getpgid or killpg falls back to proc termination.""" | |
| mock_os.getpgrp.return_value = 11111 | |
| with self.subTest(case="getpgid_permission_error"): | |
| mock_os.getpgid.side_effect = PermissionError("denied") | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=None) | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| mock_os.killpg.assert_not_called() | |
| mock_proc.terminate.assert_called_once_with() | |
| mock_proc.wait.assert_called_once_with(timeout=1.0) | |
| with self.subTest(case="killpg_permission_error_falls_back_to_proc"): | |
| mock_os.getpgid.reset_mock() | |
| mock_os.getpgid.side_effect = None | |
| mock_os.getpgid.return_value = 43210 | |
| mock_os.killpg.side_effect = PermissionError("denied") | |
| mock_proc = _make_mock_popen(pid=43210, poll_return=None) | |
| _cleanup_process(mock_proc, sigterm_timeout=1.0) | |
| mock_os.killpg.assert_called_once_with(43210, signal.SIGTERM) | |
| mock_proc.terminate.assert_called_once_with() | |
| mock_proc.wait.assert_called_once_with(timeout=1.0) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(DaemonManager, "_send_start_request", autospec=True) | |
| @mock.patch.object(DaemonManager, "do_handshake_and_connect", autospec=True) | |
| @mock.patch.object(DaemonManager, "_wait_for_ready_signal", autospec=True) | |
| async def test_start_enforces_shared_monotonic_deadline( | |
| self, | |
| mock_wait_ready: mock.Mock, | |
| mock_handshake: mock.Mock, | |
| mock_send_start: mock.Mock, | |
| mock_time: mock.Mock, | |
| ) -> None: | |
| """Tests that start() shares one monotonic deadline across ready, handshake, and start request.""" | |
| mock_proc = _make_mock_popen(poll_return=0) | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| def spawn_with_delay(_wfd: int) -> subprocess.Popen[bytes]: | |
| clock.advance(1.0) | |
| return mock_proc | |
| async def wait_ready_with_delay(*_args: Any, **_kwargs: Any) -> None: | |
| clock.advance(4.0) | |
| async def handshake_with_delay(*_args: Any, **_kwargs: Any) -> bool: | |
| clock.advance(2.0) | |
| return True | |
| mock_wait_ready.side_effect = wait_ready_with_delay | |
| mock_handshake.side_effect = handshake_with_delay | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=20.0, | |
| spawn_fn=spawn_with_delay, | |
| ) | |
| proc = await manager.start() | |
| self.assertIs(proc, mock_proc) | |
| self.assertEqual(mock_wait_ready.call_args.kwargs["timeout"], 19.0) | |
| self.assertEqual( | |
| mock_handshake.call_args.kwargs["timeout"], | |
| manager_mod._HANDSHAKE_TIMEOUT_SECS, | |
| ) | |
| self.assertEqual(mock_send_start.call_args.kwargs["timeout"], 13.0) | |
| @mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object(DaemonManager, "do_handshake_and_connect", autospec=True) | |
| @mock.patch.object(DaemonManager, "_wait_for_ready_signal", autospec=True) | |
| async def test_start_raises_timeout_and_cleans_up_when_budget_expires( | |
| self, | |
| mock_wait_ready: mock.Mock, | |
| mock_handshake: mock.Mock, | |
| mock_time: mock.Mock, | |
| mock_cleanup: mock.Mock, | |
| ) -> None: | |
| """Tests that start() raises DaemonStartupTimeoutError when monotonic budget runs out.""" | |
| mock_proc = _make_mock_popen() | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| def spawn_with_delay(_wfd: int) -> subprocess.Popen[bytes]: | |
| clock.advance(1.0) | |
| return mock_proc | |
| async def wait_ready_expiring_budget( | |
| *_args: Any, **_kwargs: Any | |
| ) -> None: | |
| clock.advance(10.0) | |
| mock_wait_ready.side_effect = wait_ready_expiring_budget | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=10.0, | |
| spawn_fn=spawn_with_delay, | |
| ) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager.start() | |
| mock_handshake.assert_not_called() | |
| mock_cleanup.assert_called_once_with(mock_proc) | |
| @mock.patch.object(manager_mod, "FxCmd", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "subprocess", autospec=True, spec_set=True) | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| async def test_start_raises_timeout_without_spawning_when_budget_exhausted( | |
| self, | |
| mock_time: mock.Mock, | |
| mock_subprocess: mock.Mock, | |
| mock_fx_cmd: mock.Mock, | |
| ) -> None: | |
| """Tests that start() does not spawn Popen when startup_timeout <= 0.0 or budget is exhausted.""" | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| for case_name, startup_timeout in ( | |
| ("zero_timeout", 0.0), | |
| ("negative_timeout", -1.0), | |
| ): | |
| with self.subTest(case=case_name): | |
| mock_subprocess.Popen.reset_mock() | |
| mock_fx_cmd.reset_mock() | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=startup_timeout, | |
| ) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager.start() | |
| mock_subprocess.Popen.assert_not_called() | |
| mock_fx_cmd.assert_not_called() | |
| with self.subTest(case="stale_socket_exhausts_budget"): | |
| mock_subprocess.Popen.reset_mock() | |
| mock_fx_cmd.reset_mock() | |
| sock_path.touch() | |
| async def stale_handshake( | |
| *_args: Any, **_kwargs: Any | |
| ) -> bool | None: | |
| clock.advance(2.0) | |
| return None | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=2.0, | |
| ) | |
| with mock.patch.object( | |
| manager, | |
| "do_handshake_and_connect", | |
| autospec=True, | |
| side_effect=stale_handshake, | |
| ): | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager.start() | |
| self.assertFalse(sock_path.exists()) | |
| mock_subprocess.Popen.assert_not_called() | |
| mock_fx_cmd.assert_not_called() | |
| @mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| @mock.patch.object( | |
| DaemonManager, "connect_to_running_daemon", autospec=True | |
| ) | |
| @mock.patch.object(DaemonManager, "do_handshake_and_connect", autospec=True) | |
| async def test_start_connect_to_existing_forwards_deadline_and_times_out( | |
| self, | |
| mock_handshake: mock.Mock, | |
| mock_connect_running: mock.Mock, | |
| mock_time: mock.Mock, | |
| ) -> None: | |
| """Tests connect_to_existing=True deadline forwarding and timeout handling in start().""" | |
| clock = _FakeClock(100.0) | |
| mock_time.monotonic.side_effect = clock.monotonic | |
| with tempfile.TemporaryDirectory() as temp_dir: | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| sock_path.touch() | |
| with self.subTest(case="forwards_remaining_budget"): | |
| mock_handshake.reset_mock() | |
| mock_connect_running.reset_mock() | |
| async def handshake_advancing( | |
| *_args: Any, **_kwargs: Any | |
| ) -> bool: | |
| clock.advance(3.0) | |
| return True | |
| mock_handshake.side_effect = handshake_advancing | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=20.0, | |
| connect_to_existing=True, | |
| ) | |
| proc = await manager.start() | |
| self.assertIsNone(proc) | |
| mock_handshake.assert_awaited_once_with( | |
| manager, timeout=manager_mod._HANDSHAKE_TIMEOUT_SECS | |
| ) | |
| mock_connect_running.assert_awaited_once_with( | |
| manager, timeout=17.0 | |
| ) | |
| self.assertTrue(sock_path.exists()) | |
| with self.subTest(case="exhausted_after_handshake"): | |
| mock_handshake.reset_mock() | |
| mock_connect_running.reset_mock() | |
| async def handshake_exhausting( | |
| *_args: Any, **_kwargs: Any | |
| ) -> bool: | |
| clock.advance(5.0) | |
| return True | |
| mock_handshake.side_effect = handshake_exhausting | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=5.0, | |
| connect_to_existing=True, | |
| ) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager.start() | |
| mock_handshake.assert_awaited_once_with(manager, timeout=5.0) | |
| mock_connect_running.assert_not_called() | |
| self.assertTrue(sock_path.exists()) | |
| with self.subTest(case="zero_timeout_before_handshake"): | |
| mock_handshake.reset_mock() | |
| mock_connect_running.reset_mock() | |
| manager = DaemonManager( | |
| socket_path=sock_path, | |
| startup_timeout=0.0, | |
| connect_to_existing=True, | |
| ) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await manager.start() | |
| mock_handshake.assert_not_called() | |
| mock_connect_running.assert_not_called() | |
| self.assertTrue(sock_path.exists()) | |
| async def test_do_handshake_and_connect_caps_timeout_for_is_running( | |
| self, | |
| ) -> None: | |
| """Tests that do_handshake_and_connect() and is_running() cap timeout at _HANDSHAKE_TIMEOUT_SECS.""" | |
| sock_path = await self._start_silent_unix_server() | |
| with self.subTest(case="caps_large_startup_timeout"): | |
| manager = DaemonManager( | |
| socket_path=sock_path, startup_timeout=320.0 | |
| ) | |
| with mock.patch.object( | |
| manager_mod, "_HANDSHAKE_TIMEOUT_SECS", 0.02 | |
| ): | |
| with self.assertRaisesRegex( | |
| DaemonHandshakeError, "Handshake timeout" | |
| ): | |
| await asyncio.wait_for( | |
| manager.do_handshake_and_connect(), timeout=1.0 | |
| ) | |
| self.assertFalse( | |
| await asyncio.wait_for(manager.is_running(), timeout=1.0) | |
| ) | |
| with self.subTest(case="honors_smaller_startup_timeout"): | |
| short_manager = DaemonManager( | |
| socket_path=sock_path, startup_timeout=0.02 | |
| ) | |
| with mock.patch.object(manager_mod, "_HANDSHAKE_TIMEOUT_SECS", 5.0): | |
| with self.assertRaisesRegex( | |
| DaemonHandshakeError, "Handshake timeout" | |
| ): | |
| await asyncio.wait_for( | |
| short_manager.do_handshake_and_connect(), timeout=1.0 | |
| ) | |
| @mock.patch.object(DaemonManager, "do_handshake_and_connect", autospec=True) | |
| async def test_is_running_returns_false_only_for_daemon_errors( | |
| self, mock_handshake: mock.Mock | |
| ) -> None: | |
| """Tests that is_running() returns False for connection/handshake errors and propagates others.""" | |
| manager = DaemonManager() | |
| for exc in ( | |
| DaemonConnectionError("connect failed"), | |
| DaemonHandshakeError("handshake failed"), | |
| ): | |
| with self.subTest(exc=type(exc).__name__): | |
| mock_handshake.reset_mock() | |
| mock_handshake.side_effect = exc | |
| self.assertFalse(await manager.is_running()) | |
| mock_handshake.reset_mock() | |
| mock_handshake.side_effect = RuntimeError("unexpected bug") | |
| with self.assertRaisesRegex(RuntimeError, "unexpected bug"): | |
| await manager.is_running() | |
| async def test_handshake_and_start_request_timeout_across_connect_and_drain( | |
| self, | |
| ) -> None: | |
| """Tests that connect and drain timeouts share the single timeout and handle writer cleanup.""" | |
| manager = DaemonManager(startup_timeout=0.01) | |
| async def hang_forever(*_args: Any, **_kwargs: Any) -> Any: | |
| await asyncio.Event().wait() | |
| cases = ( | |
| ( | |
| "handshake_connect_timeout_without_writer", | |
| lambda: manager.do_handshake_and_connect(timeout=0.01), | |
| False, | |
| DaemonHandshakeError, | |
| "Handshake timeout", | |
| ), | |
| ( | |
| "handshake_drain_timeout_closes_writer", | |
| lambda: manager.do_handshake_and_connect(timeout=0.01), | |
| True, | |
| DaemonHandshakeError, | |
| "Handshake timeout", | |
| ), | |
| ( | |
| "start_request_connect_timeout_without_writer", | |
| lambda: manager._send_start_request(timeout=0.01), | |
| False, | |
| DaemonConnectionError, | |
| "Timed out waiting for response from daemon.", | |
| ), | |
| ( | |
| "start_request_drain_timeout_closes_writer", | |
| lambda: manager._send_start_request(timeout=0.01), | |
| True, | |
| DaemonConnectionError, | |
| "Timed out waiting for response from daemon.", | |
| ), | |
| ) | |
| for ( | |
| case_name, | |
| call_fn, | |
| hang_in_drain, | |
| expected_exc, | |
| expected_msg, | |
| ) in cases: | |
| with self.subTest(case=case_name): | |
| mock_writer = None | |
| if hang_in_drain: | |
| mock_reader = mock.create_autospec( | |
| asyncio.StreamReader, instance=True, spec_set=True | |
| ) | |
| mock_writer = mock.create_autospec( | |
| asyncio.StreamWriter, instance=True, spec_set=True | |
| ) | |
| mock_writer.drain.side_effect = hang_forever | |
| mock_open_conn = mock.create_autospec( | |
| asyncio.open_unix_connection, | |
| spec_set=True, | |
| return_value=(mock_reader, mock_writer), | |
| ) | |
| else: | |
| mock_open_conn = mock.create_autospec( | |
| asyncio.open_unix_connection, | |
| spec_set=True, | |
| side_effect=hang_forever, | |
| ) | |
| with mock.patch.object( | |
| manager_mod, | |
| "asyncio", | |
| _make_asyncio_overlay(open_unix_connection=mock_open_conn), | |
| ): | |
| with self.assertRaisesRegex(expected_exc, expected_msg): | |
| await call_fn() | |
| if mock_writer is not None: | |
| mock_writer.close.assert_called_once_with() | |
| mock_writer.wait_closed.assert_awaited_once_with() | |
| async def _start_silent_unix_server( | |
| self, | |
| *, | |
| received_requests: list[bytes] | None = None, | |
| reply_line: bytes | None = None, | |
| ) -> Path: | |
| temp_dir = tempfile.mkdtemp(dir="/tmp") | |
| self.addCleanup(shutil.rmtree, temp_dir, True) | |
| sock_path = Path(temp_dir) / "daemon.sock" | |
| release_clients = asyncio.Event() | |
| self.addCleanup(release_clients.set) | |
| async def handle_client( | |
| reader: asyncio.StreamReader, writer: asyncio.StreamWriter | |
| ) -> None: | |
| try: | |
| if received_requests is not None or reply_line is not None: | |
| line = await reader.readline() | |
| if line and received_requests is not None: | |
| received_requests.append(line) | |
| if reply_line is not None: | |
| writer.write(reply_line) | |
| await writer.drain() | |
| else: | |
| await release_clients.wait() | |
| except Exception: | |
| pass | |
| finally: | |
| writer.close() | |
| server = await asyncio.start_unix_server(handle_client, path=sock_path) | |
| async def close_server() -> None: | |
| release_clients.set() | |
| server.close() | |
| await server.wait_closed() | |
| self.addAsyncCleanup(close_server) | |
| return sock_path | |
| async def test_explicit_timeouts_override_large_startup_timeout( | |
| self, | |
| ) -> None: | |
| """Tests explicit timeout overrides over real pipe/UDS boundaries and connect=True wire payload.""" | |
| with self.subTest(case="wait_for_ready_signal"): | |
| r, w = os.pipe() | |
| self.addCleanup(os.close, w) | |
| try: | |
| manager = DaemonManager() | |
| self.assertEqual(manager.startup_timeout, 320.0) | |
| with self.assertRaises(DaemonStartupTimeoutError): | |
| await asyncio.wait_for( | |
| manager._wait_for_ready_signal(r, timeout=0.01), | |
| timeout=1.0, | |
| ) | |
| finally: | |
| try: | |
| os.close(r) | |
| except OSError: | |
| pass | |
| sock_path = await self._start_silent_unix_server() | |
| manager = DaemonManager(socket_path=sock_path) | |
| with self.subTest(case="do_handshake_and_connect"): | |
| with self.assertRaises(DaemonHandshakeError): | |
| await asyncio.wait_for( | |
| manager.do_handshake_and_connect(timeout=0.01), | |
| timeout=1.0, | |
| ) | |
| with self.subTest(case="send_start_request"): | |
| with self.assertRaises(DaemonConnectionError): | |
| await asyncio.wait_for( | |
| manager._send_start_request(timeout=0.01), | |
| timeout=1.0, | |
| ) | |
| with self.subTest(case="connect_to_running_daemon_real_timeout"): | |
| with self.assertRaises(DaemonConnectionError): | |
| await asyncio.wait_for( | |
| manager.connect_to_running_daemon(timeout=0.01), | |
| timeout=1.0, | |
| ) | |
| with self.subTest(case="connect_to_running_daemon_wire_payload"): | |
| received_requests: list[bytes] = [] | |
| reply_sock_path = await self._start_silent_unix_server( | |
| received_requests=received_requests, | |
| reply_line=b'{"success": true}\n', | |
| ) | |
| connect_manager = DaemonManager(socket_path=reply_sock_path) | |
| await asyncio.wait_for( | |
| connect_manager.connect_to_running_daemon(timeout=5.0), | |
| timeout=5.0, | |
| ) | |
| self.assertEqual(len(received_requests), 1) | |
| payload = json.loads(received_requests[0].decode("utf-8")) | |
| self.assertEqual(payload["command"], "start") | |
| self.assertTrue(payload["connect"]) | |
| class TestDaemonManagerStopSync(unittest.TestCase): | |
| def setUp(self) -> None: | |
| super().setUp() | |
| self.clock = _FakeClock(100.0) | |
| self.mock_time = self.enterContext( | |
| mock.patch.object(manager_mod, "time", autospec=True, spec_set=True) | |
| ) | |
| self.mock_time.monotonic.side_effect = self.clock.monotonic | |
| self.mock_time.sleep.side_effect = self.clock.sleep | |
| self.mock_cleanup = self.enterContext( | |
| mock.patch.object( | |
| manager_mod, "_cleanup_process", autospec=True, spec_set=True | |
| ) | |
| ) | |
| self.mock_socket_mod = self.enterContext( | |
| mock.patch.object( | |
| manager_mod, "socket", autospec=True, spec_set=True | |
| ) | |
| ) | |
| self.mock_socket = ( | |
| self.mock_socket_mod.socket.return_value.__enter__.return_value | |
| ) | |
| temp_dir = self.enterContext(tempfile.TemporaryDirectory()) | |
| self.sock_path = Path(temp_dir) / "daemon.sock" | |
| self.sock_path.touch() | |
| self.manager = DaemonManager(socket_path=self.sock_path) | |
| def test_stop_sync_enforces_remaining_monotonic_deadline(self) -> None: | |
| """Tests that stop_sync shares one monotonic deadline across IPC, wait, and SIGTERM.""" | |
| self.mock_socket.connect.side_effect = _advance_clock(self.clock, 2.5) | |
| recv_chunks = iter((b'{"success": true}', b"")) | |
| def recv_with_delay(_size: int) -> bytes: | |
| chunk = next(recv_chunks) | |
| self.clock.advance(2.5 if chunk else 1.5) | |
| return chunk | |
| self.mock_socket.recv.side_effect = recv_with_delay | |
| mock_proc = _make_mock_popen() | |
| mock_proc.wait.side_effect = _advance_clock(self.clock, 2.0) | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=10.0) | |
| self.assertSequenceEqual( | |
| self.mock_socket.settimeout.call_args_list, | |
| (mock.call(10.0), mock.call(7.5), mock.call(5.0)), | |
| ) | |
| mock_proc.wait.assert_called_once_with(timeout=3.5) | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=1.5, pgid=None | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_aborts_uds_drain_and_uses_fallback_sigterm_grace_on_expiry( | |
| self, | |
| ) -> None: | |
| """Tests that stop_sync aborts UDS drain and guarantees bounded SIGTERM fallback grace on expiry.""" | |
| self.mock_socket.connect.side_effect = _advance_clock(self.clock, 2.0) | |
| def recv_expiring_budget(_size: int) -> bytes: | |
| self.clock.advance(3.0) | |
| return b"partial" | |
| self.mock_socket.recv.side_effect = recv_expiring_budget | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=5.0) | |
| self.assertSequenceEqual( | |
| self.mock_socket.settimeout.call_args_list, | |
| (mock.call(5.0), mock.call(3.0)), | |
| ) | |
| self.mock_socket.recv.assert_called_once_with(4096) | |
| mock_proc.wait.assert_not_called() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, | |
| sigterm_timeout=manager_mod._SIGTERM_FALLBACK_GRACE_SECS, | |
| pgid=None, | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_timeout_grants_bounded_fallback_sigterm_grace( | |
| self, | |
| ) -> None: | |
| """Tests that IPC timeout grants bounded SIGTERM fallback grace across timeouts.""" | |
| for timeout, expected_sigterm in ((5.0, 3.0), (1.0, 1.0)): | |
| with self.subTest(timeout=timeout): | |
| self.sock_path.touch() | |
| self.mock_cleanup.reset_mock() | |
| def recv_timeout( | |
| _size: int, advance_secs: float = timeout | |
| ) -> bytes: | |
| self.clock.advance(advance_secs) | |
| raise TimeoutError("Timed out") | |
| self.mock_socket.recv.side_effect = recv_timeout | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=timeout) | |
| mock_proc.wait.assert_not_called() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=expected_sigterm, pgid=None | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_post_ipc_wait_timeout_grants_fallback_sigterm_grace( | |
| self, | |
| ) -> None: | |
| """Tests that post-IPC wait() TimeoutExpired still receives bounded SIGTERM fallback grace.""" | |
| self.mock_socket.recv.return_value = b"" | |
| mock_proc = _make_mock_popen() | |
| def wait_timeout(**_kwargs: Any) -> int: | |
| self.clock.advance(5.0) | |
| raise subprocess.TimeoutExpired(cmd="zxdb-daemon", timeout=5.0) | |
| mock_proc.wait.side_effect = wait_timeout | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=5.0) | |
| mock_proc.wait.assert_called_once_with(timeout=5.0) | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=3.0, pgid=None | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_skips_uds_ipc_when_budget_exhausted_before_connect( | |
| self, | |
| ) -> None: | |
| """Tests that stop_sync skips UDS IPC instead of calling settimeout(0.0) when budget is 0.0.""" | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=0.0) | |
| self.mock_socket_mod.socket.assert_not_called() | |
| mock_proc.wait.assert_not_called() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=0.0, pgid=None | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_preserves_socket_when_budget_exhausted_without_proc( | |
| self, | |
| ) -> None: | |
| """Tests that stop_sync raises TimeoutError and preserves socket_path when _proc is None and budget is exhausted.""" | |
| with self.assertRaisesRegex( | |
| TimeoutError, "Timed out before daemon stop IPC" | |
| ): | |
| self.manager.stop_sync(timeout=0.0) | |
| self.mock_socket_mod.socket.assert_not_called() | |
| self.mock_cleanup.assert_not_called() | |
| self.assertTrue(self.sock_path.exists()) | |
| def test_stop_sync_logs_warning_when_unlink_raises_oserror(self) -> None: | |
| """Tests that stop_sync logs a warning instead of raising if socket_path.unlink raises OSError.""" | |
| self.mock_socket.recv.return_value = b"" | |
| with mock.patch.object( | |
| Path, | |
| "unlink", | |
| autospec=True, | |
| side_effect=PermissionError("unlink denied"), | |
| ), self.assertLogs(manager_mod._LOGGER, level="WARNING") as logs: | |
| self.manager.stop_sync(timeout=3.0) | |
| self.assertIn("Failed to unlink daemon socket", "\n".join(logs.output)) | |
| def test_stop_sync_unlinks_socket_after_cleanup_process(self) -> None: | |
| """Tests that stop_sync defers socket_path.unlink until after _cleanup_process completes.""" | |
| events: list[str] = [] | |
| self.mock_socket.connect.side_effect = TimeoutError("timed out") | |
| def record_cleanup( | |
| _proc: subprocess.Popen[bytes], | |
| sigterm_timeout: float, | |
| pgid: object = None, | |
| ) -> None: | |
| del pgid | |
| self.assertTrue(self.sock_path.exists()) | |
| events.append("cleanup") | |
| self.mock_cleanup.side_effect = record_cleanup | |
| orig_unlink = Path.unlink | |
| def record_unlink(self_path: Path, missing_ok: bool = False) -> None: | |
| if self_path == self.sock_path: | |
| events.append("unlink") | |
| orig_unlink(self_path, missing_ok=missing_ok) | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| with mock.patch.object( | |
| Path, "unlink", autospec=True, side_effect=record_unlink | |
| ): | |
| self.manager.stop_sync(timeout=4.0) | |
| self.assertFalse(self.sock_path.exists()) | |
| self.assertIsNone(self.manager._proc) | |
| self.assertSequenceEqual(events, ("cleanup", "unlink")) | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=4.0, pgid=None | |
| ) | |
| def test_stop_sync_success(self) -> None: | |
| """Tests that stop_sync() connects, sends StopRequest, reads response/EOF, and unlinks.""" | |
| cases = ( | |
| ("default_timeout", None, (b"",), 20.0), | |
| ("explicit_timeout", 3.0, (b'{"success": true}', b""), 3.0), | |
| ) | |
| for case_name, timeout, recv_chunks, expected_timeout in cases: | |
| with self.subTest(case=case_name): | |
| self.sock_path.touch() | |
| self.mock_socket_mod.socket.reset_mock() | |
| self.mock_socket.reset_mock() | |
| self.mock_socket.recv.side_effect = recv_chunks | |
| if timeout is None: | |
| self.manager.stop_sync() | |
| else: | |
| self.manager.stop_sync(timeout=timeout) | |
| self.mock_socket_mod.socket.assert_called_once() | |
| self.assertSequenceEqual( | |
| self.mock_socket.settimeout.call_args_list, | |
| (mock.call(expected_timeout),) * (1 + len(recv_chunks)), | |
| ) | |
| self.mock_socket.connect.assert_called_once_with( | |
| str(self.sock_path) | |
| ) | |
| self.mock_socket.sendall.assert_called_once() | |
| self.assertEqual( | |
| self.mock_socket.recv.call_count, len(recv_chunks) | |
| ) | |
| self.assertFalse(self.sock_path.exists()) | |
| def test_stop_sync_eof_budget_expiry_without_proc_raises_timeout( | |
| self, | |
| ) -> None: | |
| """Tests that stop_sync() raises TimeoutError if EOF drain exceeds deadline without _proc.""" | |
| self.mock_socket.connect.side_effect = _advance_clock(self.clock, 1.0) | |
| def recv_expiring_budget(_size: int) -> bytes: | |
| self.clock.advance(1.5) | |
| return b"partial" | |
| self.mock_socket.recv.side_effect = recv_expiring_budget | |
| with self.assertRaisesRegex( | |
| TimeoutError, "Timed out waiting for daemon stop EOF" | |
| ): | |
| self.manager.stop_sync(timeout=2.0) | |
| self.assertTrue(self.sock_path.exists()) | |
| def test_stop_sync_error_without_proc_returns_if_socket_disappeared( | |
| self, | |
| ) -> None: | |
| """Tests that stop_sync() returns cleanly on IPC errors if the daemon unlinked the socket.""" | |
| for exc in ( | |
| TimeoutError("Timed out"), | |
| ConnectionResetError("connection reset"), | |
| ): | |
| with self.subTest(exc=type(exc).__name__): | |
| self.sock_path.touch() | |
| def recv_and_unlink( | |
| _size: int, error: Exception = exc | |
| ) -> bytes: | |
| self.sock_path.unlink() | |
| raise error | |
| self.mock_socket.recv.side_effect = recv_and_unlink | |
| self.manager.stop_sync(timeout=2.0) | |
| self.assertFalse(self.sock_path.exists()) | |
| def test_stop_sync_ipc_errors_without_proc_raise_when_socket_remains( | |
| self, | |
| ) -> None: | |
| """Tests that IPC errors raise without unlinking when _proc is None and socket exists.""" | |
| cases = ( | |
| ( | |
| "connect_permission_error", | |
| "connect", | |
| PermissionError("permission denied"), | |
| ), | |
| ( | |
| "recv_connection_reset", | |
| "recv", | |
| ConnectionResetError("connection reset"), | |
| ), | |
| ( | |
| "sendall_broken_pipe", | |
| "sendall", | |
| BrokenPipeError("broken pipe"), | |
| ), | |
| ( | |
| "recv_timeout", | |
| "recv", | |
| TimeoutError("Timed out"), | |
| ), | |
| ) | |
| for case_name, method_name, exc in cases: | |
| with self.subTest(case=case_name): | |
| self.sock_path.touch() | |
| self.mock_socket_mod.socket.reset_mock() | |
| self.mock_socket.reset_mock() | |
| self.mock_socket.connect.side_effect = None | |
| self.mock_socket.sendall.side_effect = None | |
| self.mock_socket.recv.side_effect = None | |
| getattr(self.mock_socket, method_name).side_effect = exc | |
| with self.assertRaises(type(exc)): | |
| self.manager.stop_sync(timeout=2.0) | |
| if case_name == "recv_timeout": | |
| self.mock_socket_mod.socket.assert_called_once() | |
| self.assertSequenceEqual( | |
| self.mock_socket.settimeout.call_args_list, | |
| (mock.call(2.0), mock.call(2.0)), | |
| ) | |
| self.mock_socket.connect.assert_called_once_with( | |
| str(self.sock_path) | |
| ) | |
| self.mock_socket.sendall.assert_called_once() | |
| self.mock_socket.recv.assert_called_once() | |
| self.assertTrue(self.sock_path.exists()) | |
| def test_stop_sync_ipc_error_with_proc_cleans_up_and_unlinks(self) -> None: | |
| """Tests that IPC errors fall back to _cleanup_process without waiting and unlink when _proc is present.""" | |
| cases = ( | |
| ("permission_error", PermissionError("denied"), True), | |
| ("connection_refused", ConnectionRefusedError("refused"), False), | |
| ) | |
| for case_name, exc, expect_debug_log in cases: | |
| with self.subTest(case=case_name): | |
| self.sock_path.touch() | |
| self.mock_cleanup.reset_mock() | |
| self.mock_socket.connect.side_effect = exc | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| if expect_debug_log: | |
| with self.assertLogs( | |
| manager_mod._LOGGER, level="DEBUG" | |
| ) as logs: | |
| self.manager.stop_sync(timeout=4.0) | |
| self.assertIn(str(exc), "\n".join(logs.output)) | |
| else: | |
| with self.assertNoLogs(manager_mod._LOGGER, level="DEBUG"): | |
| self.manager.stop_sync(timeout=4.0) | |
| mock_proc.wait.assert_not_called() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=4.0, pgid=None | |
| ) | |
| self.assertIsNone(self.manager._proc) | |
| self.assertFalse(self.sock_path.exists()) | |
| def test_stop_sync_delegates_cleanup_when_proc_present(self) -> None: | |
| """Tests that stop_sync delegates cleanup to _cleanup_process when _proc is present.""" | |
| self.sock_path.unlink() | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, sigterm_timeout=20.0, pgid=None | |
| ) | |
| self.assertIsNone(self.manager._proc) | |
| def test_stop_sync_caps_sigterm_timeout_at_grace_period(self) -> None: | |
| """Tests that stop_sync caps _cleanup_process sigterm_timeout at _SIGTERM_GRACE_PERIOD_SECS.""" | |
| self.sock_path.unlink() | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| self.manager.stop_sync(timeout=30.0) | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, | |
| sigterm_timeout=manager_mod._SIGTERM_GRACE_PERIOD_SECS, | |
| pgid=None, | |
| ) | |
| @mock.patch.object( | |
| manager_mod, | |
| "_wait_and_cleanup_proc", | |
| autospec=True, | |
| spec_set=True, | |
| wraps=manager_mod._wait_and_cleanup_proc, | |
| ) | |
| def test_stop_sync_reaps_proc_when_ipc_raises_keyboard_interrupt( | |
| self, mock_wait_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that KeyboardInterrupt during stop IPC still reaps _proc via _wait_and_cleanup_proc.""" | |
| self.mock_socket.recv.side_effect = KeyboardInterrupt | |
| mock_proc = _make_mock_popen() | |
| self.manager._proc = mock_proc | |
| with self.assertRaises(KeyboardInterrupt): | |
| self.manager.stop_sync(timeout=5.0) | |
| mock_wait_cleanup.assert_called_once_with( | |
| mock_proc, | |
| timeout=5.0, | |
| deadline=105.0, | |
| graceful_ipc_succeeded=False, | |
| ipc_error=None, | |
| pgid=None, | |
| ) | |
| mock_proc.wait.assert_not_called() | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, | |
| sigterm_timeout=5.0, | |
| pgid=None, | |
| ) | |
| self.assertIsNone(self.manager._proc) | |
| @mock.patch.object( | |
| manager_mod, | |
| "_wait_and_cleanup_proc", | |
| autospec=True, | |
| spec_set=True, | |
| wraps=manager_mod._wait_and_cleanup_proc, | |
| ) | |
| def test_stop_sync_reaps_proc_when_post_ipc_wait_raises_keyboard_interrupt( | |
| self, mock_wait_cleanup: mock.Mock | |
| ) -> None: | |
| """Tests that KeyboardInterrupt during post-IPC wait still reaps _proc via _cleanup_process.""" | |
| self.mock_socket.recv.return_value = b"" | |
| mock_proc = _make_mock_popen() | |
| mock_proc.wait.side_effect = KeyboardInterrupt | |
| self.manager._proc = mock_proc | |
| with self.assertRaises(KeyboardInterrupt): | |
| self.manager.stop_sync(timeout=5.0) | |
| mock_wait_cleanup.assert_called_once_with( | |
| mock_proc, | |
| timeout=5.0, | |
| deadline=105.0, | |
| graceful_ipc_succeeded=True, | |
| ipc_error=None, | |
| pgid=None, | |
| ) | |
| mock_proc.wait.assert_called_once_with(timeout=5.0) | |
| self.mock_cleanup.assert_called_once_with( | |
| mock_proc, | |
| sigterm_timeout=5.0, | |
| pgid=None, | |
| ) | |
| self.assertIsNone(self.manager._proc) | |
| if __name__ == "__main__": | |
| unittest.main() |