refactor: one wait for an idle host in probes

This commit is contained in:
Abdessamad Derraz committed 2026-11-23 21:02:47 +01:00
1 parent 6451ea13b4
commit 6b1798cb97
4 files changed
+60 -41

No files matched your search

+15 -15
View File
@@ -42,9 +42,12 @@ from probes.host import (
Host,
Paths,
Settings,
StillBusy,
Unavailable,
child_env,
run_when_idle,
slug,
wait_for_load,
)
from probes.state import DONE, FAILED, PENDING, load_state, should_run
@@ -192,13 +195,11 @@ class Campaign:
if free < self.settings.min_free_gb:
raise Pause(f"disk: {free:.0f} GB free, the campaign stops under "
f"{self.settings.min_free_gb:.0f} GB")
waited = 0.0
while self.host.loadavg()[0] > self.host.max_load:
if waited >= self.settings.max_load_wait:
raise Pause(f"busy host: load stayed above {self.host.max_load:.1f} for "
f"{int(waited)} s")
self.host.sleep(self.host.poll)
waited += self.host.poll
try:
wait_for_load(self.host, self.settings.max_load_wait, self.host.poll)
except StillBusy as exc:
raise Pause(f"busy host: load stayed above {exc.threshold:.1f} for "
f"{int(exc.waited)} s") from None
# -- one core_probe invocation -------------------------------------------
@@ -210,12 +211,14 @@ class Campaign:
repeats = argv.count("--vary") or 1
reps = int(argv[argv.index("--repeat") + 1]) if "--repeat" in argv else 1
budget = self.settings.probe_timeout * repeats * reps + 120
attempt = busy = 0
attempt = 0
while attempt < CRASH_ATTEMPTS:
self.guard()
try:
proc = self.host.run(command, capture_output=True, text=True, check=False,
timeout=budget, cwd=self.paths.root, env=child_env())
# Refused on a busy host: run_when_idle runs it again until the wait runs out.
proc = run_when_idle(command, self.settings.max_load_wait, timeout=budget,
cwd=self.paths.root, env=child_env(), clock=self.host.clock,
pause=self.host.sleep, runner=self.host.run)
except subprocess.TimeoutExpired:
with log.open("a", encoding="utf-8") as handle:
handle.write(f"$ {' '.join(command)}\nkilled after {budget} s\n")
@@ -229,11 +232,8 @@ class Campaign:
except ValueError:
return ProbeResult(FAILED, reason="core_probe printed no record", log=str(log))
if proc.returncode == core_probe.EXIT_BUSY:
# Refused on a busy host: wait for it to settle and run it again.
busy += 1
if busy >= CRASH_ATTEMPTS:
raise Pause("busy host: core_probe refused to record three times")
continue
raise Pause(f"busy host: core_probe refused to record for "
f"{int(self.settings.max_load_wait)} s")
attempt += 1
if proc.returncode == 2:
return ProbeResult(FAILED, reason=f"core_probe refused the run: "
+23 -2
View File
@@ -93,7 +93,7 @@ BUSY_POLL = 15
def run_when_idle(argv: Sequence[str], max_wait: float, *, timeout: float | None = None,
env: dict[str, str] | None = None,
env: dict[str, str] | None = None, cwd: Path = REPO_ROOT,
clock: Callable[[], float] = time.monotonic,
pause: Callable[[float], None] = time.sleep,
runner: Callable[..., subprocess.CompletedProcess] = run_group,
@@ -103,7 +103,7 @@ def run_when_idle(argv: Sequence[str], max_wait: float, *, timeout: float | None
core_probe's own, and a timeout kills the run's whole process group."""
started = clock()
while True:
proc = runner(list(argv), cwd=REPO_ROOT, capture_output=True, text=True, timeout=timeout,
proc = runner(list(argv), cwd=cwd, capture_output=True, text=True, timeout=timeout,
**({"env": env} if env is not None else {}))
if proc.returncode != core_probe.EXIT_BUSY or clock() - started >= max_wait:
return proc
@@ -128,6 +128,27 @@ class Host:
return core_probe.default_max_load(self.cpu_count)
class StillBusy(RuntimeError):
"""The load stayed above core_probe's threshold for a whole wait."""
def __init__(self, load: float, threshold: float, waited: float) -> None:
super().__init__(f"load {load:.2f} above {threshold} for {int(waited)} s")
self.load = load
self.threshold = threshold
self.waited = waited
def wait_for_load(host: Host, limit: float, poll: float) -> None:
"""Wait while the host's load is above the threshold core_probe records
under, reading it every poll seconds, StillBusy after limit seconds."""
waited = 0.0
while (load := host.loadavg()[0]) > host.max_load:
if waited >= limit:
raise StillBusy(load, host.max_load, waited)
host.sleep(poll)
waited += poll
def parse_budget(text: str) -> float:
"""Seconds of a --budget value: a number with s, m or h."""
match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([smh]?)\s*", text or "")
+12 -13
View File
@@ -8,12 +8,11 @@ import os
import shutil
import subprocess
import sys
import time
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from pathlib import Path
from core_probe import (EXIT_BUSY, PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, default_max_load, head_commit,
from core_probe import (EXIT_BUSY, PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, head_commit,
host_probe_lock, probe_lock_path)
from core.paths import REPO_ROOT
from core.statefile import now_iso
@@ -25,7 +24,8 @@ from model.targets import load_target_config
from probes.content import Content, content_root, fetch_content, find_romfetch, load_content, load_file, ready_folder
from probes.cores import buildbot_listing, cached_nightly
from probes.entries import entry_dest
from probes.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, main_cache, run_group, run_when_idle
from probes.host import (CONTENT_FILE, PROBE_TIMEOUT, Host, StillBusy, Unavailable, main_cache, run_group,
run_when_idle, wait_for_load)
from probes.packlayout import (
Layout,
ProbeFailure,
@@ -45,6 +45,7 @@ PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml"
MAX_ROUNDS = 6
IDLE_WAIT = 1800
IDLE_POLL = 30.0
# The hardware target each platform is probed for: the one whose libretro
# cores are the buildbot's x86_64 Linux builds, or the platform's only one.
@@ -257,17 +258,13 @@ def content_folder(content: Content, fetch: bool) -> Path:
# One probe: a core, a game, a layout
# --------------------------------------------------------------------------
def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None:
def wait_idle(host: Host, limit: float = IDLE_WAIT, poll: float = IDLE_POLL) -> None:
"""Wait for the load core_probe records under (core_probe.default_max_load).
Extracting a pack loads the host itself for a minute or two."""
threshold = default_max_load()
waited = 0.0
while os.getloadavg()[0] > threshold:
if waited >= limit:
raise ProbeFailure(f"busy host: load {os.getloadavg()[0]:.2f} above {threshold} "
f"for {int(waited)} s")
time.sleep(poll)
waited += poll
try:
wait_for_load(host, limit, poll)
except StillBusy as exc:
raise ProbeFailure(f"busy host: {exc}") from None
def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) -> tuple[int, dict | None, str]:
@@ -278,11 +275,13 @@ def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) ->
argfile.write_text("".join(f"--system-file\n{rel}={layout.root / rel}\n" for rel in sorted(staged)),
encoding="utf-8")
command = [sys.executable, str(REPO_ROOT / "scripts" / "core_probe.py"), *argv, f"@{argfile}"]
host = Host()
with host_probe_lock():
if "--record" in argv:
wait_idle()
wait_idle(host)
# core_probe takes the same lock unless told its caller holds it.
proc = run_when_idle(command, IDLE_WAIT, timeout=PROBE_TIMEOUT * 2 + 120, runner=run_group,
clock=host.clock, pause=host.sleep,
env={**os.environ, PROBE_LOCK_HELD_ENV: "1",
PROBE_LOCK_ENV: str(probe_lock_path())})
record = None
+10 -11
View File
@@ -358,22 +358,21 @@ class Lock(unittest.TestCase):
class LoadThreshold(unittest.TestCase):
"""pack_probe waits for the load core_probe records under, and the campaign
passes the same value: all three read core_probe.default_max_load."""
passes the same value: both read Host.max_load, core_probe.default_max_load."""
def test_wait_and_campaign_follow_core_probe(self) -> None:
from unittest import mock
import core_probe
from probes import host
with mock.patch.object(os, "cpu_count", return_value=12):
threshold = core_probe.default_max_load()
self.assertEqual(host.Host(cpu_count=12).max_load, threshold)
with mock.patch.object(os, "getloadavg", return_value=(threshold, 0.0, 0.0)):
packprobe.wait_idle(limit=0, poll=0)
with mock.patch.object(os, "getloadavg", return_value=(threshold + 0.5, 0.0, 0.0)), \
self.assertRaisesRegex(packprobe.ProbeFailure, f"above {threshold} "):
packprobe.wait_idle(limit=0, poll=0)
threshold = core_probe.default_max_load(12)
def at(load: float) -> host.Host:
return host.Host(cpu_count=12, loadavg=lambda: (load, 0.0, 0.0), sleep=lambda _: None)
self.assertEqual(at(0.0).max_load, threshold)
packprobe.wait_idle(at(threshold), limit=0, poll=0)
with self.assertRaisesRegex(packprobe.ProbeFailure, f"busy host: load .* above {threshold} "):
packprobe.wait_idle(at(threshold + 0.5), limit=0, poll=0)
class RecordsNameNoLocalPath(unittest.TestCase):