diff --git a/runpod/serverless/modules/rp_ping.py b/runpod/serverless/modules/rp_ping.py index 53741313..a9c5f1f2 100644 --- a/runpod/serverless/modules/rp_ping.py +++ b/runpod/serverless/modules/rp_ping.py @@ -3,6 +3,8 @@ The heartbeat is responsible for sending periodic pings to the Runpod server. """ +import multiprocessing +import multiprocessing.connection import os import time @@ -92,10 +94,27 @@ def ping_loop(self, test=False): """ while True: self._send_ping() - time.sleep(self.PING_INTERVAL) - if test: + worker_alive = self._wait_for_next_ping() + if test or not worker_alive: return + def _wait_for_next_ping(self) -> bool: + """ + Waits one ping interval. Returns False if the worker process is gone. + + The ping process is a daemon, which multiprocessing only terminates + from the worker's atexit hooks. A worker that is hard-killed (SIGKILL, + the OOM killer, an unhandled SIGTERM) never runs them, so the ping + process watches the worker's sentinel instead of sleeping and exits as + soon as the worker does. Run in-process (no parent), it just sleeps. + """ + worker = multiprocessing.parent_process() + if worker is None: + time.sleep(self.PING_INTERVAL) + return True + ready = multiprocessing.connection.wait([worker.sentinel], self.PING_INTERVAL) + return not ready + def _send_ping(self): """ Sends a heartbeat to the Runpod server. diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..65dc9b58 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,31 @@ +"""Suite-wide hooks: fail the run if it leaves processes behind.""" + +import os +import uuid + +import psutil +import pytest + +from tests.process_guard import SESSION_MARKER_ENV, reap_leaks + +LEAK_GRACE_SECONDS = 5 + +_session_marker = uuid.uuid4().hex + + +def pytest_sessionstart(session): + os.environ[SESSION_MARKER_ENV] = _session_marker + + +def pytest_sessionfinish(session, exitstatus): + leaks = reap_leaks(_session_marker, psutil.Process(), LEAK_GRACE_SECONDS) + if not leaks: + return + reporter = session.config.pluginmanager.get_plugin("terminalreporter") + if reporter is not None: + reporter.write_line( + "processes left running after the test session (killed):", red=True + ) + for leak in leaks: + reporter.write_line(f" {leak}", red=True) + session.exitstatus = pytest.ExitCode.TESTS_FAILED diff --git a/tests/process_guard.py b/tests/process_guard.py new file mode 100644 index 00000000..4beb76da --- /dev/null +++ b/tests/process_guard.py @@ -0,0 +1,62 @@ +"""Find processes a test session leaves running after it ends. + +Every process a test starts inherits SESSION_MARKER_ENV from the session. +Anything still carrying this session's marker at the end that is no longer a +descendant of the pytest process has been orphaned (its parent was killed or +exited without cleaning up), and would otherwise run on after the suite. +""" + +import time + +import psutil + +SESSION_MARKER_ENV = "RUNPOD_TEST_SESSION" +POLL_SECONDS = 0.1 +KILL_WAIT_SECONDS = 5 + + +def _carries_marker(proc: psutil.Process, marker: str) -> bool: + try: + return proc.environ().get(SESSION_MARKER_ENV) == marker + except (psutil.Error, OSError): + return False + + +def leaked_processes(marker: str, root: psutil.Process) -> list[psutil.Process]: + """Processes carrying `marker` that are neither `root` nor its descendants.""" + attached = {root.pid} | {child.pid for child in root.children(recursive=True)} + return [ + proc + for proc in psutil.process_iter() + if proc.pid not in attached and _carries_marker(proc, marker) + ] + + +def _describe(proc: psutil.Process) -> str: + try: + return f"pid {proc.pid}: {' '.join(proc.cmdline())}" + except psutil.Error: + return f"pid {proc.pid}" + + +def reap_leaks(marker: str, root: psutil.Process, grace_seconds: float) -> list[str]: + """Kill leaked processes still alive after `grace_seconds`; describe them. + + The grace period lets orphans that are already shutting down (a ping + process noticing its worker died) exit on their own. + """ + deadline = time.monotonic() + grace_seconds + leaked = leaked_processes(marker, root) + while leaked and time.monotonic() < deadline: + time.sleep(POLL_SECONDS) + leaked = [proc for proc in leaked if proc.is_running()] + + reported = [] + for proc in leaked: + reported.append(_describe(proc)) + try: + proc.kill() + except psutil.Error: + continue + psutil.wait_procs(leaked, timeout=KILL_WAIT_SECONDS) + return reported diff --git a/tests/test_process_guard.py b/tests/test_process_guard.py new file mode 100644 index 00000000..e0ba6f35 --- /dev/null +++ b/tests/test_process_guard.py @@ -0,0 +1,100 @@ +"""The session guard reports processes a test run leaves behind.""" + +import os +import subprocess +import sys +import textwrap + +import psutil +import pytest + +from tests.process_guard import SESSION_MARKER_ENV, leaked_processes, reap_leaks + +SLEEP_SECONDS = 30 +# Starts a sleeper and exits at once, so the sleeper is orphaned the way a +# worker's ping process is when a test kills the worker. +ORPHAN_LAUNCHER = textwrap.dedent( + """ + import subprocess + import sys + + # detached stdio: holding the launcher's pipe would make the caller wait + sleeper = subprocess.Popen( + [sys.executable, "-c", "import time, sys; time.sleep(float(sys.argv[1]))", sys.argv[1]], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + print(sleeper.pid) + """ +) + + +@pytest.fixture(name="spawned") +def fixture_spawned(): + """Tracks pids a test starts and kills any still alive afterwards.""" + pids = [] + yield pids + for pid in pids: + if psutil.pid_exists(pid): + psutil.Process(pid).kill() + + +def _start_orphan(marker, seconds=SLEEP_SECONDS): + env = {**os.environ, SESSION_MARKER_ENV: marker} + out = subprocess.run( + [sys.executable, "-c", ORPHAN_LAUNCHER, str(seconds)], + env=env, + capture_output=True, + text=True, + check=True, + ) + return int(out.stdout.strip()) + + +def test_reports_an_orphan_from_this_session(spawned): + pid = _start_orphan("session-a") + spawned.append(pid) + + leaked = leaked_processes("session-a", psutil.Process()) + + assert [proc.pid for proc in leaked] == [pid] + + +def test_ignores_other_sessions(spawned): + spawned.append(_start_orphan("session-b")) + + assert leaked_processes("session-a", psutil.Process()) == [] + + +def test_ignores_live_children_of_the_session(spawned): + env = {**os.environ, SESSION_MARKER_ENV: "session-a"} + child = subprocess.Popen( + [sys.executable, "-c", f"import time; time.sleep({SLEEP_SECONDS})"], env=env + ) + spawned.append(child.pid) + + assert leaked_processes("session-a", psutil.Process()) == [] + + child.kill() + child.wait() + + +def test_reap_kills_and_reports_survivors(spawned): + pid = _start_orphan("session-a") + spawned.append(pid) + + reported = reap_leaks("session-a", psutil.Process(), grace_seconds=0.5) + + assert len(reported) == 1 + assert str(pid) in reported[0] + assert ( + not psutil.pid_exists(pid) + or psutil.Process(pid).status() == psutil.STATUS_ZOMBIE + ) + + +def test_reap_allows_orphans_that_exit_within_grace(spawned): + spawned.append(_start_orphan("session-a", seconds=0.2)) + + assert reap_leaks("session-a", psutil.Process(), grace_seconds=3) == [] diff --git a/tests/test_serverless/test_modules/test_ping_start_method.py b/tests/test_serverless/test_modules/test_ping_start_method.py index 3c12d310..d71d18ea 100644 --- a/tests/test_serverless/test_modules/test_ping_start_method.py +++ b/tests/test_serverless/test_modules/test_ping_start_method.py @@ -21,6 +21,7 @@ import threading import time +import psutil import pytest linux_only = pytest.mark.skipif( @@ -50,6 +51,31 @@ ) +# A worker that keeps running after starting its heartbeat, with a ping +# interval far longer than the test, so the ping child is always mid-wait. +KILLED_WORKER_SCRIPT = textwrap.dedent( + """ + import multiprocessing + import os + import time + + from runpod.serverless.modules.rp_ping import Heartbeat + from runpod.serverless.modules.worker_state import PingJobMirror + + if __name__ == "__main__": + # keep a reference: a spawned child unpickles the mirror after start + mirror = PingJobMirror() + Heartbeat().start_ping(mirror) + (child,) = multiprocessing.active_children() + with open(os.environ["CHILD_PID_FILE"], "w", encoding="utf-8") as out: + out.write(str(child.pid)) + time.sleep(float(os.environ["HOLD_SECONDS"])) + """ +) +LONG_PING_INTERVAL_MS = "600000" +CHILD_EXIT_WAIT_SECONDS = 5 + + class _PingRecorder(http.server.BaseHTTPRequestHandler): pings = [] @@ -146,3 +172,53 @@ def test_ping_process_context_keeps_default_elsewhere(monkeypatch): monkeypatch.setattr(worker_state.sys, "platform", "darwin") expected = multiprocessing.get_context().get_start_method() assert worker_state.ping_process_context().get_start_method() == expected + + +def _wait_for_exit(pid, timeout): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if not psutil.pid_exists(pid): + return True + time.sleep(0.1) + return False + + +def test_heartbeat_exits_when_worker_is_killed(tmp_path, ping_server): + """A hard-killed worker skips atexit, so nothing terminates its daemon + ping child. The child must notice on its own, or it keeps reporting a + dead worker as alive.""" + worker = tmp_path / "worker.py" + worker.write_text(KILLED_WORKER_SCRIPT, encoding="utf-8") + child_pid_file = tmp_path / "child.pid" + port = ping_server.server_address[1] + + env = { + **os.environ, + "CHILD_PID_FILE": str(child_pid_file), + "HOLD_SECONDS": str(PING_WAIT_SECONDS * 4), + "RUNPOD_AI_API_KEY": "test-key", + "RUNPOD_POD_ID": "test-pod", + "RUNPOD_PING_INTERVAL": LONG_PING_INTERVAL_MS, + "RUNPOD_WEBHOOK_PING": f"http://127.0.0.1:{port}/ping/$RUNPOD_POD_ID", + } + proc = subprocess.Popen( + [sys.executable, str(worker)], + cwd=tmp_path, + env=env, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + child_pid = None + try: + assert _wait_for_ping(PING_WAIT_SECONDS), "heartbeat never pinged" + child_pid = int(child_pid_file.read_text(encoding="utf-8")) + proc.kill() + proc.wait(timeout=SHUTDOWN_WAIT_SECONDS) + + assert _wait_for_exit(child_pid, CHILD_EXIT_WAIT_SECONDS), ( + "ping process outlived the killed worker" + ) + finally: + proc.kill() + if child_pid is not None and psutil.pid_exists(child_pid): + psutil.Process(child_pid).kill()