Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions tests/support/case_deadline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
"""Wall-clock bound for one test case, and cleanup of the worker processes it starts.

``case_deadline`` interrupts a blocked call (``os.read``, ``readline``, ``wait``) with a
``SIGALRM`` timer, so a hung case fails in seconds instead of holding the job until the CI
timeout. It needs ``SIGALRM``, ``setitimer`` and the main thread; elsewhere it is a no-op.
Every import is available on every platform; POSIX-only calls happen at run time only.
"""

import contextlib
import os
import signal
import subprocess
import threading
import time
from unittest import mock


class CaseTimeout(BaseException):
"""The deadline passed. Re-raised as ``AssertionError`` when ``case_deadline`` exits."""


class CaseReached(BaseException):
"""``until()`` became true. Propagates out of ``case_deadline`` unchanged."""


def deadline_supported():
return (
hasattr(signal, "SIGALRM")
and hasattr(signal, "setitimer")
and threading.current_thread() is threading.main_thread()
)


@contextlib.contextmanager
def case_deadline(limit, *, until=None, poll=0.25):
"""Raise ``CaseReached`` once ``until()`` is true, else ``CaseTimeout`` after ``limit`` s.

Raised at most once: the timer is cleared before the exception, so cleanup code that
runs in the interrupted frame's ``except``/``finally`` is not interrupted again.
"""
if not deadline_supported():
yield
return
started = time.monotonic()
done = False

def tick(signum, frame):
nonlocal done
if done:
return
remaining = limit - (time.monotonic() - started)
if until is not None and until():
done = True
raise CaseReached()
if remaining <= 0:
done = True
raise CaseTimeout(f"case exceeded {limit} s")
signal.setitimer(signal.ITIMER_REAL, max(0.001, min(poll, remaining)))

previous = signal.signal(signal.SIGALRM, tick)
signal.setitimer(signal.ITIMER_REAL, max(0.001, min(poll, limit)))
try:
yield
except CaseTimeout as exc:
raise AssertionError(str(exc)) from None
finally:
done = True
signal.setitimer(signal.ITIMER_REAL, 0)
signal.signal(signal.SIGALRM, previous if previous is not None else signal.SIG_DFL)


@contextlib.contextmanager
def owned_workers():
"""Record every ``subprocess.Popen`` started inside; SIGKILL the live ones' groups on exit.

Workers are expected to run with ``start_new_session=True`` (pid == process group id).
Yields the list of recorded ``Popen`` objects.
"""
workers = []
real = subprocess.Popen

class Recorded(real):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
workers.append(self)

try:
with mock.patch.object(subprocess, "Popen", Recorded):
yield workers
finally:
for proc in workers:
if proc.poll() is None:
with contextlib.suppress(ProcessLookupError):
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=5)
for stream in (proc.stdin, proc.stdout, proc.stderr):
if stream is not None:
with contextlib.suppress(OSError, ValueError):
stream.close()
135 changes: 126 additions & 9 deletions tests/unit/runtime/test_device_lease_startup_io.py
Original file line number Diff line number Diff line change
@@ -1,24 +1,59 @@
"""Linux launch adapter with synthetic files/processes and a fake smart socket."""

import contextlib
from dataclasses import replace
import hashlib
import io
import json
import os
from pathlib import Path
import select
import socket
import subprocess
import sys
import tempfile
import types
import unittest
from unittest.mock import Mock, patch

from tests.support.case_deadline import (
CaseReached,
case_deadline,
deadline_supported,
owned_workers,
)

sys.path.insert(0, str(Path(__file__).resolve().parent))
import test_device_lease_broker # noqa: F401 -- installs broker source path
from registry import DeviceRegistry
import startup
import compose


# Budgets from the CHE-9311 calibration (lease phases, 15x load).
B_HS = 6 # seconds: worker handshake select, widened from the product's 3
B_EXIT = 10 # seconds: Popen.wait after the except path, widened from the product's 5
C_MAIN = 30 # seconds: whole main case
C_FP01 = 6 # seconds: FP-01 case, ends early when the fake reports "drained"

