Coverage for src/retrospeedlab/runner/turn.py: 100%
47 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-12-03 23:09 +0000
1import os
2import signal
3import subprocess
4import time
5from collections.abc import Callable
6from contextlib import suppress
7from pathlib import Path
8from typing import IO
10from loguru import logger
12STOP_SECONDS = 20.0
13POLL_SECONDS = 5.0
16def take_turn(
17 commands: dict[str, list[str]],
18 environment: dict[str, str],
19 seconds: float,
20 restarts: int,
21 crash_loop: Callable[[str, int], None],
22) -> None:
23 deadline = time.monotonic() + seconds
24 searches = {slug: launch(command, environment) for slug, command in commands.items()}
25 stops = dict.fromkeys(commands, 0)
26 try:
27 while (left := deadline - time.monotonic()) > 0:
28 for slug in [slug for slug, search in searches.items() if search.poll() is not None]:
29 stopped = searches.pop(slug)
30 stop(stopped)
31 stops[slug] += 1
32 if stops[slug] > restarts:
33 crash_loop(slug, stopped.returncode)
34 continue
35 logger.warning(f"The {slug} search stopped with exit code {stopped.returncode} and restarts alone")
36 searches[slug] = launch(commands[slug], environment)
37 time.sleep(min(POLL_SECONDS, left))
38 finally:
39 for search in searches.values():
40 stop(search)
43def launch(command: list[str], environment: dict[str, str]) -> subprocess.Popen[bytes]:
44 return subprocess.Popen(command, env=environment, start_new_session=True)
47def run_until(
48 command: list[str], environment: dict[str, str], cwd: Path, output: IO[bytes], seconds: float
49) -> int | None:
50 process = subprocess.Popen(
51 command, env=environment, cwd=cwd, stdout=output, stderr=subprocess.STDOUT, start_new_session=True
52 )
53 try:
54 return process.wait(seconds)
55 except subprocess.TimeoutExpired:
56 return None
57 finally:
58 stop(process)
61def stop(process: subprocess.Popen[bytes]) -> None:
62 signal_group(process.pid, signal.SIGTERM)
63 with suppress(subprocess.TimeoutExpired):
64 process.wait(STOP_SECONDS)
65 signal_group(process.pid, signal.SIGKILL)
66 process.wait()
69def signal_group(leader: int, number: signal.Signals) -> None:
70 with suppress(ProcessLookupError):
71 os.killpg(leader, number)