fix: start core_probe one way from every probe

pack_probe and region_check run core_probe through probes.host.run_when_idle:
a busy refusal is retried until the wait runs out, a timeout kills the
run's whole process group, and pack_probe takes core_probe's own probe
lock, which honours RETROBIOS_PROBE_LOCK_HELD. core_probe names its busy
exit status EXIT_BUSY.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:04:23 +01:00
1 parent 922d60807f
commit d2984bc466
7 files changed
+49 -60

No files matched your search

+3 -1
View File
@@ -90,6 +90,8 @@ PRINTF_SPEC = re.compile(r"%(?P<flags>[-+ #0]*)(?P<width>\*|\d+)?(?:\.(?P<prec>\
PROBE_LOCK_ENV = "RETROBIOS_PROBE_LOCK"
PROBE_LOCK_HELD_ENV = "RETROBIOS_PROBE_LOCK_HELD"
DEFAULT_PROBE_LOCK = Path.home() / ".local" / "state" / "retrobios" / "probe.lock"
# The exit status of a run refused on a busy host: nothing was recorded.
EXIT_BUSY = 3
def probe_lock_path() -> Path:
@@ -1585,7 +1587,7 @@ def _probe(args: argparse.Namespace) -> int:
if args.record and load_before and load_before[0] > max_load:
print(f"ERROR: load average {load_before[0]} exceeds {max_load}: the machine is busy, "
f"nothing recorded (raise --max-load to override)", file=sys.stderr)
return 3
return EXIT_BUSY
repetitions = args.repeat
base = {dest: Path(src) for dest, src in args.system_file}
args.oracle_data, oracle_identity = load_oracle(Path(args.oracle) if args.oracle else DEFAULT_ORACLE)
+1 -1
View File
@@ -237,7 +237,7 @@ class Campaign:
return ProbeResult(DONE, record=json.loads(proc.stdout), log=str(log))
except ValueError:
return ProbeResult(FAILED, reason="core_probe printed no record", log=str(log))
if proc.returncode == 3:
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:
+21
View File
@@ -88,6 +88,27 @@ def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool
return result
BUSY_POLL = 15
def run_when_idle(argv: Sequence[str], max_wait: float, *, timeout: float | None = None,
env: dict[str, str] | None = None,
clock: Callable[[], float] = time.monotonic,
pause: Callable[[float], None] = time.sleep,
runner: Callable[..., subprocess.CompletedProcess] = run_group,
) -> subprocess.CompletedProcess:
"""core_probe, run again while it refuses a busy host: every BUSY_POLL
seconds until max_wait seconds have passed. The load threshold stays
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,
**({"env": env} if env is not None else {}))
if proc.returncode != core_probe.EXIT_BUSY or clock() - started >= max_wait:
return proc
pause(BUSY_POLL)
@dataclass
class Host:
"""What the campaign reads from the machine and the network, replaced in tests."""
+8 -25
View File
@@ -3,20 +3,19 @@
from __future__ import annotations
import argparse
import contextlib
import fcntl
import json
import os
import shutil
import subprocess
import sys
import time
from collections.abc import Iterable, Iterator, Sequence
from collections.abc import Iterable, Sequence
from dataclasses import dataclass
from pathlib import Path
from unattended import worktree
from core_probe import PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, probe_lock_path
from core_probe import (EXIT_BUSY, PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, host_probe_lock,
probe_lock_path)
from core.paths import REPO_ROOT
from core.statefile import now_iso
from model import measurements as mr
@@ -27,7 +26,7 @@ from model.targets import load_target_config
from probes.content import Content, load_content, load_file, verify_identity
from probes.cores import buildbot_listing, cached_nightly
from probes.entries import entry_dest
from probes.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, child_env
from probes.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, child_env, run_group, run_when_idle
from probes.packlayout import (
Layout,
ProbeFailure,
@@ -50,8 +49,6 @@ CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores"
MAX_ROUNDS = 6
IDLE_WAIT = 1800
PROBE_LOCK = probe_lock_path()
EXIT_BUSY = 3
# 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.
@@ -278,20 +275,6 @@ def wait_idle(limit: float = IDLE_WAIT, poll: float = 30.0) -> None:
waited += poll
@contextlib.contextmanager
def probe_lock(path: Path | None = None) -> Iterator[None]:
"""The host's probe lock, for one run: one probe at a time on the host,
released between runs so a pass never holds it for its whole length."""
path = path or PROBE_LOCK
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("a") as handle:
fcntl.flock(handle, fcntl.LOCK_EX)
try:
yield
finally:
fcntl.flock(handle, fcntl.LOCK_UN)
def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) -> tuple[int, dict | None, str]:
"""core_probe.py run under the probe lock, the system files passed in an
argument file."""
@@ -300,13 +283,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}"]
with probe_lock():
with host_probe_lock():
if "--record" in argv:
wait_idle()
# core_probe takes the same lock unless told its caller holds it.
proc = subprocess.run(command, capture_output=True, text=True, check=False, cwd=REPO_ROOT,
timeout=PROBE_TIMEOUT * 2 + 120,
env={**os.environ, PROBE_LOCK_HELD_ENV: "1", PROBE_LOCK_ENV: str(PROBE_LOCK)})
proc = run_when_idle(command, IDLE_WAIT, timeout=PROBE_TIMEOUT * 2 + 120, runner=run_group,
env={**os.environ, PROBE_LOCK_HELD_ENV: "1",
PROBE_LOCK_ENV: str(probe_lock_path())})
record = None
if proc.returncode == 0:
try:
+2 -23
View File
@@ -8,7 +8,6 @@ import re
import subprocess
import sys
import tempfile
import time
from collections.abc import Callable, Iterable
from pathlib import Path
@@ -18,7 +17,7 @@ from core_probe import BUILTIN
from probes.content import Content, load_content, load_file
from probes.cores import cached_nightly
from probes.entries import entry_dest, held_file, regions_of
from probes.host import CONTENT_FILE
from probes.host import CONTENT_FILE, run_when_idle
from resolve.validation import read_by_build
@@ -216,26 +215,6 @@ def local_resolver() -> Callable[[dict], Path | None]:
return lambda entry: held_file(entry, db, REPO_ROOT)
BUSY = 3 # core_probe's exit status when it refuses to record on a busy host
POLL_S = 15
def probe_when_idle(argv: list[str], max_wait: float,
clock: Callable[[], float] = time.monotonic,
pause: Callable[[float], None] = time.sleep,
runner: Callable[..., subprocess.CompletedProcess] = subprocess.run
) -> subprocess.CompletedProcess:
"""core_probe, run again while it refuses a busy host, as the campaign
does: every POLL_S seconds until max_wait seconds have passed. The load
threshold stays core_probe's own."""
started = clock()
while True:
proc = runner(argv, cwd=REPO_ROOT, capture_output=True, text=True)
if proc.returncode != BUSY or clock() - started >= max_wait:
return proc
pause(POLL_S)
def run(args: argparse.Namespace) -> int:
from model.profiles import load_emulator_profiles
@@ -268,7 +247,7 @@ def run(args: argparse.Namespace) -> int:
argv += ["--core-artifact", url]
for dest, src in sorted(variants[label].items()):
argv += ["--system-file", f"{dest}={src}"]
proc = probe_when_idle(argv, args.max_load_wait)
proc = run_when_idle(argv, args.max_load_wait, timeout=args.timeout * 2 + 120)
status = "recorded" if proc.returncode == 0 else f"exit {proc.returncode}"
print(json.dumps({"game": game.name, "variant": label, "status": status,
"error": proc.stderr.strip()[-400:] if proc.returncode else None}),
+7 -4
View File
@@ -16,6 +16,7 @@ import tests
import contextlib
import io
import json
import os
import re
import shutil
import unittest
@@ -283,8 +284,9 @@ class Lock(unittest.TestCase):
return subprocess.CompletedProcess(command, 2, "", "refused")
lay = layout({"a.bin": 1})
with unittest.mock.patch.object(packprobe, "PROBE_LOCK", lock), \
unittest.mock.patch.object(packprobe.subprocess, "run", fake_run):
env = {"RETROBIOS_PROBE_LOCK": str(lock), "RETROBIOS_PROBE_LOCK_HELD": ""}
with unittest.mock.patch.dict(os.environ, env), \
unittest.mock.patch.object(packprobe, "run_group", fake_run):
for _ in range(2):
self.assertEqual(packprobe.core_probe(["run"], {"a.bin"}, lay, work), (2, None, "refused"))
self.assertEqual(held, [True, True])
@@ -314,8 +316,9 @@ class RecordsNameNoLocalPath(unittest.TestCase):
def fake_run(command, **kwargs):
return subprocess.CompletedProcess(command, 1, "", f' File "{script}", line 9\n')
with unittest.mock.patch.object(packprobe, "PROBE_LOCK", work / "probe.lock"), \
unittest.mock.patch.object(packprobe.subprocess, "run", fake_run):
env = {"RETROBIOS_PROBE_LOCK": str(work / "probe.lock"), "RETROBIOS_PROBE_LOCK_HELD": ""}
with unittest.mock.patch.dict(os.environ, env), \
unittest.mock.patch.object(packprobe, "run_group", fake_run):
code, record, error = packprobe.core_probe(["run"], set(), layout({}), work)
self.assertEqual((code, record), (1, None))
self.assertEqual(error, 'File "<repo>/scripts/core_probe.py", line 9')
+7 -6
View File
@@ -8,7 +8,8 @@ import tests
import unittest
from pathlib import Path
from probes import regioncheck
from core_probe import EXIT_BUSY
from probes import host, regioncheck
ROOT = Path(__file__).resolve().parent.parent
@@ -74,16 +75,16 @@ class BusyHost(unittest.TestCase):
def pause(seconds: float) -> None:
now[0] += seconds
proc = regioncheck.probe_when_idle(["probe"], max_wait, clock=lambda: now[0], pause=pause, runner=runner)
proc = host.run_when_idle(["probe"], max_wait, clock=lambda: now[0], pause=pause, runner=runner)
return proc.returncode, len(calls)
def test_a_refused_run_is_tried_again_once_the_host_settles(self) -> None:
self.assertEqual(self._run([regioncheck.BUSY, regioncheck.BUSY, 0], 600), (0, 3))
self.assertEqual(self._run([EXIT_BUSY, EXIT_BUSY, 0], 600), (0, 3))
def test_it_gives_up_after_the_wait(self) -> None:
code, calls = self._run([regioncheck.BUSY], 60)
self.assertEqual(code, regioncheck.BUSY)
self.assertEqual(calls, 60 // regioncheck.POLL_S + 1)
code, calls = self._run([EXIT_BUSY], 60)
self.assertEqual(code, EXIT_BUSY)
self.assertEqual(calls, 60 // host.BUSY_POLL + 1)
def test_another_failure_is_not_retried(self) -> None:
self.assertEqual(self._run([1, 0], 600), (1, 1))