LINUX_DEADLINE = unittest.skipUnless(
sys.platform.startswith("linux") and deadline_supported(),
"needs Linux process groups, SIGALRM and the main thread",
)

PARTIAL_JOURNAL_WORKER = """\
import fcntl, os, struct, sys, termios, time
os.write(1, b'{"worker": ')
# The parent has read the partial line once the pipe holds no unread bytes.
while struct.unpack("i", fcntl.ioctl(1, termios.FIONREAD, b"\\0\\0\\0\\0"))[0]:
time.sleep(0.01)
open(DRAINED, "w").write("drained")
sys.stdin.read()
"""
SILENT_WORKER = "#!/bin/sh\nexec 3>&1\nexec cat >/dev/null\n"
EOF_WORKER = "import os\nos.close(1)\n"


class StartupIOTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
Expand Down Expand Up @@ -64,6 +99,47 @@ def digest(path):
def adapter(self):
return startup.LinuxStartupIO(lambda: self.host)

@contextlib.contextmanager
def widened(self, *, handshake=True):
"""Give the product's fixed 3 s handshake and 5 s reap budgets room under load."""
real_select, real_wait = select.select, subprocess.Popen.wait

def wide_select(readers, writers, errors, timeout=None):
if handshake and timeout is not None:
timeout = max(timeout, B_HS)
return real_select(readers, writers, errors, timeout)

def wide_wait(proc, timeout=None):
return real_wait(proc, None if timeout is None else max(timeout, B_EXIT))

with (
patch("startup.select.select", wide_select),
patch.object(subprocess.Popen, "wait", wide_wait),
):
yield

def fake_worker(self, source, *, interpreter=None):
"""Make ``prepare`` spawn ``source`` as the worker; returns the path it writes on drain."""
drained = Path(self.temp.name) / "drained"
script = Path(self.temp.name) / "fake_worker"
script.write_text(source.replace("DRAINED", repr(str(drained))))
patches = [patch.object(startup, "__file__", str(script))]
if interpreter:
patches.append(
patch.object(startup, "sys", types.SimpleNamespace(executable=interpreter))
)
for item in patches:
item.start()
self.addCleanup(item.stop)
return drained

def assert_partial_read(self, outcome, drained, workers, marker):
self.assertIsInstance(outcome, CaseReached, outcome)
self.assertTrue(drained.exists(), "worker never saw the partial line consumed")
self.assertEqual(len(workers), 1)
self.assertEqual(workers[0].returncode, 0) # reaped by the except path
self.assertFalse(marker.exists())

def test_preflight_requires_shared_listener_pins_and_no_existing_resource_user(self):
adapter = self.adapter()
with (
Expand Down Expand Up @@ -311,16 +387,57 @@ def test_real_paused_worker_with_fake_executable_cannot_run_before_gate(self):
)
self.binary.chmod(0o700)
adapter = self.adapter()
journal = adapter.prepare(self.device)
self.assertFalse(marker.exists())
self.assertNotEqual(journal["worker"]["pid"], journal["child"]["pid"])
adapter.abort(journal)
self.assertFalse(marker.exists())
journal = adapter.prepare(self.device)
with owned_workers(), self.widened(), case_deadline(C_MAIN):
journal = adapter.prepare(self.device)
self.assertFalse(marker.exists())
self.assertNotEqual(journal["worker"]["pid"], journal["child"]["pid"])
adapter.abort(journal)
self.assertFalse(marker.exists())
journal = adapter.prepare(self.device)
self.assertFalse(marker.exists())
adapter.resume(journal)
adapter._running[journal["worker"]["pid"]].wait(timeout=B_EXIT)
self.assertEqual(marker.read_text(), "fake only")

@LINUX_DEADLINE
def test_silent_worker_times_out_the_handshake_and_is_reaped(self):
marker = Path(self.temp.name) / "executed"
self.fake_worker(SILENT_WORKER, interpreter="/bin/sh")
adapter = self.adapter()
with owned_workers() as workers, self.widened(handshake=False):
with case_deadline(3 + B_EXIT):
with self.assertRaisesRegex(ValueError, "paused worker handshake timeout"):
adapter.prepare(self.device)
self.assertEqual(len(workers), 1)
self.assertIsNotNone(workers[0].returncode)
self.assertFalse(marker.exists())
adapter.resume(journal)
adapter._running[journal["worker"]["pid"]].wait(timeout=5)
self.assertEqual(marker.read_text(), "fake only")

@LINUX_DEADLINE
def test_partial_journal_is_bounded_and_reaped(self):
# REQUIRED_TEST id=FP-01 severity=P1 class=failure-path
marker = Path(self.temp.name) / "executed"
drained = self.fake_worker(PARTIAL_JOURNAL_WORKER)
adapter = self.adapter()
with owned_workers() as workers, self.widened():
with case_deadline(C_FP01, until=drained.exists):
try:
adapter.prepare(self.device)
outcome = None
except BaseException as exc: # CaseReached must be seen as the outcome
outcome = exc
self.assert_partial_read(outcome, drained, workers, marker)

@LINUX_DEADLINE
def test_eof_before_a_journal_is_not_a_partial_read(self):
marker = Path(self.temp.name) / "executed"
drained = self.fake_worker(EOF_WORKER)
adapter = self.adapter()
with owned_workers() as workers, self.widened():
with case_deadline(B_EXIT):
with self.assertRaises(json.JSONDecodeError) as caught:
adapter.prepare(self.device)
with self.assertRaises(AssertionError):
self.assert_partial_read(caught.exception, drained, workers, marker)

def test_worker_allows_bounded_slow_journal_recheck_before_forwarding_gate(self):
with (
Expand Down
60 changes: 60 additions & 0 deletions tests/unit/test_case_deadline.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import os
import signal
import subprocess
import sys
import time
import types
import unittest
from unittest.mock import patch

from tests.support import case_deadline as module


class CaseDeadlineTests(unittest.TestCase):
@unittest.skipUnless(module.deadline_supported(), "needs SIGALRM and the main thread")
def test_deadline_interrupts_a_blocked_read_and_restores_the_handler(self):
before = signal.getsignal(signal.SIGALRM)
read_fd, write_fd = os.pipe()
self.addCleanup(os.close, read_fd)
self.addCleanup(os.close, write_fd)
started = time.monotonic()
with self.assertRaises(AssertionError):
with module.case_deadline(1):
os.read(read_fd, 1)
self.assertLess(time.monotonic() - started, 1.5)
self.assertIs(signal.getsignal(signal.SIGALRM), before)
self.assertEqual(signal.getitimer(signal.ITIMER_REAL), (0.0, 0.0))

def test_without_setitimer_nothing_is_armed(self):
# No SIGALRM machinery at all, as on Windows: the context must be a no-op.
without = types.SimpleNamespace(SIGALRM=signal.SIGALRM)
with patch.object(module, "signal", without):
self.assertFalse(module.deadline_supported())
with module.case_deadline(1):
pass

@unittest.skipUnless(module.deadline_supported(), "needs SIGALRM and the main thread")
def test_until_raises_case_reached_once_and_leaves_no_timer(self):
flag = {"hit": False}
with self.assertRaises(module.CaseReached):
with module.case_deadline(5, until=lambda: flag["hit"], poll=0.05):
time.sleep(0.1)
flag["hit"] = True
time.sleep(2)
self.assertEqual(signal.getitimer(signal.ITIMER_REAL), (0.0, 0.0))

@unittest.skipUnless(sys.platform.startswith("linux"), "process groups")
def test_owned_workers_kills_a_live_worker_group_and_reaps_it(self):
original = subprocess.Popen
with module.owned_workers() as workers:
subprocess.Popen(
[sys.executable, "-c", "import time; time.sleep(60)"], start_new_session=True
)
self.assertEqual(len(workers), 1)
self.assertIsNone(workers[0].poll())
self.assertIsNotNone(workers[0].returncode)
self.assertIs(subprocess.Popen, original)


if __name__ == "__main__":
unittest.main()
Loading