diff --git a/scripts/campaign.py b/scripts/campaign.py index 83167ebf4..368dffd45 100644 --- a/scripts/campaign.py +++ b/scripts/campaign.py @@ -61,94 +61,38 @@ job runs it on a schedule. from __future__ import annotations import argparse -import contextlib -import datetime as dt -import hashlib -import http.client -import io import json -import os import re -import shutil import signal -import stat -import subprocess import sys -import tarfile -import threading -import time -import urllib.error -import urllib.request -import zipfile -from collections.abc import Callable, Iterator, Sequence -from dataclasses import dataclass, field +from collections.abc import Sequence from pathlib import Path -from typing import IO, TYPE_CHECKING, TypedDict, TypeVar -if TYPE_CHECKING: - from typing_extensions import Unpack +# First: the floor, before anything else fails on an older interpreter. +if sys.version_info < (3, 9): + sys.exit( + f"{Path(sys.argv[0]).name} needs Python 3.9 or newer, " + f"this is {sys.version.split()[0]}" + ) sys.path.insert(0, str(Path(__file__).resolve().parent)) -# First: core_probe stops an interpreter older than 3.9 before anything else -# fails on it. -import core_probe - import yaml import autorun -from core import childenv from core import hostguard -from core import statefile -from probes import profileedit as campaign_profiles -from probes import rules -from model import measurements as mr -from core.statefile import now_iso +from probes.profileedit import ProfileEditError from core.paths import REPO_ROOT +from probes.campaign import Campaign +from probes.content import ROMFETCH_ENV +from probes.gate import changed_profiles, gate +from probes.host import CONTENT_FILE, Paths, Settings, host_lock +from probes.reports import REVIEWED, open_findings, render_status, review_finding, status_report -T = TypeVar("T") -CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" -BUILDBOT = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/" -LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV -ROMFETCH_ENV = "RETROBIOS_ROMFETCH" -STATE_VERSION = 1 - -DONE = "done" -FAILED = "failed" -PENDING = "pending" - -CRASH_ATTEMPTS = 3 -NETWORK_DELAYS = (10, 60, 300) -MAX_ALIAS_CANDIDATES = 6 -MAX_REGION_DUMPS = 2 -BENCH_WARMUP = 600 -BENCH_FRAMES = 1800 -BENCH_REPEAT = 5 -CHECK_REPEAT = 2 -PROBE_TIMEOUT = 900 -BUILD_TIMEOUT = 3600 -LOG_DAYS = 30 -ROMFETCH_TRANSIENT = 3 EXIT_REFUSED = 3 -class Pause(RuntimeError): - """The host cannot run measurements now: the pass stops and resumes later.""" - - -class Unavailable(RuntimeError): - """A core or a piece of content the campaign cannot get.""" - - -# -------------------------------------------------------------------------- -# Small helpers -# -------------------------------------------------------------------------- - -def slug(text: str) -> str: - return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x" - - def parse_budget(text: str) -> float: match = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*([smh]?)\s*", text or "") if not match: @@ -156,1802 +100,6 @@ def parse_budget(text: str) -> float: return float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600}[match[2]] -def file_sha256(path: Path) -> str: - digest = hashlib.sha256() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def file_sha1(path: Path) -> str: - digest = hashlib.sha1() - with path.open("rb") as handle: - for chunk in iter(lambda: handle.read(1 << 20), b""): - digest.update(chunk) - return digest.hexdigest() - - -def profile_digest(profile: dict) -> str: - """What a check depends on in a profile: its entries, evidence left out, - so the campaign's own evidence never makes it run again.""" - entries = [{k: v for k, v in entry.items() if k != "evidence"} - for entry in profile.get("files") or []] - body = {"files": entries, "cores": profile.get("cores"), "type": profile.get("type"), - "systems": profile.get("systems")} - return hashlib.sha1(mr.canonical(body)).hexdigest() - - -def entry_systems(entry: dict, profile: dict) -> list[str]: - if entry.get("systems"): - return list(entry["systems"]) - if entry.get("system"): - return [entry["system"]] - return list(profile.get("systems") or []) - - -def entry_dest(entry: dict) -> str: - """Where the core reads the entry, relative to its system directory.""" - path = entry.get("path") - if isinstance(path, str) and path and not path.endswith("/"): - return path - return entry["name"] - - -def region_matches(entry: dict, region: str | None) -> bool: - regions = entry.get("region") - if not regions or not region: - return True - if isinstance(regions, str): - regions = [regions] - return region in regions or "world" in regions - - -def regions_of(entry: dict) -> list[str]: - regions = entry.get("region") or [] - return [regions] if isinstance(regions, str) else list(regions) - - -def is_bios(entry: dict) -> bool: - return entry.get("category", "bios") == "bios" and entry.get("type") != "directory" - - -# -------------------------------------------------------------------------- -# Host -# -------------------------------------------------------------------------- - -class PopenOptions(TypedDict, total=False): - """The Popen arguments the campaign passes through run_group.""" - - cwd: str | Path - env: dict[str, str] - text: bool - stdout: int | IO[str] | IO[bytes] - stderr: int | IO[str] | IO[bytes] - - -def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool = False, - capture_output: bool = False, **kwargs: Unpack[PopenOptions]) -> subprocess.CompletedProcess: - """subprocess.run in a process group of its own, the whole group killed - on a timeout or an interruption: a hung core never outlives its run.""" - if capture_output: - kwargs.setdefault("stdout", subprocess.PIPE) - kwargs.setdefault("stderr", subprocess.PIPE) - with subprocess.Popen(list(argv), start_new_session=True, **kwargs) as proc: - try: - out, err = proc.communicate(timeout=timeout) - except BaseException: - with contextlib.suppress(ProcessLookupError): - os.killpg(proc.pid, signal.SIGKILL) - proc.communicate() - raise - result = subprocess.CompletedProcess(list(argv), proc.returncode, out, err) - if check: - result.check_returncode() - return result - - -@dataclass -class Host: - """What the campaign reads from the machine and the network, replaced in tests.""" - - loadavg: Callable[[], tuple[float, float, float]] = os.getloadavg - sleep: Callable[[float], None] = time.sleep - clock: Callable[[], float] = time.monotonic - cpu_count: int = os.cpu_count() or 1 - free_gb: Callable[[Path], float] = hostguard.free_gb - poll: float = 60.0 - run: Callable[..., subprocess.CompletedProcess] = run_group - urlopen: Callable[..., http.client.HTTPResponse] = urllib.request.urlopen - - @property - def max_load(self) -> float: - return self.cpu_count / 4 - - -@dataclass -class Settings: - budget: float = 6 * 3600 - max_load_wait: float = 3600 - min_free_gb: float = 30 - cache_cap_gb: float = 20 - probe_timeout: int = PROBE_TIMEOUT - check_repeat: int = CHECK_REPEAT - bench_repeat: int = BENCH_REPEAT - bench_warmup: int = BENCH_WARMUP - bench_frames: int = BENCH_FRAMES - romfetch: str = "" - network: bool = True - # Benchmarks only choose between variants: never part of a default pass. - bench: bool = False - delays: tuple[float, ...] = NETWORK_DELAYS - echo: bool = True - # Third-party code (a nightly core, a project's Makefile) runs only under - # bubblewrap unless this is set. - allow_unsandboxed: bool = False - - -@dataclass -class Paths: - """Where the campaign writes: records and profiles in the checkout it - runs from, state, cores, logs and content in the main checkout's .cache.""" - - root: Path - home: Path - content: Path - db: Path - content_file: Path = CONTENT_FILE - oracle: Path = core_probe.DEFAULT_ORACLE - - @property - def state(self) -> Path: - return self.home / "state.json" - - @property - def logs(self) -> Path: - return self.home / "logs" - - @property - def emulators(self) -> Path: - return self.root / "emulators" - - @classmethod - def default(cls) -> Paths: - main = autorun.main_checkout() - return cls(root=REPO_ROOT, home=main / ".cache" / "campaign", - content=main / ".cache" / "test-content", db=REPO_ROOT / "database.json") - - -ROMFETCH_PASSED = ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME") - - -def child_env(romfetch: bool = False) -> dict[str, str]: - """What a program the campaign starts inherits: autorun's allowlist, - never a token or a password. romfetch also gets its own settings - (ROMFETCH_*), its account staying in its config file.""" - names: list[str] = [core_probe.PROBE_LOCK_ENV, core_probe.PROBE_LOCK_HELD_ENV] - if romfetch: - names += [k for k in os.environ if k.startswith("ROMFETCH_")] + list(ROMFETCH_PASSED) - return childenv.safe_env(names) - - -# Host-side git on a third-party project. It only ever touches bare mirrors -# this campaign created: no working tree, never bound into a sandbox. No user -# or system config is read, https is the only transport, and the overrides -# blank every hook, filter, proxy and ssh command a config could name. -GIT_SAFE = ( - "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", - "-c", "core.sshCommand=", "-c", "core.gitProxy=", "-c", "core.askPass=", - "-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", - "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=", "-c", "filter.lfs.process=", - "-c", "filter.lfs.required=false", "-c", "core.attributesFile=/dev/null", -) -MIRROR_URL = re.compile(r"^https://[A-Za-z0-9.-]+(?::\d+)?/[A-Za-z0-9._~/+-]+$") - - -def host_git(*args: str) -> list[str]: - return ["git", *GIT_SAFE, *args] - - -def git_env() -> dict[str, str]: - env = child_env() - env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0", - GIT_ALLOW_PROTOCOL="https", GIT_ATTR_NOSYSTEM="1") - return env - - -def blank_filters(repo: Path) -> list[str]: - """-c overrides emptying every filter driver the repository's config, - includes followed, defines: git archive runs smudge filters.""" - config = repo / "config" - if not config.is_file(): - return [] - listing = run_group(["git", "config", "--file", str(config), "--includes", "--name-only", - "--get-regexp", r"^filter\."], capture_output=True, env=git_env(), - timeout=60).stdout.decode("utf-8", "replace") - drivers = sorted({line.rsplit(".", 1)[0] for line in listing.splitlines() if line.count(".") >= 2}) - out = [] - for driver in drivers: - for key in ("smudge", "clean", "process"): - out += ["-c", f"{driver}.{key}="] - out += ["-c", f"{driver}.required=false"] - return out - - -def git_out(*args: str, timeout: int = 1800) -> bytes: - extra = blank_filters(Path(args[1])) if len(args) > 1 and args[0] == "-C" else [] - return run_group(["git", *GIT_SAFE, *extra, *args], capture_output=True, check=True, - env=git_env(), timeout=timeout).stdout - - -def submodule_url(base: str, url: str) -> str: - """A .gitmodules URL, relative ones read against the parent's URL.""" - if url.startswith(("./", "../")): - parts = base.rstrip("/").removesuffix(".git").split("/") - for piece in url.split("/"): - if piece == "..": - parts.pop() - elif piece not in (".", ""): - parts.append(piece) - url = "/".join(parts) - return url - - -def extract_tar(blob: bytes, target: Path) -> None: - """A git archive unpacked into target: no absolute path, no .., no link - that leaves target.""" - target.mkdir(parents=True, exist_ok=True) - with tarfile.open(fileobj=io.BytesIO(blob)) as handle: - if hasattr(tarfile, "data_filter"): - handle.extractall(target, filter="data") - return - for member in handle.getmembers(): - name = Path(member.name) - link = Path(member.linkname) - if name.is_absolute() or ".." in name.parts or member.islnk() or ( - member.issym() and (link.is_absolute() or ".." in link.parts)): - raise Unavailable(f"core: unsafe archive member {member.name}") - handle.extractall(target) - - -def export_commit(mirror: Callable[[str], Path], url: str, commit: str, dest: Path) -> None: - """The tree of commit, and of each submodule at the commit the tree - records, as plain files in a fresh dest. Every object comes from a bare - mirror (mirror(url) fetches into it), never from a working tree.""" - if dest.exists(): - shutil.rmtree(dest) - - def one(repo_url: str, sha: str, target: Path) -> None: - if not re.fullmatch(r"[0-9a-f]{40}", sha): - raise Unavailable(f"core: {sha!r} is not a commit id") - bare = mirror(repo_url) - try: - git_out("-C", str(bare), "cat-file", "-e", f"{sha}^{{commit}}") - except subprocess.CalledProcessError: - git_out("-C", str(bare), "fetch", "--quiet", repo_url, sha) - extract_tar(git_out("-C", str(bare), "archive", "--format=tar", sha), target) - links: dict[str, str] = {} - for entry in git_out("-C", str(bare), "ls-tree", "-r", "-z", sha).split(b"\0"): - if entry.startswith(b"160000 commit "): - meta, raw_path = entry.split(b"\t", 1) - links[raw_path.decode()] = meta.split()[2].decode() - if not links: - return - try: - config = git_out("-C", str(bare), "config", "--blob", f"{sha}:.gitmodules", "-z", - "--get-regexp", r"^submodule\..*\.(path|url)$").decode() - except subprocess.CalledProcessError as exc: - raise Unavailable(f"core: {repo_url} has submodules and no readable .gitmodules") from exc - paths: dict[str, str] = {} - urls: dict[str, str] = {} - for item in filter(None, config.split("\0")): - key, _, value = item.partition("\n") - name, field_ = key[len("submodule."):].rsplit(".", 1) - (paths if field_ == "path" else urls)[name] = value - for name, path in paths.items(): - if path in links and name in urls: - one(submodule_url(repo_url, urls[name]), links[path], target / path) - - one(url, commit, dest) - - -def built_core(tree: Path) -> Path: - """The newest *_libretro.so a build left: a regular file inside the tree, - never a link a build could point at a host file.""" - root = tree.resolve() - found = [] - for path in tree.rglob("*_libretro.so"): - info = path.lstat() - if stat.S_ISREG(info.st_mode) and path.resolve().is_relative_to(root): - found.append((info.st_mtime, path)) - if not found: - raise Unavailable(f"core: the build left no *_libretro.so regular file in {tree}") - return max(found)[1] - - -def copy_regular(src: Path, dest: Path) -> None: - """Copy src only when it is a regular file, never through a link.""" - fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW) - with os.fdopen(fd, "rb") as handle: - if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): - raise Unavailable(f"core: {src} is not a regular file") - dest.parent.mkdir(parents=True, exist_ok=True) - with dest.open("wb") as out: - shutil.copyfileobj(handle, out) - - -# The working directory belongs to the process. Two passes in threads that -# each saved and restored it could leave the process in the other's root, -# then in a folder deleted with its workspace. -_CWD_LOCK = threading.Lock() - - -@contextlib.contextmanager -def working_directory(path: Path) -> Iterator[None]: - """contextlib.chdir, which Python 3.9 lacks, one thread at a time.""" - with _CWD_LOCK: - before = Path.cwd() - os.chdir(path) - try: - yield - finally: - os.chdir(before) - - -@contextlib.contextmanager -def host_lock(lock_path: Path) -> Iterator[None]: - """The automation lock, unless the autorun job running us holds it.""" - if os.environ.get(LOCK_HELD_ENV): - yield - return - with hostguard.global_lock(lock_path): - yield - - -# -------------------------------------------------------------------------- -# State -# -------------------------------------------------------------------------- - -def load_state(path: Path) -> dict: - try: - state = json.loads(path.read_text(encoding="utf-8")) - except FileNotFoundError: - state = {} - state.setdefault("version", STATE_VERSION) - for key in ("checks", "cores", "content", "builds", "emulators"): - state.setdefault(key, {}) - return state - - -def save_state(path: Path, state: dict) -> None: - statefile.save_state(path, state) - - -def should_run(previous: dict | None, core_sha: str, digest: str, oracle_sha: str = "") -> bool: - """A check runs again when it never ran, is pending, or ran against - another core build, another version of the profile, another oracle, or - before records carried a verdict.""" - if not previous: - return True - if previous.get("status") == PENDING: - return True - return (previous.get("core_sha256") != core_sha or previous.get("profile_digest") != digest - or previous.get("record_version") != mr.RECORD_VERSION - or previous.get("oracle_sha256", "") != oracle_sha) - - -# -------------------------------------------------------------------------- -# Content: what each system is tested with, and where it comes from -# -------------------------------------------------------------------------- - -@dataclass(frozen=True) -class Content: - system: str - romfetch_system: str - name: str - catalog: str - reason: str - region: str | None - load: str - frames: int - frame_hash_every: int - pinned: bool - boot_file: str | None - - @property - def key(self) -> str: - return f"{self.romfetch_system}/{self.name}" - - -def load_content(path: Path) -> dict[str, list[Content]]: - data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - out: dict[str, list[Content]] = {} - for system, spec in (data.get("systems") or {}).items(): - for item in spec.get("content") or (): - out.setdefault(system, []).append(Content( - system=system, romfetch_system=str(spec["romfetch"]), name=str(item["name"]), - catalog=str(item["catalog"]), reason=str(item["reason"]).strip(), - region=item.get("region"), load=str(item.get("load") or ""), - frames=int(item.get("frames", 3600)), - frame_hash_every=int(item.get("frame_hash_every", 10)), - pinned=bool(item.get("pinned", False)), boot_file=spec.get("boot_file"), - )) - return out - - -def load_file(folder: Path, load: str) -> Path: - """The file handed to the core.""" - if load == "cue": - cues = sorted(folder.glob("*.cue")) - if len(cues) != 1: - raise Unavailable(f"{folder.name}: {len(cues)} .cue files, one expected") - return cues[0] - if load: - return folder / load - files = [p for p in sorted(folder.iterdir()) if p.is_file() and p.name != "identity.json"] - if len(files) != 1: - raise Unavailable(f"{folder.name}: {len(files)} files, name one with load:") - return files[0] - - -def verify_identity(folder: Path) -> dict: - """The identity.json romfetch wrote, each listed file hashed again.""" - try: - identity = json.loads((folder / "identity.json").read_text(encoding="utf-8")) - except FileNotFoundError as exc: - raise Unavailable(f"{folder}: no identity.json") from exc - if identity.get("status") != "verified": - raise Unavailable(f"{folder.name}: identity status {identity.get('status')!r}") - for item in identity.get("files") or (): - path = folder / item["name"] - if not path.is_file() or path.stat().st_size != item["size"] or file_sha1(path) != item["sha1"]: - raise Unavailable(f"{folder.name}: {item['name']} does not match its identity") - return identity - - -def folder_size(folder: Path) -> int: - return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file()) - - -class ContentStore: - """Content on disk, its users counted, the least recently used evicted - past the cap. Only what the campaign fetched is ever deleted, and never - a pinned entry.""" - - def __init__(self, campaign: Campaign) -> None: - self.c = campaign - self.state: dict = campaign.state["content"] - self.refs: dict[str, set[str]] = {} - self.verified: set[str] = set() - - def folder(self, content: Content) -> Path: - return self.c.paths.content / content.romfetch_system / content.name - - def hold(self, content: Content, user: str) -> None: - self.refs.setdefault(content.key, set()).add(user) - - def get(self, content: Content) -> Path: - """The folder of the content, fetched when absent. Unavailable when not.""" - folder = self.folder(content) - entry = self.state.setdefault(content.key, {"fetched_by_campaign": False}) - entry["pinned"] = content.pinned - if not (folder / "identity.json").is_file(): - self.evict(keep={content.key}) - self.fetch(content) - entry["fetched_by_campaign"] = True - if content.key not in self.verified: - identity = verify_identity(folder) - entry["identity"] = {"catalog": identity.get("catalog"), "dat": identity.get("dat"), - "entry": identity.get("entry")} - self.verified.add(content.key) - entry["size"] = folder_size(folder) - entry["last_used"] = now_iso() - return folder - - def romfetch(self) -> str | None: - configured = self.c.settings.romfetch or os.environ.get(ROMFETCH_ENV, "") - if configured: - return configured if Path(configured).is_file() or shutil.which(configured) else None - return shutil.which("romfetch") - - def fetch(self, content: Content) -> None: - command = self.romfetch() - if not command: - raise Unavailable(f"content: romfetch not found, {content.catalog} entry {content.name!r}") - if not self.c.settings.network: - raise Unavailable(f"content: offline, {content.catalog} entry {content.name!r}") - argv = [command, "get", content.romfetch_system, content.name, "--json", "-q", - "--content-dir", str(self.c.paths.content)] - for attempt, delay in enumerate((*self.c.settings.delays, None)): - proc = self.c.host.run(argv, capture_output=True, text=True, check=False, - timeout=6 * 3600, env=child_env(romfetch=True)) - if proc.returncode == 0: - self.c.log(f"romfetch {content.name}: {proc.stdout.strip()[:300]}") - return - code = "unknown" - with contextlib.suppress(ValueError, AttributeError): - code = json.loads(proc.stdout)["error"]["code"] - if proc.returncode != ROMFETCH_TRANSIENT or delay is None: - raise Unavailable(f"content: romfetch exit {proc.returncode} ({code}) " - f"for {content.name!r}") - self.c.log(f"romfetch {content.name}: exit {proc.returncode} ({code}), " - f"retry {attempt + 1} in {delay}s") - self.c.host.sleep(delay) - - def release(self, content: Content, user: str) -> None: - users = self.refs.get(content.key, set()) - users.discard(user) - if not users: - self.drop(content.key) - - def deletable(self, key: str) -> bool: - entry = self.state.get(key) or {} - return bool(entry.get("fetched_by_campaign")) and not entry.get("pinned") - - def drop(self, key: str) -> bool: - if not self.deletable(key) or self.refs.get(key): - return False - folder = self.c.paths.content / key - if folder.is_dir(): - shutil.rmtree(folder) - self.c.log(f"content {key}: deleted, no check left needs it") - self.state.pop(key, None) - self.verified.discard(key) - return True - - def evict(self, keep: set[str]) -> list[str]: - """Least recently used first, until the campaign's content fits the cap.""" - cap = self.c.settings.cache_cap_gb * 1024 ** 3 - held = sorted((entry.get("last_used", ""), key) for key, entry in self.state.items() - if self.deletable(key) and key not in keep) - total = sum(entry.get("size", 0) for key, entry in self.state.items() if self.deletable(key)) - evicted = [] - for _, key in held: - if total <= cap: - break - size = self.state[key].get("size", 0) - folder = self.c.paths.content / key - if folder.is_dir(): - shutil.rmtree(folder) - self.state.pop(key, None) - self.verified.discard(key) - total -= size - evicted.append(key) - self.c.log(f"content {key}: evicted, the cache is over {self.c.settings.cache_cap_gb} GB") - return evicted - - -# -------------------------------------------------------------------------- -# Cores -# -------------------------------------------------------------------------- - -@dataclass(frozen=True) -class Core: - name: str - path: Path - sha256: str - artifact: str | None = None - repo: str | None = None - commit: str | None = None - build_command: str | None = None - - -def safe_extract_so(archive: Path, member: str, target: Path) -> None: - with zipfile.ZipFile(archive) as handle: - names = handle.namelist() - if member not in names: - raise Unavailable(f"{archive.name}: no {member} inside ({', '.join(names[:5])})") - target.parent.mkdir(parents=True, exist_ok=True) - scratch = target.with_suffix(".part") - with handle.open(member) as src, scratch.open("wb") as dst: - shutil.copyfileobj(src, dst) - os.replace(scratch, target) - - -class Cores: - """Buildbot nightlies, downloaded once per build, else local builds of - the profile's pinned commit.""" - - def __init__(self, campaign: Campaign) -> None: - self.c = campaign - self.listing: set[str] | None = None - - def retrying(self, what: str, call: Callable[[], T]) -> T: - for attempt, delay in enumerate((*self.c.settings.delays, None)): - try: - return call() - except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc: - if isinstance(exc, urllib.error.HTTPError) and exc.code < 500 and exc.code != 429: - raise Unavailable(f"{what}: HTTP {exc.code}") from exc - if delay is None: - raise Unavailable(f"{what}: {exc}") from exc - self.c.log(f"{what}: {exc}, retry {attempt + 1} in {delay}s") - self.c.host.sleep(delay) - raise AssertionError("unreachable") - - def buildbot(self) -> set[str]: - if self.listing is None: - if not self.c.settings.network: - self.listing = set() - else: - def read() -> bytes: - with self.c.host.urlopen(BUILDBOT, timeout=120) as response: - return response.read() - page = self.retrying("buildbot listing", read).decode("utf-8", "replace") - self.listing = set(re.findall(r"([A-Za-z0-9_]+)_libretro\.so\.zip", page)) - return self.listing - - def names(self, profile: dict) -> list[str]: - listing = self.buildbot() - return sorted({str(c) for c in profile.get("cores") or () if str(c) in listing}) - - def nightly(self, name: str, profile: dict) -> Core: - url = f"{BUILDBOT}{name}_libretro.so.zip" - cached = self.c.state["cores"].get(name) or {} - - def head() -> dict: - request = urllib.request.Request(url, method="HEAD") - with self.c.host.urlopen(request, timeout=120) as response: - return {"etag": response.headers.get("ETag"), - "last_modified": response.headers.get("Last-Modified")} - stamp = self.retrying(f"{name} nightly", head) - target = self.c.paths.home / "cores" / name / f"{name}_libretro.so" - if (cached.get("etag"), cached.get("last_modified")) != (stamp["etag"], stamp["last_modified"]) \ - or not target.is_file() or file_sha256(target) != cached.get("sha256"): - archive = target.parent / f"{name}_libretro.so.zip" - archive.parent.mkdir(parents=True, exist_ok=True) - - def download() -> None: - with self.c.host.urlopen(url, timeout=600) as response, archive.open("wb") as out: - shutil.copyfileobj(response, out) - self.retrying(f"{name} nightly", download) - safe_extract_so(archive, f"{name}_libretro.so", target) - archive.unlink() - cached = {**stamp, "url": url, "sha256": file_sha256(target), "fetched_at": now_iso()} - self.c.state["cores"][name] = cached - self.c.log(f"core {name}: new nightly {cached['sha256'][:12]} ({stamp['last_modified']})") - repo = profile.get("source") if isinstance(profile.get("source"), str) else None - return Core(name, target, cached["sha256"], artifact=url, - repo=repo if repo and repo.startswith("http") else None) - - def build(self, emulator: str, profile: dict) -> Core: - """The profile's pinned commit, built once and kept.""" - source, commit = profile.get("source"), profile.get("source_commit") - if not (isinstance(source, str) and source.startswith("http") and isinstance(commit, str)): - raise Unavailable("core: not on the buildbot, and no source and source_commit to build") - record = self.c.state["builds"].setdefault(emulator, {}) - if record.get("commit") == commit and record.get("error"): - raise Unavailable(f"core: build of {commit[:12]} failed before: {record['error']}") - out = self.c.paths.home / "builds" / emulator / commit - built = sorted(out.glob("*_libretro.so")) - if not built: - if not self.c.settings.network: - raise Unavailable("core: not on the buildbot, offline, nothing built yet") - try: - so, command = self.compile(source, commit, out) - except Unavailable as exc: - self.c.state["builds"][emulator] = {"commit": commit, "error": str(exc), "at": now_iso()} - raise - built = [so] - record["command"] = command - command = record.get("command") or "make" - self.c.state["builds"][emulator] = {"commit": commit, "command": command, - "so": built[0].name, "at": now_iso()} - return Core(built[0].name.removesuffix("_libretro.so"), built[0], file_sha256(built[0]), - repo=source, commit=commit, build_command=command) - - def mirror(self, url: str) -> Path: - """The bare mirror of a repository, created on first use. Only host - git with the overrides of GIT_SAFE ever touches it.""" - if not MIRROR_URL.match(url): - raise Unavailable(f"core: {url!r} is not an https repository URL") - bare = self.c.paths.home / "mirrors" / f"{slug(url)}.git" - if not (bare / "HEAD").is_file(): - bare.parent.mkdir(parents=True, exist_ok=True) - git_out("clone", "--bare", "--quiet", url, str(bare)) - return bare - - def compile(self, source: str, commit: str, out: Path) -> tuple[Path, str]: - """Fetch the commit into a bare mirror (host git, networked), export - it and its submodules with git archive into a fresh folder, and run - the project's make there under bubblewrap: no network, that folder - the one writable path. Returns the .so and the command, with how it - was isolated.""" - log = self.c.paths.logs / "builds" / f"{slug(source)}-{commit[:12]}.log" - log.parent.mkdir(parents=True, exist_ok=True) - isolation = core_probe.sandbox_argv([])[1] - if isolation != core_probe.SANDBOX and not self.c.settings.allow_unsandboxed: - raise Unavailable(f"refused: no sandbox to build {source} in ({isolation}), " - f"--allow-unsandboxed overrides") - # Working-tree clones of earlier campaign versions are never reused. - shutil.rmtree(self.c.paths.home / "src", ignore_errors=True) - tree = self.c.paths.home / "build-trees" / f"{slug(source)}-{commit[:12]}" - try: - export_commit(self.mirror, source, commit, tree) - except (OSError, subprocess.CalledProcessError, tarfile.TarError) as exc: - raise Unavailable(f"core: exporting {commit[:12]} of {source} failed: {exc}") from exc - makefile = "Makefile.libretro" if (tree / "Makefile.libretro").is_file() else "Makefile" - jobs = str(max(1, (os.cpu_count() or 2) // 2)) - command = ["make", "-f", makefile, f"-j{jobs}", "platform=unix"] - prefix, isolation = core_probe.sandbox_argv([tree]) - with log.open("a", encoding="utf-8") as handle: - handle.write(f"$ {' '.join(command)} in {tree} ({isolation})\n") - handle.flush() - proc = self.c.host.run(prefix + command, cwd=tree, stdout=handle, stderr=subprocess.STDOUT, - check=False, timeout=BUILD_TIMEOUT, env=child_env()) - if proc.returncode != 0: - tail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()[-3:] - raise Unavailable(f"core: make exited {proc.returncode}: {' | '.join(tail)} (log {log})") - built = built_core(tree) - copy_regular(built, out / built.name) - shutil.rmtree(tree, ignore_errors=True) - return out / built.name, f"{' '.join(command)} on git archive (isolation: {isolation})" - - -# -------------------------------------------------------------------------- -# Probe runs -# -------------------------------------------------------------------------- - -@dataclass -class ProbeResult: - status: str - record: dict | None = None - reason: str = "" - log: str = "" - - -@dataclass -class Unit: - """One core of one emulator profile, with its systems' content.""" - - emulator: str - profile: dict - core_name: str | None = None - pending: str = "" - # A game engine or utility profile: run when the buildbot has its core, - # otherwise it is a standalone program. - buildbot_only: bool = False - - -@dataclass(frozen=True) -class Trial: - """One core on one content: what every check of that pairing shares.""" - - unit: Unit - core: Core - content: Content - load: Path - frames: list[str] - digest: str - - -@dataclass(frozen=True) -class Held: - """A declared file the collection holds, at its place.""" - - index: int - entry: dict - dest: str - local: Path - - -@dataclass -class Pass: - started: str - records: list[str] = field(default_factory=list) - findings: dict[str, int] = field(default_factory=dict) - touched: set[str] = field(default_factory=set) - result: str = "complete" - detail: str = "" - - -class Campaign: - def __init__(self, paths: Paths, settings: Settings | None = None, host: Host | None = None, - probe_script: Path | None = None, lock_path: Path | None = None) -> None: - self.paths = paths - self.settings = settings or Settings() - self.host = host or Host() - self.probe_script = probe_script or REPO_ROOT / "scripts" / "core_probe.py" - self.lock_path = lock_path or Path(os.environ.get(hostguard.LOCK_ENV) or hostguard.DEFAULT_LOCK) - self.state = load_state(paths.state) - self.cores = Cores(self) - self.store = ContentStore(self) - self.content = load_content(paths.content_file) - self.oracle_sha = file_sha256(paths.oracle) if paths.oracle.is_file() else "" - self.oracle_data = core_probe.load_oracle(paths.oracle)[0] - self.deadline = 0.0 - self.current: Pass | None = None - self.dirty_at_start: set[str] = set() - self._db: dict | None = None - - # -- logging ------------------------------------------------------------ - - def log(self, text: str) -> None: - line = f"{now_iso()} {text}" - path = self.paths.logs / f"{dt.date.today().isoformat()}.log" - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(line + "\n") - if self.settings.echo: - print(line, file=sys.stderr) - - # -- profiles and files ------------------------------------------------- - - def profiles(self) -> dict[str, dict]: - out = {} - for path in sorted(self.paths.emulators.glob("*.yml")): - if path.name.startswith("_") or path.stem == "00_example": - continue - data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - if "emulator" in data: - out[path.stem] = data - return out - - @property - def db(self) -> dict: - if self._db is None: - self._db = json.loads(self.paths.db.read_text(encoding="utf-8")) - return self._db - - def local_file(self, entry: dict) -> Path | None: - """The collection's copy of an entry, by its declared hashes or its name.""" - from resolve.localfile import resolve_local_file - - hint = entry.get("path") if isinstance(entry.get("path"), str) else "" - # The database names files relative to the checkout it describes. - with working_directory(self.paths.root): - path, status = resolve_local_file(entry, self.db, dest_hint=hint or "") - if not path or status in ("not_found", "hash_mismatch"): - return None - local = Path(path) - local = local if local.is_absolute() else self.paths.root / local - return local if local.is_file() else None - - def variant_files(self, entry: dict, primary: Path) -> list[Path]: - """The .variants/ copies of an entry's file the collection holds.""" - names = [entry["name"], *(entry.get("aliases") or ())] - out = [] - index = self.db.get("indexes", {}).get("by_name", {}) - for name in names: - for sha1 in index.get(name, ()): - path = (self.db["files"].get(sha1) or {}).get("path", "") - if "/.variants/" in path: - local = self.paths.root / path - if local.is_file() and local.resolve() != primary.resolve() and local not in out: - out.append(local) - return out - - # -- guards --------------------------------------------------------------- - - def guard(self) -> None: - """Raise Pause when the pass must stop: budget spent, disk full, host busy.""" - if self.host.clock() >= self.deadline: - raise Pause("budget") - free = self.host.free_gb(self.paths.home if self.paths.home.exists() else self.paths.root) - 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 - - # -- one core_probe invocation ------------------------------------------- - - def probe(self, argv: list[str], log_name: str) -> ProbeResult: - """core_probe with retries for a crashing core. Never raises for the core's sake.""" - command = [sys.executable, str(self.probe_script), *argv] - log = self.paths.logs / dt.date.today().isoformat() / f"{log_name}.log" - log.parent.mkdir(parents=True, exist_ok=True) - 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 - 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()) - except subprocess.TimeoutExpired: - with log.open("a", encoding="utf-8") as handle: - handle.write(f"$ {' '.join(command)}\nkilled after {budget} s\n") - return ProbeResult(FAILED, reason="timeout", log=str(log)) - with log.open("a", encoding="utf-8") as handle: - handle.write(f"$ {' '.join(command)}\n# exit {proc.returncode}\n" - f"{proc.stderr[-20000:]}\n") - if proc.returncode == 0: - try: - 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: - # 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 - attempt += 1 - if proc.returncode == 2: - return ProbeResult(FAILED, reason=f"core_probe refused the run: " - f"{proc.stderr.strip()[-300:]}", log=str(log)) - if "TimeoutExpired" in proc.stderr or "timed out after" in proc.stderr: - return ProbeResult(FAILED, reason="timeout", log=str(log)) - self.log(f"{log_name}: attempt {attempt} exited {proc.returncode}") - return ProbeResult(FAILED, reason=f"crashed {CRASH_ATTEMPTS} times", log=str(log)) - - def probe_args(self, mode: str, core: Core, emulator: str, subject: str, content: Content | None, - load: Path | None) -> list[str]: - argv = [mode, "--core", str(core.path), "--record", str(self.paths.root), - "--emulator", emulator, "--subject", subject, - "--max-load", str(self.host.max_load), "--timeout", str(self.settings.probe_timeout), - "--work-dir", str(self.paths.root / "tmp" / "core_probe")] - if self.paths.oracle.is_file(): - argv += ["--oracle", str(self.paths.oracle)] - if not self.settings.allow_unsandboxed: - argv.append("--require-sandbox") - if core.artifact: - argv += ["--core-artifact", core.artifact] - if core.repo: - argv += ["--core-repo", core.repo] - if core.commit: - argv += ["--core-commit", core.commit] - if core.build_command: - argv += ["--build-command", core.build_command] - if content and load: - argv += ["--content", str(load), "--content-label", content.name] - return argv - - # -- the checks ------------------------------------------------------------- - - def check_key(self, core: Core, content: Content, check: str) -> str: - return f"{core.name}/{content.system}/{slug(content.name)}/{check}" - - def remember(self, emulator: str, key: str, result: ProbeResult, core: Core | None, - digest: str) -> None: - judged = None - if result.record and result.record["inputs"].get("content"): - judged = [result.record["inputs"]["content"]["sha1"], result.record["core"]["library_name"]] - entry = {"status": result.status, "at": now_iso(), "profile_digest": digest, - "core_sha256": core.sha256 if core else None, - "record_version": mr.RECORD_VERSION, "oracle_sha256": self.oracle_digest(judged)} - if judged: - entry["oracle_key"] = judged - if result.reason: - entry["reason"] = result.reason - if result.log: - entry["log"] = result.log - if result.record: - entry["record"] = result.record["id"] - if self.current: - self.current.records.append(result.record["id"]) - self.current.touched.add(mr.records_path(emulator)) - self.state["checks"].setdefault(emulator, {})[key] = entry - - def pending(self, emulator: str, key: str, reason: str, digest: str = "") -> None: - self.state["checks"].setdefault(emulator, {})[key] = { - "status": PENDING, "reason": reason, "at": now_iso(), "profile_digest": digest} - - def oracle_digest(self, key: list[str] | None) -> str: - """What a check's verdicts depend on in the oracle: the entries of its - content and core, else the whole file. Another core's references - never make a check run again.""" - if not key: - return self.oracle_sha - return mr.value_sha1(core_probe.oracle_for(self.oracle_data, *key)) - - def needed(self, emulator: str, key: str, core: Core, digest: str) -> bool: - previous = self.state["checks"].get(emulator, {}).get(key) - judged = (previous or {}).get("oracle_key") - if previous and not judged and previous.get("record"): - record = self.read_record(emulator, previous["record"]) or {} - if (record.get("inputs") or {}).get("content"): - judged = [record["inputs"]["content"]["sha1"], record["core"]["library_name"]] - previous["oracle_key"] = judged - # Judged against the entries the record kept, not the file it named. - kept = {k: v for k, v in (record["inputs"].get("oracle") or {}).items() - if k not in ("file", "sha256")} - previous["oracle_sha256"] = mr.value_sha1({"bios_patterns": [], **kept}) - return should_run(previous, core.sha256, digest, self.oracle_digest(judged)) - - def check(self, emulator: str, key: str, core: Core, digest: str, argv: list[str], - log_name: str) -> dict | None: - """The record of a check: run now when needed, else the one kept.""" - if not self.needed(emulator, key, core, digest): - previous = self.state["checks"].get(emulator, {}).get(key) or {} - return self.read_record(emulator, previous.get("record")) - result = self.probe(argv, log_name) - self.remember(emulator, key, result, core, digest) - return result.record - - def system_entries(self, profile: dict, system: str) -> list[tuple[int, dict]]: - from resolve.validation import filter_files_by_mode - - libretro = filter_files_by_mode(profile.get("files") or [], standalone=False) - keep = {id(e) for e in libretro} - return [(i, e) for i, e in enumerate(profile.get("files") or []) - if id(e) in keep and system in entry_systems(e, profile) and is_bios(e)] - - def boot_entry(self, entries: list[tuple[int, dict]], content: Content) -> tuple[int, dict] | None: - held = [(i, e) for i, e in entries if region_matches(e, content.region) and self.local_file(e)] - if content.boot_file: - named = [(i, e) for i, e in held - if content.boot_file in (e["name"], *(e.get("aliases") or ()))] - if named: - return named[0] - held.sort(key=lambda item: (item[1].get("priority", 1 << 30), item[0])) - return held[0] if held else None - - @staticmethod - def other_regions(entry: dict, staged: dict[str, tuple[int, dict, Path]], local: Path) -> list[Path]: - """Held dumps of the same system for regions this entry does not - serve, one per distinct file: the wrong-region variants.""" - mine = set(regions_of(entry)) - if not mine or "world" in mine: - return [] - out: dict[str, Path] = {} - for _, other, path in staged.values(): - theirs = set(regions_of(other)) - if theirs and "world" not in theirs and not theirs & mine and path.resolve() != local.resolve(): - out.setdefault(file_sha1(path), path) - return sorted(out.values(), key=lambda p: p.name)[:MAX_REGION_DUMPS] - - def run_unit_content(self, unit: Unit, core: Core, content: Content, digest: str) -> None: - emulator, profile = unit.emulator, unit.profile - entries = self.system_entries(profile, content.system) - staged: dict[str, tuple[int, dict, Path]] = {} - for index, entry in entries: - local = self.local_file(entry) - if local and entry_dest(entry) not in staged: - staged[entry_dest(entry)] = (index, entry, local) - tested = {dest: item for dest, item in staged.items() if region_matches(item[1], content.region)} - keys = self.content_keys(core, content, tested) - # The rules run on every pass, from the records kept when nothing - # needs to run again: a change of the table applies without a run. - try: - folder = self.store.get(content) - load = load_file(folder, content.load) - except Unavailable as exc: - for key in keys.values(): - if self.needed(emulator, key, core, digest): - self.pending(emulator, key, str(exc), digest) - return - frames = ["--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every)] - trial = Trial(unit, core, content, load, frames, digest) - records = self.reference_runs(trial, keys, staged) - if not records: - return - files_record, none_record = records - full = rules.run_of(files_record, files_record["variants"][0]["label"]) - none = rules.run_of(none_record, none_record["variants"][0]["label"]) - self.log(f"{emulator}: {core.name} on {content.name}: full set {full.verdict}, " - f"no BIOS {none.verdict}") - - for dest, (index, entry, local) in sorted(tested.items()): - self.test_entry(trial, keys[f"negative:{dest}"], Held(index, entry, dest, local), staged, - files_record, none) - - boot = self.boot_entry(entries, content) - if boot and entry_dest(boot[1]) in tested: - index, entry = boot - self.follow_aliases(trial, index, entry, tested[entry_dest(entry)][2], none_record) - - if self.settings.bench and full.verdict == rules.BOOTS: - self.bench(trial, keys["bench"], boot) - - def content_keys(self, core: Core, content: Content, - tested: dict[str, tuple[int, dict, Path]]) -> dict[str, str]: - keys = {"files": self.check_key(core, content, "files"), - "none": self.check_key(core, content, "none")} - for dest in tested: - keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}") - if self.settings.bench: - keys["bench"] = self.check_key(core, content, "bench") - return keys - - def reference_runs(self, trial: Trial, keys: dict[str, str], - staged: dict[str, tuple[int, dict, Path]]) -> tuple[dict, dict] | None: - """The full set and no BIOS at all, or None while either is missing.""" - core, emulator, content, load = trial.core, trial.unit.emulator, trial.content, trial.load - repeat = ["--repeat", str(self.settings.check_repeat)] - stem = f"{core.name}-{slug(content.name)}" - - # files: every declared file the collection holds, at its place. - argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + trial.frames + repeat - for dest, (_, _, local) in sorted(staged.items()): - argv += ["--system-file", f"{dest}={local}"] - files_record = self.check(emulator, keys["files"], core, trial.digest, argv, f"{emulator}-{stem}-files") - # none: no BIOS at all. - argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + trial.frames + repeat - none_record = self.check(emulator, keys["none"], core, trial.digest, argv, f"{emulator}-{stem}-none") - if not files_record or not none_record: - return None - return files_record, none_record - - def test_entry(self, trial: Trial, key: str, held: Held, staged: dict[str, tuple[int, dict, Path]], - files_record: dict, none: rules.Run) -> None: - """One declared file alone and replaced, then what its runs settle.""" - emulator, content, entry = trial.unit.emulator, trial.content, held.entry - record = self.negative(trial, key, held, staged) - if not record: - return - labels = [v["label"] for v in record["variants"]] - present = rules.run_of(record, labels[0]) - zeros, half = (rules.run_of(record, label) for label in labels[1:3]) - for label in labels[3:]: - self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}") - if held.dest in self.opened(files_record, 0) or held.dest in self.opened(record, 0): - verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half)) - validation = rules.rule_validation(zeros, half, none, present, entry) - if validation: - verdicts.append(validation) - self.settle(emulator, content, trial.core, held.index, entry, verdicts) - variants = self.variant_files(entry, held.local) - if variants: - self.run_variants(trial, held, variants) - else: - self.moved(trial, held, files_record, record) - - def bench(self, trial: Trial, key: str, boot: tuple[int, dict] | None) -> None: - core, emulator, content = trial.core, trial.unit.emulator, trial.content - stem = f"{core.name}-{slug(content.name)}" - argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, trial.load) - argv += ["--warmup", str(self.settings.bench_warmup), "--frames", - str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat), - "--no-trace"] - if boot: - argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"] - self.check(emulator, key, core, trial.digest, argv, f"{emulator}-{stem}-bench") - - def negative(self, trial: Trial, key: str, held: Held, - staged: dict[str, tuple[int, dict, Path]]) -> dict | None: - """The file alone, then wrong files under its name: zeros of its - size, its first half, and other regions' dumps.""" - core, content, entry, dest, local = trial.core, trial.content, held.entry, held.dest, held.local - unit = trial.unit - stem = f"{core.name}-{slug(content.name)}" - size = local.stat().st_size - others = self.other_regions(entry, staged, local) - argv = self.probe_args("check", core, unit.emulator, slug(f"negative-{entry['name']}-{stem}"), - content, trial.load) + trial.frames - argv += ["--vary", f"{dest}={local}", "--vary", f"{dest}=@zeros:{size}", - "--vary", f"{dest}=@head:{size // 2}:{local}"] - for other in others: - argv += ["--vary", f"{dest}={other}"] - regions = f", then {', '.join(p.name for p in others)} staged under its name" if others else "" - argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat), - "--claim", (f"{core.name} boots {content.name} with {entry['name']} alone and " - f"refuses a wrong file under its name"), - "--method", (f"{entry['name']} alone as {dest}, then {size} zero bytes and its " - f"first {size // 2} bytes{regions}, nothing else staged. Each run " - f"{self.settings.check_repeat} times from a fresh process for " - f"{content.frames} frames with no button pressed, every " - f"{content.frame_hash_every}th frame hashed. The boot oracle judges " - f"each variant against the reference frames of {content.name}.")] - return self.check(unit.emulator, key, core, trial.digest, argv, f"{unit.emulator}-{stem}-negative") - - def moved(self, trial: Trial, held: Held, files_record: dict, alone: dict) -> None: - """A file the core opened neither in the full set nor alone: where - else it looked for a file of that name, else flagged.""" - unit, core, content = trial.unit, trial.core, trial.content - index, entry, dest = held.index, held.entry, held.dest - probed = [p for record in (files_record, alone) for r in record["variants"][0]["repetitions"] - for p in r.get("files_probed_absent") or ()] - others = [p for p in dict.fromkeys(probed) if p != dest - and p.rsplit("/", 1)[-1].casefold() == dest.rsplit("/", 1)[-1].casefold()] - for candidate in others[:MAX_ALIAS_CANDIDATES]: - found = self.follow_up(trial, entry, held.local, candidate, f"path:{entry['name']}:{candidate}") - if found and candidate in self.opened(found, 0): - verdict = rules.rule_path(entry, dest, rules.Opened(candidate, found["id"])) - if verdict: - self.settle(unit.emulator, content, core, index, entry, [verdict]) - return - verdict = rules.rule_never_opened(entry, [files_record["id"], alone["id"]], content.name) - self.settle(unit.emulator, content, core, index, entry, [verdict]) - - def read_record(self, emulator: str, rid: str | None) -> dict | None: - """A record by its id, or the record that supersedes it: a run - judged again offline is read as judged last.""" - if not rid: - return None - path = self.paths.root / mr.records_path(emulator) - if not path.is_file(): - return None - records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] - by_id = {r["id"]: r for r in records} - successor = {r["supersedes"]: r["id"] for r in records if r.get("supersedes")} - seen = set() - while rid in successor and rid not in seen: - seen.add(rid) - rid = successor[rid] - return by_id.get(rid) - - def judged(self, emulator: str, rid: str) -> bool: - """True for a record the boot oracle judged: only those prove a field.""" - record = self.read_record(emulator, rid) - return record is not None and record.get("record_version", 0) >= 4 - - @staticmethod - def opened(record: dict, position: int) -> set[str]: - out: set[str] = set() - for rep in record["variants"][position]["repetitions"]: - out |= {item["path"] for item in rep.get("files_opened") or ()} - return out - - def follow_up(self, trial: Trial, entry: dict, local: Path, dest: str, check: str) -> dict | None: - """The file staged at dest alone: does the core open it there.""" - unit, core, content = trial.unit, trial.core, trial.content - stem = f"{core.name}-{slug(content.name)}" - argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, trial.load) - argv += trial.frames + ["--system-file", f"{dest}={local}"] - return self.check(unit.emulator, self.check_key(core, content, check), core, trial.digest, argv, - f"{unit.emulator}-{stem}-{slug(check)}") - - def follow_aliases(self, trial: Trial, index: int, entry: dict, local: Path, none_record: dict) -> None: - """Names the core looked for, with no BIOS, that no entry declares.""" - unit, core, content = trial.unit, trial.core, trial.content - declared = {e["name"] for e in unit.profile.get("files") or ()} - declared |= {a for e in unit.profile.get("files") or () for a in e.get("aliases") or ()} - suffix = Path(entry["name"]).suffix.casefold() - dest = entry_dest(entry) - folder = dest.rsplit("/", 1)[0] if "/" in dest else "" - probed: list[str] = [] - for rep in none_record["variants"][0]["repetitions"]: - for path in rep.get("files_probed_absent") or (): - name = path.rsplit("/", 1)[-1] - where = path.rsplit("/", 1)[0] if "/" in path else "" - if (where == folder and name not in declared and Path(name).suffix.casefold() == suffix - and path not in probed): - probed.append(path) - for candidate in probed[:MAX_ALIAS_CANDIDATES]: - found = self.follow_up(trial, entry, local, candidate, - f"alias:{entry['name']}:{candidate.rsplit('/', 1)[-1]}") - if found and candidate in self.opened(found, 0): - verdict = rules.rule_alias(self.reload_entry(unit, index), rules.Opened(candidate, found["id"])) - if verdict: - self.settle(unit.emulator, content, core, index, self.reload_entry(unit, index), [verdict]) - - def run_variants(self, trial: Trial, held: Held, variants: list[Path]) -> None: - unit, core, content, digest = trial.unit, trial.core, trial.content, trial.digest - index, entry, dest = held.index, held.entry, held.dest - key = self.check_key(core, content, f"variants:{entry['name']}") - if not self.needed(unit.emulator, key, core, digest): - return - stem = f"{core.name}-{slug(content.name)}" - argv = self.probe_args("check", core, unit.emulator, slug(f"variants-{entry['name']}-{stem}"), - content, trial.load) + trial.frames - for path in [held.local, *variants]: - argv += ["--vary", f"{dest}={path}"] - argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat), - "--claim", f"every copy of {entry['name']} boots {content.name} on {core.name}", - "--method", (f"Each copy the collection holds staged alone as {dest}, each run " - f"{self.settings.check_repeat} times for {content.frames} frames. The " - f"boot oracle judges each copy.")] - record = self.check(unit.emulator, key, core, digest, argv, f"{unit.emulator}-{stem}-variants") - if record: - verdict = rules.rule_variants([rules.run_of(record, v["label"]) for v in record["variants"]], - entry) - if verdict: - self.settle(unit.emulator, content, core, index, entry, [verdict]) - - # -- verdicts ----------------------------------------------------------------- - - def reload_entry(self, unit: Unit, index: int) -> dict: - path = self.paths.emulators / f"{unit.emulator}.yml" - unit.profile = yaml.safe_load(path.read_text(encoding="utf-8")) - return unit.profile["files"][index] - - def settle(self, emulator: str, content: Content, core: Core, index: int, entry: dict, - verdicts: Sequence[rules.Verdict]) -> None: - """Apply what the table settles, queue the rest, resolve what now agrees.""" - path = self.paths.emulators / f"{emulator}.yml" - for verdict in verdicts: - fresh = (yaml.safe_load(path.read_text(encoding="utf-8")).get("files") or [])[index] - if fresh.get("name") != entry.get("name"): - self.log(f"{emulator}: files[{index}] is no longer {entry.get('name')}, nothing applied") - return - says = rules.current(fresh, verdict.field) if verdict.field in rules.SETTLED_FIELDS \ - else None - agrees = verdict.field in rules.SETTLED_FIELDS and rules.agrees(fresh, verdict) - if verdict.apply: - updates: dict[str, object] = {} - if not agrees or (verdict.field not in fresh and verdict.field != "validation"): - updates[verdict.field] = verdict.value - evidence = rules.merge_evidence(fresh.get("evidence"), verdict, - keep=lambda rid: self.judged(emulator, rid)) - if evidence != fresh.get("evidence"): - updates["evidence"] = evidence - if updates: - try: - changed = campaign_profiles.write_fields(path, index, updates) - except campaign_profiles.ProfileEditError as exc: - self.finding(emulator, content, core, fresh, verdict, "open", says, - extra=f". Not written: {exc}") - continue - if changed and self.current: - self.current.touched.add(path.relative_to(self.paths.root).as_posix()) - if agrees: - self.resolve(emulator, content, core, fresh, verdict, says) - else: - self.finding(emulator, content, core, fresh, verdict, "applied", says) - continue - if verdict.rule == "never_opened": - self.finding(emulator, content, core, fresh, verdict, "flagged", None) - elif agrees: - self.resolve(emulator, content, core, fresh, verdict, says) - else: - self.finding(emulator, content, core, fresh, verdict, "open", says) - - def finding_key(self, emulator: str, content: Content, entry: dict, verdict: rules.Verdict) -> str: - return f"{emulator}/{content.system}/{entry['name']}/{verdict.field}" - - def latest_findings(self) -> dict[str, dict]: - latest: dict[str, dict] = {} - for line in mr.read_campaign(self.paths.root, mr.FINDINGS): - latest[line["key"]] = line - return latest - - def finding(self, emulator: str, content: Content, core: Core, entry: dict, - verdict: rules.Verdict, status: str, says: object, extra: str = "") -> None: - key = self.finding_key(emulator, content, entry, verdict) - previous = self.latest_findings().get(key) - if previous and previous["status"] == status and previous["rule"] == verdict.rule \ - and previous["run_shows"] == verdict.value and previous["profile_says"] == says \ - and previous["evidence"] == list(verdict.evidence): - return - # A review that read the code and kept the profile stands while the - # runs keep showing the same thing. - if previous and previous["status"] == "rejected" and status == "open" \ - and previous["rule"] == verdict.rule and previous["run_shows"] == verdict.value \ - and previous["profile_says"] == says: - return - line = mr.seal_line({ - "schema_version": 1, "found_at": now_iso(), "key": key, "emulator": emulator, - "system": content.system, "file": entry["name"], "field": verdict.field, - "status": status, "rule": verdict.rule, "profile_says": says, "run_shows": verdict.value, - "statement": verdict.statement + extra, "evidence": list(verdict.evidence), - "core": {"file": core.path.name, "sha256": core.sha256, - "library_version": self.library_version(emulator, verdict.evidence)}, - "content": content.name, - }, "found_at") - path = self.paths.root / mr.records_path(mr.FINDINGS) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(mr.line_text(line) + "\n") - if self.current: - self.current.findings[status] = self.current.findings.get(status, 0) + 1 - self.current.touched.add(mr.records_path(mr.FINDINGS)) - self.log(f"finding {status}: {key}: {verdict.statement}") - - def resolve(self, emulator: str, content: Content, core: Core, entry: dict, - verdict: rules.Verdict, says: object) -> None: - previous = self.latest_findings().get(self.finding_key(emulator, content, entry, verdict)) - if previous and previous["status"] in ("open", "flagged"): - self.finding(emulator, content, core, entry, verdict, "resolved", says) - - def library_version(self, emulator: str, ids: Sequence[str]) -> str | None: - for rid in ids: - record = self.read_record(emulator, rid) - if record: - return record["core"].get("library_version") - return None - - # -- reference frames ----------------------------------------------------------- - - def references(self, only: set[str], system: str | None, png_dir: Path) -> list[dict]: - """The full set run once per core and content, frames written as PNG, - and the screens that stay on long enough to serve as references.""" - self.deadline = self.host.clock() + self.settings.budget - listed = [] - for unit in self.units(only, system): - contents = self.unit_contents(unit, system) - if unit.pending or not contents: - continue - try: - cores = self.unit_cores(unit.emulator, unit.profile, unit.buildbot_only) - except Unavailable as exc: - self.log(f"{unit.emulator}: {exc}") - continue - for core in cores: - for content in contents: - self.guard() - self.store.hold(content, "references") - try: - load = load_file(self.store.get(content), content.load) - except Unavailable as exc: - self.log(f"{unit.emulator}: {exc}") - continue - stem = f"{core.name}-{slug(content.name)}" - target = png_dir / slug(core.name) / slug(content.name) - shutil.rmtree(target, ignore_errors=True) - argv = self.probe_args("run", core, unit.emulator, slug(f"references-{stem}"), - content, load) - argv += ["--frames", str(content.frames), "--frame-hash-every", - str(content.frame_hash_every), "--repeat", str(self.settings.check_repeat), - "--png-dir", str(target)] - for _, entry in self.system_entries(unit.profile, content.system): - local = self.local_file(entry) - if local and f"{entry_dest(entry)}=" not in " ".join(argv): - argv += ["--system-file", f"{entry_dest(entry)}={local}"] - result = self.probe(argv, f"{unit.emulator}-{stem}-references") - self.store.release(content, "references") - if not result.record: - self.log(f"{unit.emulator}: references of {content.name}: {result.reason}") - continue - record = result.record - listed.append({ - "emulator": unit.emulator, "core": core.name, - "library_name": record["core"]["library_name"], "content": content.name, - "content_sha1": record["inputs"]["content"]["sha1"], "record": record["id"], - "verdict": record["variants"][0]["verdict"], - "png_dir": str(target / record["variants"][0]["label"]), - "candidates": reference_candidates(record), - }) - save_state(self.paths.state, self.state) - return listed - - # -- the pass ----------------------------------------------------------------- - - def units(self, only: set[str], system: str | None) -> list[Unit]: - out = [] - for emulator, profile in sorted(self.profiles().items()): - cores = {str(c) for c in profile.get("cores") or ()} - if only and emulator not in only and not (cores & only): - continue - systems = set(profile.get("systems") or ()) - if system and system not in systems: - continue - kind = str(profile.get("type") or "") - if kind in ("alias", "launcher", "test"): - continue - if "libretro" in kind or kind in ("game", "utility"): - out.append(Unit(emulator, profile, buildbot_only="libretro" not in kind)) - continue - out.append(Unit(emulator, profile, pending="standalone")) - return out - - def unit_contents(self, unit: Unit, system: str | None) -> list[Content]: - systems = [s for s in unit.profile.get("systems") or () if not system or s == system] - return [c for s in systems for c in self.content.get(s, ())] - - def run(self, only: set[str], system: str | None, dry_run: bool = False, - commit_every: int = 0, commit: bool = False) -> Pass: - self.deadline = self.host.clock() + self.settings.budget - current = self.current = Pass(started=now_iso()) - units = self.units(only, system) - if dry_run: - self.describe(units, system) - return current - isolation = core_probe.sandbox_argv([])[1] - if isolation != core_probe.SANDBOX and not self.settings.allow_unsandboxed: - # Fail closed: no core and no build runs outside the sandbox. - current.result = "refused" - current.detail = (f"no sandbox for third-party code ({isolation}). Install bubblewrap, " - f"or pass --allow-unsandboxed") - self.log(f"pass refused: {current.detail}") - self.write_run_line(current) - save_state(self.paths.state, self.state) - return current - for unit in units: - for content in self.unit_contents(unit, system): - self.store.hold(content, unit.emulator) - done_units = 0 - try: - for unit in units: - self.run_unit(unit, system) - done_units += 1 - save_state(self.paths.state, self.state) - if commit and commit_every and done_units % commit_every == 0: - self.commit_batch() - except Pause as exc: - current.result = "budget" if str(exc) == "budget" else "paused" - current.detail = str(exc) - self.log(f"pass paused: {exc}") - except KeyboardInterrupt: - current.result, current.detail = "stopped", "interrupted" - finally: - for unit in units: - for content in self.unit_contents(unit, system): - self.store.release(content, unit.emulator) - self.prune_logs() - self.write_run_line(current) - save_state(self.paths.state, self.state) - if commit: - self.commit_batch() - return current - - def run_unit(self, unit: Unit, system: str | None) -> None: - emulator, profile = unit.emulator, unit.profile - digest = profile_digest(profile) - contents = self.unit_contents(unit, system) - systems = [s for s in profile.get("systems") or () if not system or s == system] - if unit.pending: - for s in systems: - self.pending(emulator, f"*/{s}/*", unit.pending, digest) - return - if not contents: - for s in systems: - self.pending(emulator, f"*/{s}/*", f"content: no test content listed for {s}", digest) - return - try: - cores = self.unit_cores(emulator, profile, unit.buildbot_only) - except Unavailable as exc: - for s in systems: - self.pending(emulator, f"*/{s}/*", str(exc), digest) - self.log(f"{emulator}: {exc}") - return - for s in systems: - self.state["checks"].setdefault(emulator, {}).pop(f"*/{s}/*", None) - for core in cores: - self.log(f"{emulator}: core {core.name} {core.sha256[:12]}") - for content in contents: - self.guard() - self.run_unit_content(Unit(emulator, profile, core.name), core, content, digest) - for content in contents: - self.store.release(content, emulator) - self.state["emulators"][emulator] = {"profile_digest": profile_digest( - yaml.safe_load((self.paths.emulators / f"{emulator}.yml").read_text(encoding="utf-8"))), - "at": now_iso()} - # The campaign's own edits do not make its checks run again. - new_digest = self.state["emulators"][emulator]["profile_digest"] - for entry in self.state["checks"].get(emulator, {}).values(): - if entry.get("profile_digest") == digest: - entry["profile_digest"] = new_digest - - def unit_cores(self, emulator: str, profile: dict, buildbot_only: bool = False) -> list[Core]: - names = self.cores.names(profile) - if names: - return [self.cores.nightly(name, profile) for name in names] - if buildbot_only: - raise Unavailable("standalone: no libretro core on the buildbot") - return [self.cores.build(emulator, profile)] - - def describe(self, units: list[Unit], system: str | None) -> None: - for unit in units: - contents = self.unit_contents(unit, system) - if unit.pending: - print(f"{unit.emulator}: pending, {unit.pending}") - elif not contents: - print(f"{unit.emulator}: pending, no test content for " - f"{', '.join(unit.profile.get('systems') or ())}") - else: - cores = sorted({str(c) for c in unit.profile.get("cores") or ()}) - print(f"{unit.emulator}: cores {', '.join(cores)} on " - f"{', '.join(c.name for c in contents)}") - - def counts(self) -> tuple[dict[str, int], dict[str, int], list[dict]]: - counts = {DONE: 0, FAILED: 0, PENDING: 0} - reasons: dict[str, int] = {} - failed = [] - for emulator, checks in sorted(self.state["checks"].items()): - for key, entry in sorted(checks.items()): - status = entry.get("status", PENDING) - counts[status] = counts.get(status, 0) + 1 - if status == PENDING: - reason = reason_class(entry.get("reason", "")) - reasons[reason] = reasons.get(reason, 0) + 1 - elif status == FAILED: - failed.append({"emulator": emulator, "check": key, "reason": entry.get("reason", "")}) - return counts, reasons, failed - - def write_run_line(self, current: Pass) -> None: - counts, reasons, failed = self.counts() - line = mr.seal_line({ - "schema_version": 1, "started_at": current.started, "ended_at": now_iso(), - "result": current.result, "detail": current.detail, "counts": counts, - "pending_reasons": reasons, "failed": failed, "records": current.records, - "findings": dict(sorted(current.findings.items())), - }, "started_at") - path = self.paths.root / mr.records_path(mr.CAMPAIGN_RUNS) - path.parent.mkdir(parents=True, exist_ok=True) - with path.open("a", encoding="utf-8") as handle: - handle.write(mr.line_text(line) + "\n") - current.touched.add(mr.records_path(mr.CAMPAIGN_RUNS)) - self.state["last_run"] = {k: line[k] for k in ("id", "started_at", "ended_at", "result", "detail")} - - def prune_logs(self) -> None: - limit = time.time() - LOG_DAYS * 86400 - for path in self.paths.logs.rglob("*.log") if self.paths.logs.is_dir() else (): - if path.stat().st_mtime < limit: - path.unlink() - - # -- commits (direct runs, autorun commits by its own rules) ------------------- - - def plan_commits(self, dirty_at_start: set[str]) -> list[tuple[str, list[str]]]: - """(subject, paths) of each commit: the records, then one per profile.""" - touched = sorted(self.current.touched if self.current else ()) - records = [p for p in touched if p.startswith(f"{mr.RECORDS_DIR}/") and p not in dirty_at_start] - plan = [] - if records: - plan.append(("chore: add campaign measurements", records)) - for path in touched: - if path.startswith("emulators/") and path not in dirty_at_start: - subject = f"chore: apply tested fields to {Path(path).stem}" - if len(subject) > 50: - subject = "chore: apply tested profile fields" - plan.append((subject, [path])) - return plan - - def commit_batch(self, dry_run: bool = False) -> list[str]: - plan = self.plan_commits(self.dirty_at_start) - if dry_run or not plan: - for subject, paths in plan: - print(f"would commit {subject!r}: {', '.join(paths)}") - return [] - if gate(self.paths.root, [Path(p).stem for _, ps in plan for p in ps if p.startswith("emulators/")], - self.host) != 0: - self.log("gate failed, nothing committed") - return [] - made = [] - for subject, paths in plan: - problems = autorun.check_subject(subject) - if problems: - raise ValueError(f"{subject!r}: {', '.join(problems)}") - made.append(autorun.commit_paths(self.paths.root, paths, autorun.CommitRule(subject, tuple(paths)))) - if self.current: - self.current.touched.clear() - return made - - -def reference_candidates(record: dict, min_samples: int = 3) -> list[dict]: - """Screens of a record's first variant that are not one colour and stay - on for at least min_samples consecutive samples in every repetition: - what a reviewer looks at to choose reference frames.""" - found: list[dict[str, tuple[int, int]]] = [] - for rep in record["variants"][0]["repetitions"]: - observables = rep.get("observables") or {} - uniform = set(observables.get("uniform_frames") or ()) - runs: dict[str, tuple[int, int]] = {} - previous, start, length = None, 0, 0 - for frame, digest in [*(observables.get("frame_hashes") or ()), (None, None)]: - if digest == previous: - length += 1 - continue - if previous and previous not in uniform and length >= min_samples: - first, longest = runs.get(previous, (start, 0)) - runs[previous] = (min(first, start), max(longest, length)) - previous, start, length = digest, frame, 1 - found.append(runs) - common = set(found[0]) if found else set() - for runs in found[1:]: - common &= set(runs) - return sorted(({"sha1": digest, "first_frame": found[0][digest][0], "samples": found[0][digest][1]} - for digest in common), key=lambda item: item["first_frame"]) - - -def reason_class(reason: str) -> str: - """A pending reason without its detail, to count them.""" - head = reason.split(":", 1)[0].strip() if ":" in reason else reason - return head or "unknown" - - -# -------------------------------------------------------------------------- -# Gate -# -------------------------------------------------------------------------- - -def gate(root: Path, emulators: Sequence[str], host: Host | None = None) -> int: - """The measurement tests, the schemas, and verify plus an emulator pack - for each profile the campaign changed.""" - host = host or Host() - python = sys.executable - steps = [ - [python, "-m", "unittest", "tests.test_measurements", "tests.test_campaign"], - [python, "scripts/validate_schemas.py", "--source-only"], - ] - for emulator in sorted(set(emulators)): - steps.append([python, "scripts/verify.py", "--emulator", emulator]) - steps.append([python, "scripts/generate_pack.py", "--emulator", emulator, "--offline", - "--output-dir", "tmp/campaign/packs"]) - for argv in steps: - proc = host.run(argv, cwd=root, check=False) - if proc.returncode != 0: - print(f"gate: {' '.join(argv)} exited {proc.returncode}", file=sys.stderr) - return 1 - shutil.rmtree(root / "tmp" / "campaign" / "packs", ignore_errors=True) - return 0 - - -def changed_profiles(root: Path) -> list[str]: - return [Path(p).stem for p in autorun.changed_files(root) - if p.startswith("emulators/") and p.endswith(".yml")] - - -# -------------------------------------------------------------------------- -# Reports -# -------------------------------------------------------------------------- - -def status_report(campaign: Campaign) -> dict: - counts, reasons, failed = campaign.counts() - runs = mr.read_campaign(campaign.paths.root, mr.CAMPAIGN_RUNS) - per = {} - for emulator, checks in sorted(campaign.state["checks"].items()): - per[emulator] = {key: {k: v for k, v in entry.items() if k in ("status", "reason", "record", "at")} - for key, entry in sorted(checks.items())} - return {"last_run": runs[-1] if runs else None, "counts": counts, "pending_reasons": reasons, - "failed": failed, "emulators": per} - - -def render_status(report: dict) -> str: - lines = [] - last = report["last_run"] - if last: - lines.append(f"last run {last['started_at']} to {last['ended_at']}: {last['result']}" - + (f" ({last['detail']})" if last["detail"] else "")) - else: - lines.append("no run yet") - counts = report["counts"] - lines.append(f"{counts.get(DONE, 0)} done, {counts.get(FAILED, 0)} failed, " - f"{counts.get(PENDING, 0)} pending") - lines.extend(f" pending {number:5} {reason}" - for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1])) - lines.extend(f" FAILED {item['emulator']} {item['check']}: {item['reason']}" for item in report["failed"]) - for emulator, checks in report["emulators"].items(): - ran = [k for k, v in checks.items() if v["status"] != PENDING] - if ran: - lines.append(f"{emulator}") - for key in ran: - entry = checks[key] - lines.append(f" {entry['status']:7} {key}" + (f" {entry['record']}" if entry.get("record") else "") - + (f" ({entry['reason']})" if entry.get("reason") else "")) - return "\n".join(lines) - - -def open_findings(root: Path, everything: bool = False) -> list[dict]: - latest: dict[str, dict] = {} - for line in mr.read_campaign(root, mr.FINDINGS): - latest[line["key"]] = line - return [line for key, line in sorted(latest.items()) - if everything or line["status"] in ("open", "flagged")] - - -REVIEWED = ("applied", "rejected") - - -def review_finding(root: Path, key: str, status: str, reason: str, - updates: dict[str, object] | None = None, index: int | None = None) -> dict: - """Close an open finding after reading the core's code. - - `applied` writes `updates` into the entry the finding names, through the - same editor as the rule table, with the finding's record ids added as - `evidence:` under its field. An applied finding with no update records a - profile changed by hand. `rejected` keeps the profile as it is. Either - way a line with the reason is appended to the findings.""" - if status not in REVIEWED: - raise ValueError(f"status {status!r}: one of {', '.join(REVIEWED)}") - if not reason.strip(): - raise ValueError("a review names its reason") - latest = {line["key"]: line for line in mr.read_campaign(root, mr.FINDINGS)} - finding = latest.get(key) - if finding is None: - raise ValueError(f"no finding {key}") - if finding["status"] not in ("open", "flagged"): - raise ValueError(f"{key} is {finding['status']}, not open") - if updates and status != "applied": - raise ValueError("only an applied review changes the profile") - if updates: - path = root / "emulators" / f"{finding['emulator']}.yml" - entries = yaml.safe_load(path.read_text(encoding="utf-8")).get("files") or [] - matches = [i for i, entry in enumerate(entries) if entry.get("name") == finding["file"]] - if index is not None: - matches = [i for i in matches if i == index] - if len(matches) != 1: - raise ValueError(f"{finding['emulator']}: {len(matches)} entries named {finding['file']}" - + ("" if index is not None else ", pass --index")) - entry = entries[matches[0]] - verdict = rules.Verdict(finding["rule"], finding["field"], finding["run_shows"], - finding["statement"], tuple(finding["evidence"])) - evidence = rules.merge_evidence(entry.get("evidence"), verdict) - campaign_profiles.write_fields(path, matches[0], {**updates, "evidence": evidence}) - body = {key_: value for key_, value in finding.items() if key_ != "id"} - line = mr.seal_line({**body, "found_at": now_iso(), "status": status, "reason": reason}, - "found_at") - with (root / mr.records_path(mr.FINDINGS)).open("a", encoding="utf-8") as handle: - handle.write(mr.line_text(line) + "\n") - return line - - # -------------------------------------------------------------------------- # Command line # -------------------------------------------------------------------------- @@ -2017,7 +165,7 @@ def _review(parser: argparse.ArgumentParser, args: argparse.Namespace, paths: Pa try: line = review_finding(paths.root, args.key, args.status, args.reason, updates, args.index) - except (ValueError, campaign_profiles.ProfileEditError) as exc: + except (ValueError, ProfileEditError) as exc: print(f"campaign: {exc}", file=sys.stderr) return 1 print(f"{line['status']} {line['key']} [{line['id']}]") diff --git a/scripts/pack_probe.py b/scripts/pack_probe.py index a5ce0b4bb..edde2aeb0 100644 --- a/scripts/pack_probe.py +++ b/scripts/pack_probe.py @@ -59,7 +59,10 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) import autorun -import campaign +from probes import content as probes_content +from probes import cores as probes_cores +from probes import entries as probes_entries +from probes import host from model import measurements as mr from core.statefile import now_iso from model.systems import _norm_system_id @@ -79,7 +82,7 @@ PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml" CONTENT_DIR = MAIN / ".cache" / "test-content" CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores" WORK_DIR = REPO_ROOT / "tmp" / "pack_probe" -BUILDBOT = campaign.BUILDBOT +BUILDBOT = probes_cores.BUILDBOT PACK_PROBES = mr.PACK_PROBES INSTALLS = ("pack", "installer") VERDICTS = ("boots", "bios_error", "crash", "hang", "unknown") @@ -287,7 +290,7 @@ def choose_cores(config: dict, profiles: dict[str, dict], system: str, buildbot: def entry_paths(entry: dict) -> list[str]: """The paths a profile entry names under the system directory: its path or name, and its aliases beside it.""" - main = campaign.entry_dest(entry) + main = probes_entries.entry_dest(entry) folder = main.rsplit("/", 1)[0] + "/" if "/" in main else "" return [main] + [f"{folder}{alias}" for alias in entry.get("aliases") or ()] @@ -415,7 +418,7 @@ def fetch_core(name: str, refresh: bool = False) -> dict: with urllib.request.urlopen(url, timeout=600) as response, archive.open("wb") as out: shutil.copyfileobj(response, out) modified = response.headers.get("Last-Modified") - campaign.safe_extract_so(archive, f"{name}_libretro.so", so) + probes_cores.safe_extract_so(archive, f"{name}_libretro.so", so) archive.unlink() meta = {"name": name, "url": url, "last_modified": modified, "sha256": file_sha(so, "sha256"), "fetched_at": now_iso()} @@ -423,28 +426,28 @@ def fetch_core(name: str, refresh: bool = False) -> dict: return {**meta, "path": str(so)} -def load_contents(files: Sequence[Path]) -> dict[str, list[campaign.Content]]: - out: dict[str, list[campaign.Content]] = {} +def load_contents(files: Sequence[Path]) -> dict[str, list[probes_content.Content]]: + out: dict[str, list[probes_content.Content]] = {} for path in files: if path.is_file(): - for system, items in campaign.load_content(path).items(): + for system, items in probes_content.load_content(path).items(): out.setdefault(system, []).extend(items) return out -def content_folder(content: campaign.Content, fetch: bool) -> Path: +def content_folder(content: probes_content.Content, fetch: bool) -> Path: """The game's folder, fetched through romfetch when absent and asked to.""" folder = CONTENT_DIR / content.romfetch_system / content.name if not (folder / "identity.json").is_file() and fetch: romfetch = shutil.which("romfetch") if not romfetch: - raise campaign.Unavailable("romfetch not found") + raise host.Unavailable("romfetch not found") proc = subprocess.run([romfetch, "get", content.romfetch_system, content.name, "--json", "-q", "--content-dir", str(CONTENT_DIR)], capture_output=True, text=True, - check=False, env=campaign.child_env(romfetch=True)) + check=False, env=host.child_env(romfetch=True)) if proc.returncode != 0: - raise campaign.Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}") - campaign.verify_identity(folder) + raise host.Unavailable(f"romfetch exit {proc.returncode} for {content.name!r}") + probes_content.verify_identity(folder) return folder @@ -509,7 +512,7 @@ def core_probe(argv: list[str], staged: set[str], layout: Layout, work: Path) -> return proc.returncode, record, error[-1500:] -def probe_argv(core: dict, choice: CoreChoice, content: campaign.Content, load: Path, +def probe_argv(core: dict, choice: CoreChoice, content: probes_content.Content, load: Path, subject: str, record: bool, supersedes: str | None = None) -> list[str]: argv = ["run", "--core", core["path"], "--content", str(load), "--content-label", content.name, "--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every), @@ -534,7 +537,7 @@ class ProbeTarget: choice: CoreChoice core: dict system: str - content: campaign.Content + content: probes_content.Content load: Path @@ -621,7 +624,7 @@ def append_line(line: dict, root: Path = REPO_ROOT) -> dict: @dataclass class Unit: system: str - content: campaign.Content + content: probes_content.Content cores: list[CoreChoice] @@ -631,7 +634,7 @@ def plan(platform: str, systems: set[str] | None, cores: set[str] | None, profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) target = load_target_config(platform, TARGETS[platform], str(REPO_ROOT / "platforms")) units: list[Unit] = [] - for system, contents in sorted(load_contents([campaign.CONTENT_FILE, PACK_CONTENT_FILE]).items()): + for system, contents in sorted(load_contents([host.CONTENT_FILE, PACK_CONTENT_FILE]).items()): if systems and system not in systems: continue if not platform_system(config, system): @@ -666,8 +669,8 @@ def run(args: argparse.Namespace) -> int: try: for unit in units: try: - load = campaign.load_file(content_folder(unit.content, args.fetch), unit.content.load) - except campaign.Unavailable as exc: + load = probes_content.load_file(content_folder(unit.content, args.fetch), unit.content.load) + except host.Unavailable as exc: print(f"SKIP {unit.system}: {exc}", file=sys.stderr) continue for choice in unit.cores: diff --git a/scripts/probes/campaign.py b/scripts/probes/campaign.py new file mode 100644 index 000000000..ddaba783a --- /dev/null +++ b/scripts/probes/campaign.py @@ -0,0 +1,1001 @@ +"""One campaign pass: the checks of each emulator, the rule table, findings and commits.""" + +from __future__ import annotations + +import datetime as dt +import json +import os +import shutil +import subprocess +import sys +import time +from collections.abc import Sequence +from dataclasses import dataclass, field +from pathlib import Path + +import yaml + +import autorun +import core_probe +from core import hostguard +from core.paths import REPO_ROOT +from core.statefile import now_iso +from model import measurements as mr +from probes import rules +from probes.profileedit import ProfileEditError, write_fields +from probes.content import Content, ContentStore, load_content, load_file +from probes.cores import Core, Cores +from probes.entries import ( + entry_dest, + entry_systems, + is_bios, + profile_digest, + region_matches, + regions_of, +) +from probes.gate import gate +from probes.host import ( + Host, + Paths, + Settings, + Unavailable, + child_env, + file_sha1, + file_sha256, + slug, + working_directory, +) +from probes.state import DONE, FAILED, PENDING, load_state, save_state, should_run + + +CRASH_ATTEMPTS = 3 + + +MAX_ALIAS_CANDIDATES = 6 +MAX_REGION_DUMPS = 2 + + +LOG_DAYS = 30 + + +class Pause(RuntimeError): + """The host cannot run measurements now: the pass stops and resumes later.""" + + +# -------------------------------------------------------------------------- +# Probe runs +# -------------------------------------------------------------------------- + +@dataclass +class ProbeResult: + status: str + record: dict | None = None + reason: str = "" + log: str = "" + + +@dataclass +class Unit: + """One core of one emulator profile, with its systems' content.""" + + emulator: str + profile: dict + core_name: str | None = None + pending: str = "" + # A game engine or utility profile: run when the buildbot has its core, + # otherwise it is a standalone program. + buildbot_only: bool = False + + +@dataclass(frozen=True) +class Trial: + """One core on one content: what every check of that pairing shares.""" + + unit: Unit + core: Core + content: Content + load: Path + frames: list[str] + digest: str + + +@dataclass(frozen=True) +class Held: + """A declared file the collection holds, at its place.""" + + index: int + entry: dict + dest: str + local: Path + + +@dataclass +class Pass: + started: str + records: list[str] = field(default_factory=list) + findings: dict[str, int] = field(default_factory=dict) + touched: set[str] = field(default_factory=set) + result: str = "complete" + detail: str = "" + + +class Campaign: + def __init__(self, paths: Paths, settings: Settings | None = None, host: Host | None = None, + probe_script: Path | None = None, lock_path: Path | None = None) -> None: + self.paths = paths + self.settings = settings or Settings() + self.host = host or Host() + self.probe_script = probe_script or REPO_ROOT / "scripts" / "core_probe.py" + self.lock_path = lock_path or Path(os.environ.get(hostguard.LOCK_ENV) or hostguard.DEFAULT_LOCK) + self.state = load_state(paths.state) + self.cores = Cores(self) + self.store = ContentStore(self) + self.content = load_content(paths.content_file) + self.oracle_sha = file_sha256(paths.oracle) if paths.oracle.is_file() else "" + self.oracle_data = core_probe.load_oracle(paths.oracle)[0] + self.deadline = 0.0 + self.current: Pass | None = None + self.dirty_at_start: set[str] = set() + self._db: dict | None = None + + # -- logging ------------------------------------------------------------ + + def log(self, text: str) -> None: + line = f"{now_iso()} {text}" + path = self.paths.logs / f"{dt.date.today().isoformat()}.log" + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + if self.settings.echo: + print(line, file=sys.stderr) + + # -- profiles and files ------------------------------------------------- + + def profiles(self) -> dict[str, dict]: + out = {} + for path in sorted(self.paths.emulators.glob("*.yml")): + if path.name.startswith("_") or path.stem == "00_example": + continue + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if "emulator" in data: + out[path.stem] = data + return out + + @property + def db(self) -> dict: + if self._db is None: + self._db = json.loads(self.paths.db.read_text(encoding="utf-8")) + return self._db + + def local_file(self, entry: dict) -> Path | None: + """The collection's copy of an entry, by its declared hashes or its name.""" + from resolve.localfile import resolve_local_file + + hint = entry.get("path") if isinstance(entry.get("path"), str) else "" + # The database names files relative to the checkout it describes. + with working_directory(self.paths.root): + path, status = resolve_local_file(entry, self.db, dest_hint=hint or "") + if not path or status in ("not_found", "hash_mismatch"): + return None + local = Path(path) + local = local if local.is_absolute() else self.paths.root / local + return local if local.is_file() else None + + def variant_files(self, entry: dict, primary: Path) -> list[Path]: + """The .variants/ copies of an entry's file the collection holds.""" + names = [entry["name"], *(entry.get("aliases") or ())] + out = [] + index = self.db.get("indexes", {}).get("by_name", {}) + for name in names: + for sha1 in index.get(name, ()): + path = (self.db["files"].get(sha1) or {}).get("path", "") + if "/.variants/" in path: + local = self.paths.root / path + if local.is_file() and local.resolve() != primary.resolve() and local not in out: + out.append(local) + return out + + # -- guards --------------------------------------------------------------- + + def guard(self) -> None: + """Raise Pause when the pass must stop: budget spent, disk full, host busy.""" + if self.host.clock() >= self.deadline: + raise Pause("budget") + free = self.host.free_gb(self.paths.home if self.paths.home.exists() else self.paths.root) + 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 + + # -- one core_probe invocation ------------------------------------------- + + def probe(self, argv: list[str], log_name: str) -> ProbeResult: + """core_probe with retries for a crashing core. Never raises for the core's sake.""" + command = [sys.executable, str(self.probe_script), *argv] + log = self.paths.logs / dt.date.today().isoformat() / f"{log_name}.log" + log.parent.mkdir(parents=True, exist_ok=True) + 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 + 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()) + except subprocess.TimeoutExpired: + with log.open("a", encoding="utf-8") as handle: + handle.write(f"$ {' '.join(command)}\nkilled after {budget} s\n") + return ProbeResult(FAILED, reason="timeout", log=str(log)) + with log.open("a", encoding="utf-8") as handle: + handle.write(f"$ {' '.join(command)}\n# exit {proc.returncode}\n" + f"{proc.stderr[-20000:]}\n") + if proc.returncode == 0: + try: + 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: + # 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 + attempt += 1 + if proc.returncode == 2: + return ProbeResult(FAILED, reason=f"core_probe refused the run: " + f"{proc.stderr.strip()[-300:]}", log=str(log)) + if "TimeoutExpired" in proc.stderr or "timed out after" in proc.stderr: + return ProbeResult(FAILED, reason="timeout", log=str(log)) + self.log(f"{log_name}: attempt {attempt} exited {proc.returncode}") + return ProbeResult(FAILED, reason=f"crashed {CRASH_ATTEMPTS} times", log=str(log)) + + def probe_args(self, mode: str, core: Core, emulator: str, subject: str, content: Content | None, + load: Path | None) -> list[str]: + argv = [mode, "--core", str(core.path), "--record", str(self.paths.root), + "--emulator", emulator, "--subject", subject, + "--max-load", str(self.host.max_load), "--timeout", str(self.settings.probe_timeout), + "--work-dir", str(self.paths.root / "tmp" / "core_probe")] + if self.paths.oracle.is_file(): + argv += ["--oracle", str(self.paths.oracle)] + if not self.settings.allow_unsandboxed: + argv.append("--require-sandbox") + if core.artifact: + argv += ["--core-artifact", core.artifact] + if core.repo: + argv += ["--core-repo", core.repo] + if core.commit: + argv += ["--core-commit", core.commit] + if core.build_command: + argv += ["--build-command", core.build_command] + if content and load: + argv += ["--content", str(load), "--content-label", content.name] + return argv + + # -- the checks ------------------------------------------------------------- + + def check_key(self, core: Core, content: Content, check: str) -> str: + return f"{core.name}/{content.system}/{slug(content.name)}/{check}" + + def remember(self, emulator: str, key: str, result: ProbeResult, core: Core | None, + digest: str) -> None: + judged = None + if result.record and result.record["inputs"].get("content"): + judged = [result.record["inputs"]["content"]["sha1"], result.record["core"]["library_name"]] + entry = {"status": result.status, "at": now_iso(), "profile_digest": digest, + "core_sha256": core.sha256 if core else None, + "record_version": mr.RECORD_VERSION, "oracle_sha256": self.oracle_digest(judged)} + if judged: + entry["oracle_key"] = judged + if result.reason: + entry["reason"] = result.reason + if result.log: + entry["log"] = result.log + if result.record: + entry["record"] = result.record["id"] + if self.current: + self.current.records.append(result.record["id"]) + self.current.touched.add(mr.records_path(emulator)) + self.state["checks"].setdefault(emulator, {})[key] = entry + + def pending(self, emulator: str, key: str, reason: str, digest: str = "") -> None: + self.state["checks"].setdefault(emulator, {})[key] = { + "status": PENDING, "reason": reason, "at": now_iso(), "profile_digest": digest} + + def oracle_digest(self, key: list[str] | None) -> str: + """What a check's verdicts depend on in the oracle: the entries of its + content and core, else the whole file. Another core's references + never make a check run again.""" + if not key: + return self.oracle_sha + return mr.value_sha1(core_probe.oracle_for(self.oracle_data, *key)) + + def needed(self, emulator: str, key: str, core: Core, digest: str) -> bool: + previous = self.state["checks"].get(emulator, {}).get(key) + judged = (previous or {}).get("oracle_key") + if previous and not judged and previous.get("record"): + record = self.read_record(emulator, previous["record"]) or {} + if (record.get("inputs") or {}).get("content"): + judged = [record["inputs"]["content"]["sha1"], record["core"]["library_name"]] + previous["oracle_key"] = judged + # Judged against the entries the record kept, not the file it named. + kept = {k: v for k, v in (record["inputs"].get("oracle") or {}).items() + if k not in ("file", "sha256")} + previous["oracle_sha256"] = mr.value_sha1({"bios_patterns": [], **kept}) + return should_run(previous, core.sha256, digest, self.oracle_digest(judged)) + + def check(self, emulator: str, key: str, core: Core, digest: str, argv: list[str], + log_name: str) -> dict | None: + """The record of a check: run now when needed, else the one kept.""" + if not self.needed(emulator, key, core, digest): + previous = self.state["checks"].get(emulator, {}).get(key) or {} + return self.read_record(emulator, previous.get("record")) + result = self.probe(argv, log_name) + self.remember(emulator, key, result, core, digest) + return result.record + + def system_entries(self, profile: dict, system: str) -> list[tuple[int, dict]]: + from resolve.validation import filter_files_by_mode + + libretro = filter_files_by_mode(profile.get("files") or [], standalone=False) + keep = {id(e) for e in libretro} + return [(i, e) for i, e in enumerate(profile.get("files") or []) + if id(e) in keep and system in entry_systems(e, profile) and is_bios(e)] + + def boot_entry(self, entries: list[tuple[int, dict]], content: Content) -> tuple[int, dict] | None: + held = [(i, e) for i, e in entries if region_matches(e, content.region) and self.local_file(e)] + if content.boot_file: + named = [(i, e) for i, e in held + if content.boot_file in (e["name"], *(e.get("aliases") or ()))] + if named: + return named[0] + held.sort(key=lambda item: (item[1].get("priority", 1 << 30), item[0])) + return held[0] if held else None + + @staticmethod + def other_regions(entry: dict, staged: dict[str, tuple[int, dict, Path]], local: Path) -> list[Path]: + """Held dumps of the same system for regions this entry does not + serve, one per distinct file: the wrong-region variants.""" + mine = set(regions_of(entry)) + if not mine or "world" in mine: + return [] + out: dict[str, Path] = {} + for _, other, path in staged.values(): + theirs = set(regions_of(other)) + if theirs and "world" not in theirs and not theirs & mine and path.resolve() != local.resolve(): + out.setdefault(file_sha1(path), path) + return sorted(out.values(), key=lambda p: p.name)[:MAX_REGION_DUMPS] + + def run_unit_content(self, unit: Unit, core: Core, content: Content, digest: str) -> None: + emulator, profile = unit.emulator, unit.profile + entries = self.system_entries(profile, content.system) + staged: dict[str, tuple[int, dict, Path]] = {} + for index, entry in entries: + local = self.local_file(entry) + if local and entry_dest(entry) not in staged: + staged[entry_dest(entry)] = (index, entry, local) + tested = {dest: item for dest, item in staged.items() if region_matches(item[1], content.region)} + keys = self.content_keys(core, content, tested) + # The rules run on every pass, from the records kept when nothing + # needs to run again: a change of the table applies without a run. + try: + folder = self.store.get(content) + load = load_file(folder, content.load) + except Unavailable as exc: + for key in keys.values(): + if self.needed(emulator, key, core, digest): + self.pending(emulator, key, str(exc), digest) + return + frames = ["--frames", str(content.frames), "--frame-hash-every", str(content.frame_hash_every)] + trial = Trial(unit, core, content, load, frames, digest) + records = self.reference_runs(trial, keys, staged) + if not records: + return + files_record, none_record = records + full = rules.run_of(files_record, files_record["variants"][0]["label"]) + none = rules.run_of(none_record, none_record["variants"][0]["label"]) + self.log(f"{emulator}: {core.name} on {content.name}: full set {full.verdict}, " + f"no BIOS {none.verdict}") + + for dest, (index, entry, local) in sorted(tested.items()): + self.test_entry(trial, keys[f"negative:{dest}"], Held(index, entry, dest, local), staged, + files_record, none) + + boot = self.boot_entry(entries, content) + if boot and entry_dest(boot[1]) in tested: + index, entry = boot + self.follow_aliases(trial, index, entry, tested[entry_dest(entry)][2], none_record) + + if self.settings.bench and full.verdict == rules.BOOTS: + self.bench(trial, keys["bench"], boot) + + def content_keys(self, core: Core, content: Content, + tested: dict[str, tuple[int, dict, Path]]) -> dict[str, str]: + keys = {"files": self.check_key(core, content, "files"), + "none": self.check_key(core, content, "none")} + for dest in tested: + keys[f"negative:{dest}"] = self.check_key(core, content, f"negative:{dest}") + if self.settings.bench: + keys["bench"] = self.check_key(core, content, "bench") + return keys + + def reference_runs(self, trial: Trial, keys: dict[str, str], + staged: dict[str, tuple[int, dict, Path]]) -> tuple[dict, dict] | None: + """The full set and no BIOS at all, or None while either is missing.""" + core, emulator, content, load = trial.core, trial.unit.emulator, trial.content, trial.load + repeat = ["--repeat", str(self.settings.check_repeat)] + stem = f"{core.name}-{slug(content.name)}" + + # files: every declared file the collection holds, at its place. + argv = self.probe_args("run", core, emulator, slug(f"files-{stem}"), content, load) + trial.frames + repeat + for dest, (_, _, local) in sorted(staged.items()): + argv += ["--system-file", f"{dest}={local}"] + files_record = self.check(emulator, keys["files"], core, trial.digest, argv, f"{emulator}-{stem}-files") + # none: no BIOS at all. + argv = self.probe_args("run", core, emulator, slug(f"none-{stem}"), content, load) + trial.frames + repeat + none_record = self.check(emulator, keys["none"], core, trial.digest, argv, f"{emulator}-{stem}-none") + if not files_record or not none_record: + return None + return files_record, none_record + + def test_entry(self, trial: Trial, key: str, held: Held, staged: dict[str, tuple[int, dict, Path]], + files_record: dict, none: rules.Run) -> None: + """One declared file alone and replaced, then what its runs settle.""" + emulator, content, entry = trial.unit.emulator, trial.content, held.entry + record = self.negative(trial, key, held, staged) + if not record: + return + labels = [v["label"] for v in record["variants"]] + present = rules.run_of(record, labels[0]) + zeros, half = (rules.run_of(record, label) for label in labels[1:3]) + for label in labels[3:]: + self.log(f"{emulator}: {rules.rule_region(rules.run_of(record, label), present, entry, content.region)}") + if held.dest in self.opened(files_record, 0) or held.dest in self.opened(record, 0): + verdicts = rules.rule_need(none, present, entry, rules.read(none, present, zeros, half)) + validation = rules.rule_validation(zeros, half, none, present, entry) + if validation: + verdicts.append(validation) + self.settle(emulator, content, trial.core, held.index, entry, verdicts) + variants = self.variant_files(entry, held.local) + if variants: + self.run_variants(trial, held, variants) + else: + self.moved(trial, held, files_record, record) + + def bench(self, trial: Trial, key: str, boot: tuple[int, dict] | None) -> None: + core, emulator, content = trial.core, trial.unit.emulator, trial.content + stem = f"{core.name}-{slug(content.name)}" + argv = self.probe_args("bench", core, emulator, slug(f"bench-{stem}"), content, trial.load) + argv += ["--warmup", str(self.settings.bench_warmup), "--frames", + str(self.settings.bench_frames), "--repeat", str(self.settings.bench_repeat), + "--no-trace"] + if boot: + argv += ["--system-file", f"{entry_dest(boot[1])}={self.local_file(boot[1])}"] + self.check(emulator, key, core, trial.digest, argv, f"{emulator}-{stem}-bench") + + def negative(self, trial: Trial, key: str, held: Held, + staged: dict[str, tuple[int, dict, Path]]) -> dict | None: + """The file alone, then wrong files under its name: zeros of its + size, its first half, and other regions' dumps.""" + core, content, entry, dest, local = trial.core, trial.content, held.entry, held.dest, held.local + unit = trial.unit + stem = f"{core.name}-{slug(content.name)}" + size = local.stat().st_size + others = self.other_regions(entry, staged, local) + argv = self.probe_args("check", core, unit.emulator, slug(f"negative-{entry['name']}-{stem}"), + content, trial.load) + trial.frames + argv += ["--vary", f"{dest}={local}", "--vary", f"{dest}=@zeros:{size}", + "--vary", f"{dest}=@head:{size // 2}:{local}"] + for other in others: + argv += ["--vary", f"{dest}={other}"] + regions = f", then {', '.join(p.name for p in others)} staged under its name" if others else "" + argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat), + "--claim", (f"{core.name} boots {content.name} with {entry['name']} alone and " + f"refuses a wrong file under its name"), + "--method", (f"{entry['name']} alone as {dest}, then {size} zero bytes and its " + f"first {size // 2} bytes{regions}, nothing else staged. Each run " + f"{self.settings.check_repeat} times from a fresh process for " + f"{content.frames} frames with no button pressed, every " + f"{content.frame_hash_every}th frame hashed. The boot oracle judges " + f"each variant against the reference frames of {content.name}.")] + return self.check(unit.emulator, key, core, trial.digest, argv, f"{unit.emulator}-{stem}-negative") + + def moved(self, trial: Trial, held: Held, files_record: dict, alone: dict) -> None: + """A file the core opened neither in the full set nor alone: where + else it looked for a file of that name, else flagged.""" + unit, core, content = trial.unit, trial.core, trial.content + index, entry, dest = held.index, held.entry, held.dest + probed = [p for record in (files_record, alone) for r in record["variants"][0]["repetitions"] + for p in r.get("files_probed_absent") or ()] + others = [p for p in dict.fromkeys(probed) if p != dest + and p.rsplit("/", 1)[-1].casefold() == dest.rsplit("/", 1)[-1].casefold()] + for candidate in others[:MAX_ALIAS_CANDIDATES]: + found = self.follow_up(trial, entry, held.local, candidate, f"path:{entry['name']}:{candidate}") + if found and candidate in self.opened(found, 0): + verdict = rules.rule_path(entry, dest, rules.Opened(candidate, found["id"])) + if verdict: + self.settle(unit.emulator, content, core, index, entry, [verdict]) + return + verdict = rules.rule_never_opened(entry, [files_record["id"], alone["id"]], content.name) + self.settle(unit.emulator, content, core, index, entry, [verdict]) + + def read_record(self, emulator: str, rid: str | None) -> dict | None: + """A record by its id, or the record that supersedes it: a run + judged again offline is read as judged last.""" + if not rid: + return None + path = self.paths.root / mr.records_path(emulator) + if not path.is_file(): + return None + records = [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines()] + by_id = {r["id"]: r for r in records} + successor = {r["supersedes"]: r["id"] for r in records if r.get("supersedes")} + seen = set() + while rid in successor and rid not in seen: + seen.add(rid) + rid = successor[rid] + return by_id.get(rid) + + def judged(self, emulator: str, rid: str) -> bool: + """True for a record the boot oracle judged: only those prove a field.""" + record = self.read_record(emulator, rid) + return record is not None and record.get("record_version", 0) >= 4 + + @staticmethod + def opened(record: dict, position: int) -> set[str]: + out: set[str] = set() + for rep in record["variants"][position]["repetitions"]: + out |= {item["path"] for item in rep.get("files_opened") or ()} + return out + + def follow_up(self, trial: Trial, entry: dict, local: Path, dest: str, check: str) -> dict | None: + """The file staged at dest alone: does the core open it there.""" + unit, core, content = trial.unit, trial.core, trial.content + stem = f"{core.name}-{slug(content.name)}" + argv = self.probe_args("run", core, unit.emulator, slug(f"{check}-{stem}"), content, trial.load) + argv += trial.frames + ["--system-file", f"{dest}={local}"] + return self.check(unit.emulator, self.check_key(core, content, check), core, trial.digest, argv, + f"{unit.emulator}-{stem}-{slug(check)}") + + def follow_aliases(self, trial: Trial, index: int, entry: dict, local: Path, none_record: dict) -> None: + """Names the core looked for, with no BIOS, that no entry declares.""" + unit, core, content = trial.unit, trial.core, trial.content + declared = {e["name"] for e in unit.profile.get("files") or ()} + declared |= {a for e in unit.profile.get("files") or () for a in e.get("aliases") or ()} + suffix = Path(entry["name"]).suffix.casefold() + dest = entry_dest(entry) + folder = dest.rsplit("/", 1)[0] if "/" in dest else "" + probed: list[str] = [] + for rep in none_record["variants"][0]["repetitions"]: + for path in rep.get("files_probed_absent") or (): + name = path.rsplit("/", 1)[-1] + where = path.rsplit("/", 1)[0] if "/" in path else "" + if (where == folder and name not in declared and Path(name).suffix.casefold() == suffix + and path not in probed): + probed.append(path) + for candidate in probed[:MAX_ALIAS_CANDIDATES]: + found = self.follow_up(trial, entry, local, candidate, + f"alias:{entry['name']}:{candidate.rsplit('/', 1)[-1]}") + if found and candidate in self.opened(found, 0): + verdict = rules.rule_alias(self.reload_entry(unit, index), rules.Opened(candidate, found["id"])) + if verdict: + self.settle(unit.emulator, content, core, index, self.reload_entry(unit, index), [verdict]) + + def run_variants(self, trial: Trial, held: Held, variants: list[Path]) -> None: + unit, core, content, digest = trial.unit, trial.core, trial.content, trial.digest + index, entry, dest = held.index, held.entry, held.dest + key = self.check_key(core, content, f"variants:{entry['name']}") + if not self.needed(unit.emulator, key, core, digest): + return + stem = f"{core.name}-{slug(content.name)}" + argv = self.probe_args("check", core, unit.emulator, slug(f"variants-{entry['name']}-{stem}"), + content, trial.load) + trial.frames + for path in [held.local, *variants]: + argv += ["--vary", f"{dest}={path}"] + argv += ["--observable", "frame_hashes", "--repeat", str(self.settings.check_repeat), + "--claim", f"every copy of {entry['name']} boots {content.name} on {core.name}", + "--method", (f"Each copy the collection holds staged alone as {dest}, each run " + f"{self.settings.check_repeat} times for {content.frames} frames. The " + f"boot oracle judges each copy.")] + record = self.check(unit.emulator, key, core, digest, argv, f"{unit.emulator}-{stem}-variants") + if record: + verdict = rules.rule_variants([rules.run_of(record, v["label"]) for v in record["variants"]], + entry) + if verdict: + self.settle(unit.emulator, content, core, index, entry, [verdict]) + + # -- verdicts ----------------------------------------------------------------- + + def reload_entry(self, unit: Unit, index: int) -> dict: + path = self.paths.emulators / f"{unit.emulator}.yml" + unit.profile = yaml.safe_load(path.read_text(encoding="utf-8")) + return unit.profile["files"][index] + + def settle(self, emulator: str, content: Content, core: Core, index: int, entry: dict, + verdicts: Sequence[rules.Verdict]) -> None: + """Apply what the table settles, queue the rest, resolve what now agrees.""" + path = self.paths.emulators / f"{emulator}.yml" + for verdict in verdicts: + fresh = (yaml.safe_load(path.read_text(encoding="utf-8")).get("files") or [])[index] + if fresh.get("name") != entry.get("name"): + self.log(f"{emulator}: files[{index}] is no longer {entry.get('name')}, nothing applied") + return + says = rules.current(fresh, verdict.field) if verdict.field in rules.SETTLED_FIELDS \ + else None + agrees = verdict.field in rules.SETTLED_FIELDS and rules.agrees(fresh, verdict) + if verdict.apply: + updates: dict[str, object] = {} + if not agrees or (verdict.field not in fresh and verdict.field != "validation"): + updates[verdict.field] = verdict.value + evidence = rules.merge_evidence(fresh.get("evidence"), verdict, + keep=lambda rid: self.judged(emulator, rid)) + if evidence != fresh.get("evidence"): + updates["evidence"] = evidence + if updates: + try: + changed = write_fields(path, index, updates) + except ProfileEditError as exc: + self.finding(emulator, content, core, fresh, verdict, "open", says, + extra=f". Not written: {exc}") + continue + if changed and self.current: + self.current.touched.add(path.relative_to(self.paths.root).as_posix()) + if agrees: + self.resolve(emulator, content, core, fresh, verdict, says) + else: + self.finding(emulator, content, core, fresh, verdict, "applied", says) + continue + if verdict.rule == "never_opened": + self.finding(emulator, content, core, fresh, verdict, "flagged", None) + elif agrees: + self.resolve(emulator, content, core, fresh, verdict, says) + else: + self.finding(emulator, content, core, fresh, verdict, "open", says) + + def finding_key(self, emulator: str, content: Content, entry: dict, verdict: rules.Verdict) -> str: + return f"{emulator}/{content.system}/{entry['name']}/{verdict.field}" + + def latest_findings(self) -> dict[str, dict]: + latest: dict[str, dict] = {} + for line in mr.read_campaign(self.paths.root, mr.FINDINGS): + latest[line["key"]] = line + return latest + + def finding(self, emulator: str, content: Content, core: Core, entry: dict, + verdict: rules.Verdict, status: str, says: object, extra: str = "") -> None: + key = self.finding_key(emulator, content, entry, verdict) + previous = self.latest_findings().get(key) + if previous and previous["status"] == status and previous["rule"] == verdict.rule \ + and previous["run_shows"] == verdict.value and previous["profile_says"] == says \ + and previous["evidence"] == list(verdict.evidence): + return + # A review that read the code and kept the profile stands while the + # runs keep showing the same thing. + if previous and previous["status"] == "rejected" and status == "open" \ + and previous["rule"] == verdict.rule and previous["run_shows"] == verdict.value \ + and previous["profile_says"] == says: + return + line = mr.seal_line({ + "schema_version": 1, "found_at": now_iso(), "key": key, "emulator": emulator, + "system": content.system, "file": entry["name"], "field": verdict.field, + "status": status, "rule": verdict.rule, "profile_says": says, "run_shows": verdict.value, + "statement": verdict.statement + extra, "evidence": list(verdict.evidence), + "core": {"file": core.path.name, "sha256": core.sha256, + "library_version": self.library_version(emulator, verdict.evidence)}, + "content": content.name, + }, "found_at") + path = self.paths.root / mr.records_path(mr.FINDINGS) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(mr.line_text(line) + "\n") + if self.current: + self.current.findings[status] = self.current.findings.get(status, 0) + 1 + self.current.touched.add(mr.records_path(mr.FINDINGS)) + self.log(f"finding {status}: {key}: {verdict.statement}") + + def resolve(self, emulator: str, content: Content, core: Core, entry: dict, + verdict: rules.Verdict, says: object) -> None: + previous = self.latest_findings().get(self.finding_key(emulator, content, entry, verdict)) + if previous and previous["status"] in ("open", "flagged"): + self.finding(emulator, content, core, entry, verdict, "resolved", says) + + def library_version(self, emulator: str, ids: Sequence[str]) -> str | None: + for rid in ids: + record = self.read_record(emulator, rid) + if record: + return record["core"].get("library_version") + return None + + # -- reference frames ----------------------------------------------------------- + + def references(self, only: set[str], system: str | None, png_dir: Path) -> list[dict]: + """The full set run once per core and content, frames written as PNG, + and the screens that stay on long enough to serve as references.""" + self.deadline = self.host.clock() + self.settings.budget + listed = [] + for unit in self.units(only, system): + contents = self.unit_contents(unit, system) + if unit.pending or not contents: + continue + try: + cores = self.unit_cores(unit.emulator, unit.profile, unit.buildbot_only) + except Unavailable as exc: + self.log(f"{unit.emulator}: {exc}") + continue + for core in cores: + for content in contents: + self.guard() + self.store.hold(content, "references") + try: + load = load_file(self.store.get(content), content.load) + except Unavailable as exc: + self.log(f"{unit.emulator}: {exc}") + continue + stem = f"{core.name}-{slug(content.name)}" + target = png_dir / slug(core.name) / slug(content.name) + shutil.rmtree(target, ignore_errors=True) + argv = self.probe_args("run", core, unit.emulator, slug(f"references-{stem}"), + content, load) + argv += ["--frames", str(content.frames), "--frame-hash-every", + str(content.frame_hash_every), "--repeat", str(self.settings.check_repeat), + "--png-dir", str(target)] + for _, entry in self.system_entries(unit.profile, content.system): + local = self.local_file(entry) + if local and f"{entry_dest(entry)}=" not in " ".join(argv): + argv += ["--system-file", f"{entry_dest(entry)}={local}"] + result = self.probe(argv, f"{unit.emulator}-{stem}-references") + self.store.release(content, "references") + if not result.record: + self.log(f"{unit.emulator}: references of {content.name}: {result.reason}") + continue + record = result.record + listed.append({ + "emulator": unit.emulator, "core": core.name, + "library_name": record["core"]["library_name"], "content": content.name, + "content_sha1": record["inputs"]["content"]["sha1"], "record": record["id"], + "verdict": record["variants"][0]["verdict"], + "png_dir": str(target / record["variants"][0]["label"]), + "candidates": reference_candidates(record), + }) + save_state(self.paths.state, self.state) + return listed + + # -- the pass ----------------------------------------------------------------- + + def units(self, only: set[str], system: str | None) -> list[Unit]: + out = [] + for emulator, profile in sorted(self.profiles().items()): + cores = {str(c) for c in profile.get("cores") or ()} + if only and emulator not in only and not (cores & only): + continue + systems = set(profile.get("systems") or ()) + if system and system not in systems: + continue + kind = str(profile.get("type") or "") + if kind in ("alias", "launcher", "test"): + continue + if "libretro" in kind or kind in ("game", "utility"): + out.append(Unit(emulator, profile, buildbot_only="libretro" not in kind)) + continue + out.append(Unit(emulator, profile, pending="standalone")) + return out + + def unit_contents(self, unit: Unit, system: str | None) -> list[Content]: + systems = [s for s in unit.profile.get("systems") or () if not system or s == system] + return [c for s in systems for c in self.content.get(s, ())] + + def run(self, only: set[str], system: str | None, dry_run: bool = False, + commit_every: int = 0, commit: bool = False) -> Pass: + self.deadline = self.host.clock() + self.settings.budget + current = self.current = Pass(started=now_iso()) + units = self.units(only, system) + if dry_run: + self.describe(units, system) + return current + isolation = core_probe.sandbox_argv([])[1] + if isolation != core_probe.SANDBOX and not self.settings.allow_unsandboxed: + # Fail closed: no core and no build runs outside the sandbox. + current.result = "refused" + current.detail = (f"no sandbox for third-party code ({isolation}). Install bubblewrap, " + f"or pass --allow-unsandboxed") + self.log(f"pass refused: {current.detail}") + self.write_run_line(current) + save_state(self.paths.state, self.state) + return current + for unit in units: + for content in self.unit_contents(unit, system): + self.store.hold(content, unit.emulator) + done_units = 0 + try: + for unit in units: + self.run_unit(unit, system) + done_units += 1 + save_state(self.paths.state, self.state) + if commit and commit_every and done_units % commit_every == 0: + self.commit_batch() + except Pause as exc: + current.result = "budget" if str(exc) == "budget" else "paused" + current.detail = str(exc) + self.log(f"pass paused: {exc}") + except KeyboardInterrupt: + current.result, current.detail = "stopped", "interrupted" + finally: + for unit in units: + for content in self.unit_contents(unit, system): + self.store.release(content, unit.emulator) + self.prune_logs() + self.write_run_line(current) + save_state(self.paths.state, self.state) + if commit: + self.commit_batch() + return current + + def run_unit(self, unit: Unit, system: str | None) -> None: + emulator, profile = unit.emulator, unit.profile + digest = profile_digest(profile) + contents = self.unit_contents(unit, system) + systems = [s for s in profile.get("systems") or () if not system or s == system] + if unit.pending: + for s in systems: + self.pending(emulator, f"*/{s}/*", unit.pending, digest) + return + if not contents: + for s in systems: + self.pending(emulator, f"*/{s}/*", f"content: no test content listed for {s}", digest) + return + try: + cores = self.unit_cores(emulator, profile, unit.buildbot_only) + except Unavailable as exc: + for s in systems: + self.pending(emulator, f"*/{s}/*", str(exc), digest) + self.log(f"{emulator}: {exc}") + return + for s in systems: + self.state["checks"].setdefault(emulator, {}).pop(f"*/{s}/*", None) + for core in cores: + self.log(f"{emulator}: core {core.name} {core.sha256[:12]}") + for content in contents: + self.guard() + self.run_unit_content(Unit(emulator, profile, core.name), core, content, digest) + for content in contents: + self.store.release(content, emulator) + self.state["emulators"][emulator] = {"profile_digest": profile_digest( + yaml.safe_load((self.paths.emulators / f"{emulator}.yml").read_text(encoding="utf-8"))), + "at": now_iso()} + # The campaign's own edits do not make its checks run again. + new_digest = self.state["emulators"][emulator]["profile_digest"] + for entry in self.state["checks"].get(emulator, {}).values(): + if entry.get("profile_digest") == digest: + entry["profile_digest"] = new_digest + + def unit_cores(self, emulator: str, profile: dict, buildbot_only: bool = False) -> list[Core]: + names = self.cores.names(profile) + if names: + return [self.cores.nightly(name, profile) for name in names] + if buildbot_only: + raise Unavailable("standalone: no libretro core on the buildbot") + return [self.cores.build(emulator, profile)] + + def describe(self, units: list[Unit], system: str | None) -> None: + for unit in units: + contents = self.unit_contents(unit, system) + if unit.pending: + print(f"{unit.emulator}: pending, {unit.pending}") + elif not contents: + print(f"{unit.emulator}: pending, no test content for " + f"{', '.join(unit.profile.get('systems') or ())}") + else: + cores = sorted({str(c) for c in unit.profile.get("cores") or ()}) + print(f"{unit.emulator}: cores {', '.join(cores)} on " + f"{', '.join(c.name for c in contents)}") + + def counts(self) -> tuple[dict[str, int], dict[str, int], list[dict]]: + counts = {DONE: 0, FAILED: 0, PENDING: 0} + reasons: dict[str, int] = {} + failed = [] + for emulator, checks in sorted(self.state["checks"].items()): + for key, entry in sorted(checks.items()): + status = entry.get("status", PENDING) + counts[status] = counts.get(status, 0) + 1 + if status == PENDING: + reason = reason_class(entry.get("reason", "")) + reasons[reason] = reasons.get(reason, 0) + 1 + elif status == FAILED: + failed.append({"emulator": emulator, "check": key, "reason": entry.get("reason", "")}) + return counts, reasons, failed + + def write_run_line(self, current: Pass) -> None: + counts, reasons, failed = self.counts() + line = mr.seal_line({ + "schema_version": 1, "started_at": current.started, "ended_at": now_iso(), + "result": current.result, "detail": current.detail, "counts": counts, + "pending_reasons": reasons, "failed": failed, "records": current.records, + "findings": dict(sorted(current.findings.items())), + }, "started_at") + path = self.paths.root / mr.records_path(mr.CAMPAIGN_RUNS) + path.parent.mkdir(parents=True, exist_ok=True) + with path.open("a", encoding="utf-8") as handle: + handle.write(mr.line_text(line) + "\n") + current.touched.add(mr.records_path(mr.CAMPAIGN_RUNS)) + self.state["last_run"] = {k: line[k] for k in ("id", "started_at", "ended_at", "result", "detail")} + + def prune_logs(self) -> None: + limit = time.time() - LOG_DAYS * 86400 + for path in self.paths.logs.rglob("*.log") if self.paths.logs.is_dir() else (): + if path.stat().st_mtime < limit: + path.unlink() + + # -- commits (direct runs, autorun commits by its own rules) ------------------- + + def plan_commits(self, dirty_at_start: set[str]) -> list[tuple[str, list[str]]]: + """(subject, paths) of each commit: the records, then one per profile.""" + touched = sorted(self.current.touched if self.current else ()) + records = [p for p in touched if p.startswith(f"{mr.RECORDS_DIR}/") and p not in dirty_at_start] + plan = [] + if records: + plan.append(("chore: add campaign measurements", records)) + for path in touched: + if path.startswith("emulators/") and path not in dirty_at_start: + subject = f"chore: apply tested fields to {Path(path).stem}" + if len(subject) > 50: + subject = "chore: apply tested profile fields" + plan.append((subject, [path])) + return plan + + def commit_batch(self, dry_run: bool = False) -> list[str]: + plan = self.plan_commits(self.dirty_at_start) + if dry_run or not plan: + for subject, paths in plan: + print(f"would commit {subject!r}: {', '.join(paths)}") + return [] + if gate(self.paths.root, [Path(p).stem for _, ps in plan for p in ps if p.startswith("emulators/")], + self.host) != 0: + self.log("gate failed, nothing committed") + return [] + made = [] + for subject, paths in plan: + problems = autorun.check_subject(subject) + if problems: + raise ValueError(f"{subject!r}: {', '.join(problems)}") + made.append(autorun.commit_paths(self.paths.root, paths, autorun.CommitRule(subject, tuple(paths)))) + if self.current: + self.current.touched.clear() + return made + + +def reference_candidates(record: dict, min_samples: int = 3) -> list[dict]: + """Screens of a record's first variant that are not one colour and stay + on for at least min_samples consecutive samples in every repetition: + what a reviewer looks at to choose reference frames.""" + found: list[dict[str, tuple[int, int]]] = [] + for rep in record["variants"][0]["repetitions"]: + observables = rep.get("observables") or {} + uniform = set(observables.get("uniform_frames") or ()) + runs: dict[str, tuple[int, int]] = {} + previous, start, length = None, 0, 0 + for frame, digest in [*(observables.get("frame_hashes") or ()), (None, None)]: + if digest == previous: + length += 1 + continue + if previous and previous not in uniform and length >= min_samples: + first, longest = runs.get(previous, (start, 0)) + runs[previous] = (min(first, start), max(longest, length)) + previous, start, length = digest, frame, 1 + found.append(runs) + common = set(found[0]) if found else set() + for runs in found[1:]: + common &= set(runs) + return sorted(({"sha1": digest, "first_frame": found[0][digest][0], "samples": found[0][digest][1]} + for digest in common), key=lambda item: item["first_frame"]) + + +def reason_class(reason: str) -> str: + """A pending reason without its detail, to count them.""" + head = reason.split(":", 1)[0].strip() if ":" in reason else reason + return head or "unknown" diff --git a/scripts/probes/content.py b/scripts/probes/content.py new file mode 100644 index 000000000..cfe04d2e3 --- /dev/null +++ b/scripts/probes/content.py @@ -0,0 +1,206 @@ +"""The test content of each system, fetched through romfetch and checked by hash.""" + +from __future__ import annotations + +import contextlib +import json +import os +import shutil +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING + +import yaml + +from core.statefile import now_iso +from probes.host import Unavailable, child_env, file_sha1 + +if TYPE_CHECKING: + from probes.campaign import Campaign + + +ROMFETCH_ENV = "RETROBIOS_ROMFETCH" + + +ROMFETCH_TRANSIENT = 3 + + +# -------------------------------------------------------------------------- +# Content: what each system is tested with, and where it comes from +# -------------------------------------------------------------------------- + +@dataclass(frozen=True) +class Content: + system: str + romfetch_system: str + name: str + catalog: str + reason: str + region: str | None + load: str + frames: int + frame_hash_every: int + pinned: bool + boot_file: str | None + + @property + def key(self) -> str: + return f"{self.romfetch_system}/{self.name}" + + +def load_content(path: Path) -> dict[str, list[Content]]: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + out: dict[str, list[Content]] = {} + for system, spec in (data.get("systems") or {}).items(): + for item in spec.get("content") or (): + out.setdefault(system, []).append(Content( + system=system, romfetch_system=str(spec["romfetch"]), name=str(item["name"]), + catalog=str(item["catalog"]), reason=str(item["reason"]).strip(), + region=item.get("region"), load=str(item.get("load") or ""), + frames=int(item.get("frames", 3600)), + frame_hash_every=int(item.get("frame_hash_every", 10)), + pinned=bool(item.get("pinned", False)), boot_file=spec.get("boot_file"), + )) + return out + + +def load_file(folder: Path, load: str) -> Path: + """The file handed to the core.""" + if load == "cue": + cues = sorted(folder.glob("*.cue")) + if len(cues) != 1: + raise Unavailable(f"{folder.name}: {len(cues)} .cue files, one expected") + return cues[0] + if load: + return folder / load + files = [p for p in sorted(folder.iterdir()) if p.is_file() and p.name != "identity.json"] + if len(files) != 1: + raise Unavailable(f"{folder.name}: {len(files)} files, name one with load:") + return files[0] + + +def verify_identity(folder: Path) -> dict: + """The identity.json romfetch wrote, each listed file hashed again.""" + try: + identity = json.loads((folder / "identity.json").read_text(encoding="utf-8")) + except FileNotFoundError as exc: + raise Unavailable(f"{folder}: no identity.json") from exc + if identity.get("status") != "verified": + raise Unavailable(f"{folder.name}: identity status {identity.get('status')!r}") + for item in identity.get("files") or (): + path = folder / item["name"] + if not path.is_file() or path.stat().st_size != item["size"] or file_sha1(path) != item["sha1"]: + raise Unavailable(f"{folder.name}: {item['name']} does not match its identity") + return identity + + +def folder_size(folder: Path) -> int: + return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file()) + + +class ContentStore: + """Content on disk, its users counted, the least recently used evicted + past the cap. Only what the campaign fetched is ever deleted, and never + a pinned entry.""" + + def __init__(self, campaign: Campaign) -> None: + self.c = campaign + self.state: dict = campaign.state["content"] + self.refs: dict[str, set[str]] = {} + self.verified: set[str] = set() + + def folder(self, content: Content) -> Path: + return self.c.paths.content / content.romfetch_system / content.name + + def hold(self, content: Content, user: str) -> None: + self.refs.setdefault(content.key, set()).add(user) + + def get(self, content: Content) -> Path: + """The folder of the content, fetched when absent. Unavailable when not.""" + folder = self.folder(content) + entry = self.state.setdefault(content.key, {"fetched_by_campaign": False}) + entry["pinned"] = content.pinned + if not (folder / "identity.json").is_file(): + self.evict(keep={content.key}) + self.fetch(content) + entry["fetched_by_campaign"] = True + if content.key not in self.verified: + identity = verify_identity(folder) + entry["identity"] = {"catalog": identity.get("catalog"), "dat": identity.get("dat"), + "entry": identity.get("entry")} + self.verified.add(content.key) + entry["size"] = folder_size(folder) + entry["last_used"] = now_iso() + return folder + + def romfetch(self) -> str | None: + configured = self.c.settings.romfetch or os.environ.get(ROMFETCH_ENV, "") + if configured: + return configured if Path(configured).is_file() or shutil.which(configured) else None + return shutil.which("romfetch") + + def fetch(self, content: Content) -> None: + command = self.romfetch() + if not command: + raise Unavailable(f"content: romfetch not found, {content.catalog} entry {content.name!r}") + if not self.c.settings.network: + raise Unavailable(f"content: offline, {content.catalog} entry {content.name!r}") + argv = [command, "get", content.romfetch_system, content.name, "--json", "-q", + "--content-dir", str(self.c.paths.content)] + for attempt, delay in enumerate((*self.c.settings.delays, None)): + proc = self.c.host.run(argv, capture_output=True, text=True, check=False, + timeout=6 * 3600, env=child_env(romfetch=True)) + if proc.returncode == 0: + self.c.log(f"romfetch {content.name}: {proc.stdout.strip()[:300]}") + return + code = "unknown" + with contextlib.suppress(ValueError, AttributeError): + code = json.loads(proc.stdout)["error"]["code"] + if proc.returncode != ROMFETCH_TRANSIENT or delay is None: + raise Unavailable(f"content: romfetch exit {proc.returncode} ({code}) " + f"for {content.name!r}") + self.c.log(f"romfetch {content.name}: exit {proc.returncode} ({code}), " + f"retry {attempt + 1} in {delay}s") + self.c.host.sleep(delay) + + def release(self, content: Content, user: str) -> None: + users = self.refs.get(content.key, set()) + users.discard(user) + if not users: + self.drop(content.key) + + def deletable(self, key: str) -> bool: + entry = self.state.get(key) or {} + return bool(entry.get("fetched_by_campaign")) and not entry.get("pinned") + + def drop(self, key: str) -> bool: + if not self.deletable(key) or self.refs.get(key): + return False + folder = self.c.paths.content / key + if folder.is_dir(): + shutil.rmtree(folder) + self.c.log(f"content {key}: deleted, no check left needs it") + self.state.pop(key, None) + self.verified.discard(key) + return True + + def evict(self, keep: set[str]) -> list[str]: + """Least recently used first, until the campaign's content fits the cap.""" + cap = self.c.settings.cache_cap_gb * 1024 ** 3 + held = sorted((entry.get("last_used", ""), key) for key, entry in self.state.items() + if self.deletable(key) and key not in keep) + total = sum(entry.get("size", 0) for key, entry in self.state.items() if self.deletable(key)) + evicted = [] + for _, key in held: + if total <= cap: + break + size = self.state[key].get("size", 0) + folder = self.c.paths.content / key + if folder.is_dir(): + shutil.rmtree(folder) + self.state.pop(key, None) + self.verified.discard(key) + total -= size + evicted.append(key) + self.c.log(f"content {key}: evicted, the cache is over {self.c.settings.cache_cap_gb} GB") + return evicted diff --git a/scripts/probes/cores.py b/scripts/probes/cores.py new file mode 100644 index 000000000..dd0c6eebd --- /dev/null +++ b/scripts/probes/cores.py @@ -0,0 +1,346 @@ +"""Where a campaign's cores come from: the buildbot nightly, else a sandboxed build of the profile's pinned commit.""" + +from __future__ import annotations + +import io +import os +import re +import shutil +import stat +import subprocess +import tarfile +import urllib.error +import urllib.request +import zipfile +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import TYPE_CHECKING, TypeVar + +import core_probe +from core.statefile import now_iso +from probes.host import Unavailable, child_env, file_sha256, run_group, slug + +if TYPE_CHECKING: + from probes.campaign import Campaign + + +T = TypeVar("T") + + +BUILDBOT = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/" + + +BUILD_TIMEOUT = 3600 + + +# Host-side git on a third-party project. It only ever touches bare mirrors +# this campaign created: no working tree, never bound into a sandbox. No user +# or system config is read, https is the only transport, and the overrides +# blank every hook, filter, proxy and ssh command a config could name. +GIT_SAFE = ( + "-c", "core.hooksPath=/dev/null", "-c", "core.fsmonitor=false", + "-c", "core.sshCommand=", "-c", "core.gitProxy=", "-c", "core.askPass=", + "-c", "credential.helper=", "-c", "protocol.allow=never", "-c", "protocol.https.allow=always", + "-c", "filter.lfs.smudge=", "-c", "filter.lfs.clean=", "-c", "filter.lfs.process=", + "-c", "filter.lfs.required=false", "-c", "core.attributesFile=/dev/null", +) +MIRROR_URL = re.compile(r"^https://[A-Za-z0-9.-]+(?::\d+)?/[A-Za-z0-9._~/+-]+$") + + +def host_git(*args: str) -> list[str]: + return ["git", *GIT_SAFE, *args] + + +def git_env() -> dict[str, str]: + env = child_env() + env.update(GIT_CONFIG_NOSYSTEM="1", GIT_CONFIG_GLOBAL=os.devnull, GIT_TERMINAL_PROMPT="0", + GIT_ALLOW_PROTOCOL="https", GIT_ATTR_NOSYSTEM="1") + return env + + +def blank_filters(repo: Path) -> list[str]: + """-c overrides emptying every filter driver the repository's config, + includes followed, defines: git archive runs smudge filters.""" + config = repo / "config" + if not config.is_file(): + return [] + listing = run_group(["git", "config", "--file", str(config), "--includes", "--name-only", + "--get-regexp", r"^filter\."], capture_output=True, env=git_env(), + timeout=60).stdout.decode("utf-8", "replace") + drivers = sorted({line.rsplit(".", 1)[0] for line in listing.splitlines() if line.count(".") >= 2}) + out = [] + for driver in drivers: + for key in ("smudge", "clean", "process"): + out += ["-c", f"{driver}.{key}="] + out += ["-c", f"{driver}.required=false"] + return out + + +def git_out(*args: str, timeout: int = 1800) -> bytes: + extra = blank_filters(Path(args[1])) if len(args) > 1 and args[0] == "-C" else [] + return run_group(["git", *GIT_SAFE, *extra, *args], capture_output=True, check=True, + env=git_env(), timeout=timeout).stdout + + +def submodule_url(base: str, url: str) -> str: + """A .gitmodules URL, relative ones read against the parent's URL.""" + if url.startswith(("./", "../")): + parts = base.rstrip("/").removesuffix(".git").split("/") + for piece in url.split("/"): + if piece == "..": + parts.pop() + elif piece not in (".", ""): + parts.append(piece) + url = "/".join(parts) + return url + + +def extract_tar(blob: bytes, target: Path) -> None: + """A git archive unpacked into target: no absolute path, no .., no link + that leaves target.""" + target.mkdir(parents=True, exist_ok=True) + with tarfile.open(fileobj=io.BytesIO(blob)) as handle: + if hasattr(tarfile, "data_filter"): + handle.extractall(target, filter="data") + return + for member in handle.getmembers(): + name = Path(member.name) + link = Path(member.linkname) + if name.is_absolute() or ".." in name.parts or member.islnk() or ( + member.issym() and (link.is_absolute() or ".." in link.parts)): + raise Unavailable(f"core: unsafe archive member {member.name}") + handle.extractall(target) + + +def export_commit(mirror: Callable[[str], Path], url: str, commit: str, dest: Path) -> None: + """The tree of commit, and of each submodule at the commit the tree + records, as plain files in a fresh dest. Every object comes from a bare + mirror (mirror(url) fetches into it), never from a working tree.""" + if dest.exists(): + shutil.rmtree(dest) + + def one(repo_url: str, sha: str, target: Path) -> None: + if not re.fullmatch(r"[0-9a-f]{40}", sha): + raise Unavailable(f"core: {sha!r} is not a commit id") + bare = mirror(repo_url) + try: + git_out("-C", str(bare), "cat-file", "-e", f"{sha}^{{commit}}") + except subprocess.CalledProcessError: + git_out("-C", str(bare), "fetch", "--quiet", repo_url, sha) + extract_tar(git_out("-C", str(bare), "archive", "--format=tar", sha), target) + links: dict[str, str] = {} + for entry in git_out("-C", str(bare), "ls-tree", "-r", "-z", sha).split(b"\0"): + if entry.startswith(b"160000 commit "): + meta, raw_path = entry.split(b"\t", 1) + links[raw_path.decode()] = meta.split()[2].decode() + if not links: + return + try: + config = git_out("-C", str(bare), "config", "--blob", f"{sha}:.gitmodules", "-z", + "--get-regexp", r"^submodule\..*\.(path|url)$").decode() + except subprocess.CalledProcessError as exc: + raise Unavailable(f"core: {repo_url} has submodules and no readable .gitmodules") from exc + paths: dict[str, str] = {} + urls: dict[str, str] = {} + for item in filter(None, config.split("\0")): + key, _, value = item.partition("\n") + name, field_ = key[len("submodule."):].rsplit(".", 1) + (paths if field_ == "path" else urls)[name] = value + for name, path in paths.items(): + if path in links and name in urls: + one(submodule_url(repo_url, urls[name]), links[path], target / path) + + one(url, commit, dest) + + +def built_core(tree: Path) -> Path: + """The newest *_libretro.so a build left: a regular file inside the tree, + never a link a build could point at a host file.""" + root = tree.resolve() + found = [] + for path in tree.rglob("*_libretro.so"): + info = path.lstat() + if stat.S_ISREG(info.st_mode) and path.resolve().is_relative_to(root): + found.append((info.st_mtime, path)) + if not found: + raise Unavailable(f"core: the build left no *_libretro.so regular file in {tree}") + return max(found)[1] + + +def copy_regular(src: Path, dest: Path) -> None: + """Copy src only when it is a regular file, never through a link.""" + fd = os.open(src, os.O_RDONLY | os.O_NOFOLLOW) + with os.fdopen(fd, "rb") as handle: + if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode): + raise Unavailable(f"core: {src} is not a regular file") + dest.parent.mkdir(parents=True, exist_ok=True) + with dest.open("wb") as out: + shutil.copyfileobj(handle, out) + + +# -------------------------------------------------------------------------- +# Cores +# -------------------------------------------------------------------------- + +@dataclass(frozen=True) +class Core: + name: str + path: Path + sha256: str + artifact: str | None = None + repo: str | None = None + commit: str | None = None + build_command: str | None = None + + +def safe_extract_so(archive: Path, member: str, target: Path) -> None: + with zipfile.ZipFile(archive) as handle: + names = handle.namelist() + if member not in names: + raise Unavailable(f"{archive.name}: no {member} inside ({', '.join(names[:5])})") + target.parent.mkdir(parents=True, exist_ok=True) + scratch = target.with_suffix(".part") + with handle.open(member) as src, scratch.open("wb") as dst: + shutil.copyfileobj(src, dst) + os.replace(scratch, target) + + +class Cores: + """Buildbot nightlies, downloaded once per build, else local builds of + the profile's pinned commit.""" + + def __init__(self, campaign: Campaign) -> None: + self.c = campaign + self.listing: set[str] | None = None + + def retrying(self, what: str, call: Callable[[], T]) -> T: + for attempt, delay in enumerate((*self.c.settings.delays, None)): + try: + return call() + except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as exc: + if isinstance(exc, urllib.error.HTTPError) and exc.code < 500 and exc.code != 429: + raise Unavailable(f"{what}: HTTP {exc.code}") from exc + if delay is None: + raise Unavailable(f"{what}: {exc}") from exc + self.c.log(f"{what}: {exc}, retry {attempt + 1} in {delay}s") + self.c.host.sleep(delay) + raise AssertionError("unreachable") + + def buildbot(self) -> set[str]: + if self.listing is None: + if not self.c.settings.network: + self.listing = set() + else: + def read() -> bytes: + with self.c.host.urlopen(BUILDBOT, timeout=120) as response: + return response.read() + page = self.retrying("buildbot listing", read).decode("utf-8", "replace") + self.listing = set(re.findall(r"([A-Za-z0-9_]+)_libretro\.so\.zip", page)) + return self.listing + + def names(self, profile: dict) -> list[str]: + listing = self.buildbot() + return sorted({str(c) for c in profile.get("cores") or () if str(c) in listing}) + + def nightly(self, name: str, profile: dict) -> Core: + url = f"{BUILDBOT}{name}_libretro.so.zip" + cached = self.c.state["cores"].get(name) or {} + + def head() -> dict: + request = urllib.request.Request(url, method="HEAD") + with self.c.host.urlopen(request, timeout=120) as response: + return {"etag": response.headers.get("ETag"), + "last_modified": response.headers.get("Last-Modified")} + stamp = self.retrying(f"{name} nightly", head) + target = self.c.paths.home / "cores" / name / f"{name}_libretro.so" + if (cached.get("etag"), cached.get("last_modified")) != (stamp["etag"], stamp["last_modified"]) \ + or not target.is_file() or file_sha256(target) != cached.get("sha256"): + archive = target.parent / f"{name}_libretro.so.zip" + archive.parent.mkdir(parents=True, exist_ok=True) + + def download() -> None: + with self.c.host.urlopen(url, timeout=600) as response, archive.open("wb") as out: + shutil.copyfileobj(response, out) + self.retrying(f"{name} nightly", download) + safe_extract_so(archive, f"{name}_libretro.so", target) + archive.unlink() + cached = {**stamp, "url": url, "sha256": file_sha256(target), "fetched_at": now_iso()} + self.c.state["cores"][name] = cached + self.c.log(f"core {name}: new nightly {cached['sha256'][:12]} ({stamp['last_modified']})") + repo = profile.get("source") if isinstance(profile.get("source"), str) else None + return Core(name, target, cached["sha256"], artifact=url, + repo=repo if repo and repo.startswith("http") else None) + + def build(self, emulator: str, profile: dict) -> Core: + """The profile's pinned commit, built once and kept.""" + source, commit = profile.get("source"), profile.get("source_commit") + if not (isinstance(source, str) and source.startswith("http") and isinstance(commit, str)): + raise Unavailable("core: not on the buildbot, and no source and source_commit to build") + record = self.c.state["builds"].setdefault(emulator, {}) + if record.get("commit") == commit and record.get("error"): + raise Unavailable(f"core: build of {commit[:12]} failed before: {record['error']}") + out = self.c.paths.home / "builds" / emulator / commit + built = sorted(out.glob("*_libretro.so")) + if not built: + if not self.c.settings.network: + raise Unavailable("core: not on the buildbot, offline, nothing built yet") + try: + so, command = self.compile(source, commit, out) + except Unavailable as exc: + self.c.state["builds"][emulator] = {"commit": commit, "error": str(exc), "at": now_iso()} + raise + built = [so] + record["command"] = command + command = record.get("command") or "make" + self.c.state["builds"][emulator] = {"commit": commit, "command": command, + "so": built[0].name, "at": now_iso()} + return Core(built[0].name.removesuffix("_libretro.so"), built[0], file_sha256(built[0]), + repo=source, commit=commit, build_command=command) + + def mirror(self, url: str) -> Path: + """The bare mirror of a repository, created on first use. Only host + git with the overrides of GIT_SAFE ever touches it.""" + if not MIRROR_URL.match(url): + raise Unavailable(f"core: {url!r} is not an https repository URL") + bare = self.c.paths.home / "mirrors" / f"{slug(url)}.git" + if not (bare / "HEAD").is_file(): + bare.parent.mkdir(parents=True, exist_ok=True) + git_out("clone", "--bare", "--quiet", url, str(bare)) + return bare + + def compile(self, source: str, commit: str, out: Path) -> tuple[Path, str]: + """Fetch the commit into a bare mirror (host git, networked), export + it and its submodules with git archive into a fresh folder, and run + the project's make there under bubblewrap: no network, that folder + the one writable path. Returns the .so and the command, with how it + was isolated.""" + log = self.c.paths.logs / "builds" / f"{slug(source)}-{commit[:12]}.log" + log.parent.mkdir(parents=True, exist_ok=True) + isolation = core_probe.sandbox_argv([])[1] + if isolation != core_probe.SANDBOX and not self.c.settings.allow_unsandboxed: + raise Unavailable(f"refused: no sandbox to build {source} in ({isolation}), " + f"--allow-unsandboxed overrides") + # Working-tree clones of earlier campaign versions are never reused. + shutil.rmtree(self.c.paths.home / "src", ignore_errors=True) + tree = self.c.paths.home / "build-trees" / f"{slug(source)}-{commit[:12]}" + try: + export_commit(self.mirror, source, commit, tree) + except (OSError, subprocess.CalledProcessError, tarfile.TarError) as exc: + raise Unavailable(f"core: exporting {commit[:12]} of {source} failed: {exc}") from exc + makefile = "Makefile.libretro" if (tree / "Makefile.libretro").is_file() else "Makefile" + jobs = str(max(1, (os.cpu_count() or 2) // 2)) + command = ["make", "-f", makefile, f"-j{jobs}", "platform=unix"] + prefix, isolation = core_probe.sandbox_argv([tree]) + with log.open("a", encoding="utf-8") as handle: + handle.write(f"$ {' '.join(command)} in {tree} ({isolation})\n") + handle.flush() + proc = self.c.host.run(prefix + command, cwd=tree, stdout=handle, stderr=subprocess.STDOUT, + check=False, timeout=BUILD_TIMEOUT, env=child_env()) + if proc.returncode != 0: + tail = log.read_text(encoding="utf-8", errors="replace").strip().splitlines()[-3:] + raise Unavailable(f"core: make exited {proc.returncode}: {' | '.join(tail)} (log {log})") + built = built_core(tree) + copy_regular(built, out / built.name) + shutil.rmtree(tree, ignore_errors=True) + return out / built.name, f"{' '.join(command)} on git archive (isolation: {isolation})" diff --git a/scripts/probes/entries.py b/scripts/probes/entries.py new file mode 100644 index 000000000..44efe23fe --- /dev/null +++ b/scripts/probes/entries.py @@ -0,0 +1,51 @@ +"""Profile entries as the probes read them: systems, destination, regions, category.""" + +from __future__ import annotations + +import hashlib + +from model import measurements as mr + + +def profile_digest(profile: dict) -> str: + """What a check depends on in a profile: its entries, evidence left out, + so the campaign's own evidence never makes it run again.""" + entries = [{k: v for k, v in entry.items() if k != "evidence"} + for entry in profile.get("files") or []] + body = {"files": entries, "cores": profile.get("cores"), "type": profile.get("type"), + "systems": profile.get("systems")} + return hashlib.sha1(mr.canonical(body)).hexdigest() + + +def entry_systems(entry: dict, profile: dict) -> list[str]: + if entry.get("systems"): + return list(entry["systems"]) + if entry.get("system"): + return [entry["system"]] + return list(profile.get("systems") or []) + + +def entry_dest(entry: dict) -> str: + """Where the core reads the entry, relative to its system directory.""" + path = entry.get("path") + if isinstance(path, str) and path and not path.endswith("/"): + return path + return entry["name"] + + +def region_matches(entry: dict, region: str | None) -> bool: + regions = entry.get("region") + if not regions or not region: + return True + if isinstance(regions, str): + regions = [regions] + return region in regions or "world" in regions + + +def regions_of(entry: dict) -> list[str]: + regions = entry.get("region") or [] + return [regions] if isinstance(regions, str) else list(regions) + + +def is_bios(entry: dict) -> bool: + return entry.get("category", "bios") == "bios" and entry.get("type") != "directory" diff --git a/scripts/probes/gate.py b/scripts/probes/gate.py new file mode 100644 index 000000000..000bc919c --- /dev/null +++ b/scripts/probes/gate.py @@ -0,0 +1,42 @@ +"""The gate a campaign commit passes: tests, schemas, verify and pack of the changed profiles.""" + +from __future__ import annotations + +import shutil +import sys +from collections.abc import Sequence +from pathlib import Path + +import autorun +from probes.host import Host + + +# -------------------------------------------------------------------------- +# Gate +# -------------------------------------------------------------------------- + +def gate(root: Path, emulators: Sequence[str], host: Host | None = None) -> int: + """The measurement tests, the schemas, and verify plus an emulator pack + for each profile the campaign changed.""" + host = host or Host() + python = sys.executable + steps = [ + [python, "-m", "unittest", "tests.test_measurements", "tests.test_campaign"], + [python, "scripts/validate_schemas.py", "--source-only"], + ] + for emulator in sorted(set(emulators)): + steps.append([python, "scripts/verify.py", "--emulator", emulator]) + steps.append([python, "scripts/generate_pack.py", "--emulator", emulator, "--offline", + "--output-dir", "tmp/campaign/packs"]) + for argv in steps: + proc = host.run(argv, cwd=root, check=False) + if proc.returncode != 0: + print(f"gate: {' '.join(argv)} exited {proc.returncode}", file=sys.stderr) + return 1 + shutil.rmtree(root / "tmp" / "campaign" / "packs", ignore_errors=True) + return 0 + + +def changed_profiles(root: Path) -> list[str]: + return [Path(p).stem for p in autorun.changed_files(root) + if p.startswith("emulators/") and p.endswith(".yml")] diff --git a/scripts/probes/host.py b/scripts/probes/host.py new file mode 100644 index 000000000..ed2a138a0 --- /dev/null +++ b/scripts/probes/host.py @@ -0,0 +1,217 @@ +"""What a campaign reads from the machine: processes in their own group, settings, paths, the child environment and the host lock.""" + +from __future__ import annotations + +import contextlib +import hashlib +import http.client +import os +import re +import signal +import subprocess +import threading +import time +import urllib.request +from collections.abc import Callable, Iterator, Sequence +from dataclasses import dataclass +from pathlib import Path +from typing import IO, TYPE_CHECKING, TypedDict + +import autorun +import core_probe +from core import childenv, hostguard +from core.paths import REPO_ROOT + +if TYPE_CHECKING: + from typing_extensions import Unpack + + +CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" + + +LOCK_HELD_ENV = hostguard.LOCK_HELD_ENV + + +NETWORK_DELAYS = (10, 60, 300) + + +BENCH_WARMUP = 600 +BENCH_FRAMES = 1800 +BENCH_REPEAT = 5 +CHECK_REPEAT = 2 +PROBE_TIMEOUT = 900 + + +class Unavailable(RuntimeError): + """A core or a piece of content the campaign cannot get.""" + + +# -------------------------------------------------------------------------- +# Small helpers +# -------------------------------------------------------------------------- + +def slug(text: str) -> str: + return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-") or "x" + + +def file_sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +def file_sha1(path: Path) -> str: + digest = hashlib.sha1() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1 << 20), b""): + digest.update(chunk) + return digest.hexdigest() + + +# -------------------------------------------------------------------------- +# Host +# -------------------------------------------------------------------------- + +class PopenOptions(TypedDict, total=False): + """The Popen arguments the campaign passes through run_group.""" + + cwd: str | Path + env: dict[str, str] + text: bool + stdout: int | IO[str] | IO[bytes] + stderr: int | IO[str] | IO[bytes] + + +def run_group(argv: Sequence[str], *, timeout: float | None = None, check: bool = False, + capture_output: bool = False, **kwargs: Unpack[PopenOptions]) -> subprocess.CompletedProcess: + """subprocess.run in a process group of its own, the whole group killed + on a timeout or an interruption: a hung core never outlives its run.""" + if capture_output: + kwargs.setdefault("stdout", subprocess.PIPE) + kwargs.setdefault("stderr", subprocess.PIPE) + with subprocess.Popen(list(argv), start_new_session=True, **kwargs) as proc: + try: + out, err = proc.communicate(timeout=timeout) + except BaseException: + with contextlib.suppress(ProcessLookupError): + os.killpg(proc.pid, signal.SIGKILL) + proc.communicate() + raise + result = subprocess.CompletedProcess(list(argv), proc.returncode, out, err) + if check: + result.check_returncode() + return result + + +@dataclass +class Host: + """What the campaign reads from the machine and the network, replaced in tests.""" + + loadavg: Callable[[], tuple[float, float, float]] = os.getloadavg + sleep: Callable[[float], None] = time.sleep + clock: Callable[[], float] = time.monotonic + cpu_count: int = os.cpu_count() or 1 + free_gb: Callable[[Path], float] = hostguard.free_gb + poll: float = 60.0 + run: Callable[..., subprocess.CompletedProcess] = run_group + urlopen: Callable[..., http.client.HTTPResponse] = urllib.request.urlopen + + @property + def max_load(self) -> float: + return self.cpu_count / 4 + + +@dataclass +class Settings: + budget: float = 6 * 3600 + max_load_wait: float = 3600 + min_free_gb: float = 30 + cache_cap_gb: float = 20 + probe_timeout: int = PROBE_TIMEOUT + check_repeat: int = CHECK_REPEAT + bench_repeat: int = BENCH_REPEAT + bench_warmup: int = BENCH_WARMUP + bench_frames: int = BENCH_FRAMES + romfetch: str = "" + network: bool = True + # Benchmarks only choose between variants: never part of a default pass. + bench: bool = False + delays: tuple[float, ...] = NETWORK_DELAYS + echo: bool = True + # Third-party code (a nightly core, a project's Makefile) runs only under + # bubblewrap unless this is set. + allow_unsandboxed: bool = False + + +@dataclass +class Paths: + """Where the campaign writes: records and profiles in the checkout it + runs from, state, cores, logs and content in the main checkout's .cache.""" + + root: Path + home: Path + content: Path + db: Path + content_file: Path = CONTENT_FILE + oracle: Path = core_probe.DEFAULT_ORACLE + + @property + def state(self) -> Path: + return self.home / "state.json" + + @property + def logs(self) -> Path: + return self.home / "logs" + + @property + def emulators(self) -> Path: + return self.root / "emulators" + + @classmethod + def default(cls) -> Paths: + main = autorun.main_checkout() + return cls(root=REPO_ROOT, home=main / ".cache" / "campaign", + content=main / ".cache" / "test-content", db=REPO_ROOT / "database.json") + + +ROMFETCH_PASSED = ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME") + + +def child_env(romfetch: bool = False) -> dict[str, str]: + """What a program the campaign starts inherits: autorun's allowlist, + never a token or a password. romfetch also gets its own settings + (ROMFETCH_*), its account staying in its config file.""" + names: list[str] = [core_probe.PROBE_LOCK_ENV, core_probe.PROBE_LOCK_HELD_ENV] + if romfetch: + names += [k for k in os.environ if k.startswith("ROMFETCH_")] + list(ROMFETCH_PASSED) + return childenv.safe_env(names) + + +# The working directory belongs to the process. Two passes in threads that +# each saved and restored it could leave the process in the other's root, +# then in a folder deleted with its workspace. +_CWD_LOCK = threading.Lock() + + +@contextlib.contextmanager +def working_directory(path: Path) -> Iterator[None]: + """contextlib.chdir, which Python 3.9 lacks, one thread at a time.""" + with _CWD_LOCK: + before = Path.cwd() + os.chdir(path) + try: + yield + finally: + os.chdir(before) + + +@contextlib.contextmanager +def host_lock(lock_path: Path) -> Iterator[None]: + """The automation lock, unless the autorun job running us holds it.""" + if os.environ.get(LOCK_HELD_ENV): + yield + return + with hostguard.global_lock(lock_path): + yield diff --git a/scripts/probes/reports.py b/scripts/probes/reports.py new file mode 100644 index 000000000..7e261ec21 --- /dev/null +++ b/scripts/probes/reports.py @@ -0,0 +1,111 @@ +"""What the campaign reports: check status, open findings, and their review.""" + +from __future__ import annotations + +from pathlib import Path +from typing import TYPE_CHECKING + +import yaml + +from core.statefile import now_iso +from model import measurements as mr +from probes import rules +from probes.profileedit import write_fields +from probes.state import DONE, FAILED, PENDING + +if TYPE_CHECKING: + from probes.campaign import Campaign + + +# -------------------------------------------------------------------------- +# Reports +# -------------------------------------------------------------------------- + +def status_report(campaign: Campaign) -> dict: + counts, reasons, failed = campaign.counts() + runs = mr.read_campaign(campaign.paths.root, mr.CAMPAIGN_RUNS) + per = {} + for emulator, checks in sorted(campaign.state["checks"].items()): + per[emulator] = {key: {k: v for k, v in entry.items() if k in ("status", "reason", "record", "at")} + for key, entry in sorted(checks.items())} + return {"last_run": runs[-1] if runs else None, "counts": counts, "pending_reasons": reasons, + "failed": failed, "emulators": per} + + +def render_status(report: dict) -> str: + lines = [] + last = report["last_run"] + if last: + lines.append(f"last run {last['started_at']} to {last['ended_at']}: {last['result']}" + + (f" ({last['detail']})" if last["detail"] else "")) + else: + lines.append("no run yet") + counts = report["counts"] + lines.append(f"{counts.get(DONE, 0)} done, {counts.get(FAILED, 0)} failed, " + f"{counts.get(PENDING, 0)} pending") + lines.extend(f" pending {number:5} {reason}" + for reason, number in sorted(report["pending_reasons"].items(), key=lambda kv: -kv[1])) + lines.extend(f" FAILED {item['emulator']} {item['check']}: {item['reason']}" for item in report["failed"]) + for emulator, checks in report["emulators"].items(): + ran = [k for k, v in checks.items() if v["status"] != PENDING] + if ran: + lines.append(f"{emulator}") + for key in ran: + entry = checks[key] + lines.append(f" {entry['status']:7} {key}" + (f" {entry['record']}" if entry.get("record") else "") + + (f" ({entry['reason']})" if entry.get("reason") else "")) + return "\n".join(lines) + + +def open_findings(root: Path, everything: bool = False) -> list[dict]: + latest: dict[str, dict] = {} + for line in mr.read_campaign(root, mr.FINDINGS): + latest[line["key"]] = line + return [line for key, line in sorted(latest.items()) + if everything or line["status"] in ("open", "flagged")] + + +REVIEWED = ("applied", "rejected") + + +def review_finding(root: Path, key: str, status: str, reason: str, + updates: dict[str, object] | None = None, index: int | None = None) -> dict: + """Close an open finding after reading the core's code. + + `applied` writes `updates` into the entry the finding names, through the + same editor as the rule table, with the finding's record ids added as + `evidence:` under its field. An applied finding with no update records a + profile changed by hand. `rejected` keeps the profile as it is. Either + way a line with the reason is appended to the findings.""" + if status not in REVIEWED: + raise ValueError(f"status {status!r}: one of {', '.join(REVIEWED)}") + if not reason.strip(): + raise ValueError("a review names its reason") + latest = {line["key"]: line for line in mr.read_campaign(root, mr.FINDINGS)} + finding = latest.get(key) + if finding is None: + raise ValueError(f"no finding {key}") + if finding["status"] not in ("open", "flagged"): + raise ValueError(f"{key} is {finding['status']}, not open") + if updates and status != "applied": + raise ValueError("only an applied review changes the profile") + if updates: + path = root / "emulators" / f"{finding['emulator']}.yml" + entries = yaml.safe_load(path.read_text(encoding="utf-8")).get("files") or [] + matches = [i for i, entry in enumerate(entries) if entry.get("name") == finding["file"]] + if index is not None: + matches = [i for i in matches if i == index] + if len(matches) != 1: + raise ValueError(f"{finding['emulator']}: {len(matches)} entries named {finding['file']}" + + ("" if index is not None else ", pass --index")) + entry = entries[matches[0]] + verdict = rules.Verdict(finding["rule"], finding["field"], finding["run_shows"], + finding["statement"], tuple(finding["evidence"])) + evidence = rules.merge_evidence(entry.get("evidence"), verdict) + write_fields(path, matches[0], {**updates, "evidence": evidence}) + body = {key_: value for key_, value in finding.items() if key_ != "id"} + line = mr.seal_line({**body, "found_at": now_iso(), "status": status, "reason": reason}, + "found_at") + with (root / mr.records_path(mr.FINDINGS)).open("a", encoding="utf-8") as handle: + handle.write(mr.line_text(line) + "\n") + return line diff --git a/scripts/probes/state.py b/scripts/probes/state.py new file mode 100644 index 000000000..324d4dedd --- /dev/null +++ b/scripts/probes/state.py @@ -0,0 +1,48 @@ +"""The campaign's state file: what each check ran against, and whether it runs again.""" + +from __future__ import annotations + +import json +from pathlib import Path + +from core import statefile +from model import measurements as mr + + +STATE_VERSION = 1 + +DONE = "done" +FAILED = "failed" +PENDING = "pending" + + +# -------------------------------------------------------------------------- +# State +# -------------------------------------------------------------------------- + +def load_state(path: Path) -> dict: + try: + state = json.loads(path.read_text(encoding="utf-8")) + except FileNotFoundError: + state = {} + state.setdefault("version", STATE_VERSION) + for key in ("checks", "cores", "content", "builds", "emulators"): + state.setdefault(key, {}) + return state + + +def save_state(path: Path, state: dict) -> None: + statefile.save_state(path, state) + + +def should_run(previous: dict | None, core_sha: str, digest: str, oracle_sha: str = "") -> bool: + """A check runs again when it never ran, is pending, or ran against + another core build, another version of the profile, another oracle, or + before records carried a verdict.""" + if not previous: + return True + if previous.get("status") == PENDING: + return True + return (previous.get("core_sha256") != core_sha or previous.get("profile_digest") != digest + or previous.get("record_version") != mr.RECORD_VERSION + or previous.get("oracle_sha256", "") != oracle_sha) diff --git a/tests/test_campaign.py b/tests/test_campaign.py index f1ef5ca6e..e71156e52 100644 --- a/tests/test_campaign.py +++ b/tests/test_campaign.py @@ -28,8 +28,19 @@ from types import MappingProxyType import yaml +import autorun import campaign -from probes import profileedit as campaign_profiles +import core_probe +from core import hostguard +from probes import campaign as probes_campaign +from probes import content as probes_content +from probes import cores +from probes import entries as probes_entries +from probes import host as probes_host +from probes import reports +from probes import state +from core import statefile +from probes import profileedit from probes import rules from model import measurements as mr @@ -296,14 +307,14 @@ class RuleTable(unittest.TestCase): record = {"variants": [{"repetitions": [ rep(["black"] * 4 + ["logo"] * 3 + ["flash"] + ["title"] * 5), rep(["black"] * 5 + ["logo"] * 3 + ["title"] * 3)]}]} - self.assertEqual(campaign.reference_candidates(record), + self.assertEqual(probes_campaign.reference_candidates(record), [{"sha1": "logo", "first_frame": 40, "samples": 3}, {"sha1": "title", "first_frame": 80, "samples": 5}]) class ProfileEditor(unittest.TestCase): def test_replace_insert_and_keep_the_rest(self) -> None: - out = campaign_profiles.set_fields(PROFILE, 0, { + out = profileedit.set_fields(PROFILE, 0, { "required": False, "hle_fallback": True, "aliases": ["Bios.bin", "BIOS.BIN"], "evidence": {"hle_fallback": ["2026-10-27-cccccccccccc"]}}) parsed = yaml.safe_load(out) @@ -317,17 +328,17 @@ class ProfileEditor(unittest.TestCase): self.assertEqual(lines[lines.index(' evidence:') + 1], ' hle_fallback: ["2026-10-27-cccccccccccc"]') def test_the_last_entry_and_a_no_op(self) -> None: - out = campaign_profiles.set_fields(PROFILE, 1, {"path": "sub/other.bin"}) + out = profileedit.set_fields(PROFILE, 1, {"path": "sub/other.bin"}) self.assertEqual(yaml.safe_load(out)["files"][1]["path"], "sub/other.bin") - self.assertEqual(campaign_profiles.set_fields(PROFILE, 1, {"required": False}), PROFILE) + self.assertEqual(profileedit.set_fields(PROFILE, 1, {"required": False}), PROFILE) def test_refusals(self) -> None: - with self.assertRaises(campaign_profiles.ProfileEditError): - campaign_profiles.set_fields(PROFILE, 2, {"required": False}) - with self.assertRaises(campaign_profiles.ProfileEditError): - campaign_profiles.set_fields("emulator: X\n", 0, {"required": False}) - with self.assertRaises(campaign_profiles.ProfileEditError): - campaign_profiles.set_fields(PROFILE, 0, {"name": "x.bin"}) + with self.assertRaises(profileedit.ProfileEditError): + profileedit.set_fields(PROFILE, 2, {"required": False}) + with self.assertRaises(profileedit.ProfileEditError): + profileedit.set_fields("emulator: X\n", 0, {"required": False}) + with self.assertRaises(profileedit.ProfileEditError): + profileedit.set_fields(PROFILE, 0, {"name": "x.bin"}) def test_every_profile_reads_as_its_entries(self) -> None: # The text layout the editor reads holds in every profile it may edit. @@ -337,10 +348,10 @@ class ProfileEditor(unittest.TestCase): if not entries or "\nfiles:\n" not in text: continue with self.subTest(profile=path.name): - self.assertEqual(len(campaign_profiles.item_spans(text.splitlines())), len(entries)) + self.assertEqual(len(profileedit.item_spans(text.splitlines())), len(entries)) -class FakeHost(campaign.Host): +class FakeHost(probes_host.Host): def __init__(self, loads: list[float] | None = None, free: float = 500.0) -> None: super().__init__() self.loads = list(loads or [0.0]) @@ -408,7 +419,7 @@ class Workspace(unittest.TestCase): {"sha1": screen(1), "stage": "bios", "shows": "the fake logo"}, {"sha1": screen(20), "stage": "game", "shows": "the fake title"}]}}}]}), encoding="utf-8") - self.paths = campaign.Paths(root=self.root, home=self.tmp / "home", + self.paths = probes_host.Paths(root=self.root, home=self.tmp / "home", content=self.tmp / "content", db=self.root / "database.json", content_file=self.content_file, oracle=self.oracle) @@ -423,25 +434,25 @@ class Workspace(unittest.TestCase): {"name": "game.bin", "size": len(payload), "sha1": hashlib.sha1(payload).hexdigest()}]})) return folder - def make(self, host: campaign.Host | None = None, **settings: object) -> campaign.Campaign: + def make(self, host: probes_host.Host | None = None, **settings: object) -> probes_campaign.Campaign: values = {"delays": (1, 2), "echo": False, **settings} - return campaign.Campaign(self.paths, campaign.Settings(**values), host or FakeHost(), + return probes_campaign.Campaign(self.paths, probes_host.Settings(**values), host or FakeHost(), lock_path=self.tmp / "auto.lock") class StateAndResume(Workspace): def test_should_run(self) -> None: - self.assertTrue(campaign.should_run(None, "a", "d")) + self.assertTrue(state.should_run(None, "a", "d")) done = {"status": "done", "core_sha256": "a", "profile_digest": "d", "record_version": mr.RECORD_VERSION, "oracle_sha256": ""} - self.assertFalse(campaign.should_run(done, "a", "d")) + self.assertFalse(state.should_run(done, "a", "d")) # A record from before the verdicts, or judged against another oracle, runs again. - self.assertTrue(campaign.should_run({**done, "record_version": 3}, "a", "d")) - self.assertTrue(campaign.should_run(done, "a", "d", "f" * 64)) - self.assertTrue(campaign.should_run(done, "b", "d")) - self.assertTrue(campaign.should_run(done, "a", "e")) - self.assertTrue(campaign.should_run({**done, "status": "pending"}, "a", "d")) - self.assertFalse(campaign.should_run({**done, "status": "failed"}, "a", "d")) + self.assertTrue(state.should_run({**done, "record_version": 3}, "a", "d")) + self.assertTrue(state.should_run(done, "a", "d", "f" * 64)) + self.assertTrue(state.should_run(done, "b", "d")) + self.assertTrue(state.should_run(done, "a", "e")) + self.assertTrue(state.should_run({**done, "status": "pending"}, "a", "d")) + self.assertFalse(state.should_run({**done, "status": "failed"}, "a", "d")) def test_a_record_judged_again_is_read_in_its_place(self) -> None: lines = self.root / mr.records_path("fake") @@ -467,16 +478,16 @@ class StateAndResume(Workspace): def test_evidence_does_not_change_the_digest(self) -> None: profile = yaml.safe_load(PROFILE) - before = campaign.profile_digest(profile) + before = probes_entries.profile_digest(profile) profile["files"][0]["evidence"] = {"required": ["2026-10-27-dddddddddddd"]} - self.assertEqual(campaign.profile_digest(profile), before) + self.assertEqual(probes_entries.profile_digest(profile), before) profile["files"][0]["required"] = False - self.assertNotEqual(campaign.profile_digest(profile), before) + self.assertNotEqual(probes_entries.profile_digest(profile), before) def test_state_survives_a_reload(self) -> None: c = self.make() c.pending("fake", "fake/fake-system/x/files", "content: romfetch not found") - campaign.save_state(self.paths.state, c.state) + state.save_state(self.paths.state, c.state) again = self.make() self.assertEqual(again.state["checks"]["fake"]["fake/fake-system/x/files"]["status"], "pending") @@ -498,32 +509,32 @@ class Guards(Workspace): host = FakeHost(loads=[5.0]) c = self.make(host, max_load_wait=120) c.deadline = 10_000 - with self.assertRaisesRegex(campaign.Pause, "busy host"): + with self.assertRaisesRegex(probes_campaign.Pause, "busy host"): c.guard() def test_full_disk_pauses(self) -> None: c = self.make(FakeHost(free=10.0), min_free_gb=30) c.deadline = 10_000 - with self.assertRaisesRegex(campaign.Pause, "disk"): + with self.assertRaisesRegex(probes_campaign.Pause, "disk"): c.guard() def test_budget_pauses(self) -> None: c = self.make() c.deadline = 0 - with self.assertRaisesRegex(campaign.Pause, "budget"): + with self.assertRaisesRegex(probes_campaign.Pause, "budget"): c.guard() def test_the_lock_is_skipped_under_autorun(self) -> None: lock = self.tmp / "held.lock" - with campaign.autorun.global_lock(lock): - with self.assertRaises(campaign.autorun.LockBusy), campaign.host_lock(lock): + with hostguard.global_lock(lock): + with self.assertRaises(hostguard.LockBusy), probes_host.host_lock(lock): pass - os.environ[campaign.LOCK_HELD_ENV] = "1" + os.environ[probes_host.LOCK_HELD_ENV] = "1" try: - with campaign.host_lock(lock): + with probes_host.host_lock(lock): pass finally: - del os.environ[campaign.LOCK_HELD_ENV] + del os.environ[probes_host.LOCK_HELD_ENV] class ChildEnvironment(unittest.TestCase): @@ -531,7 +542,7 @@ class ChildEnvironment(unittest.TestCase): host = {"GITHUB_TOKEN": "t", "GH_TOKEN": "t", "ROMSTATION_USER": "u", "ROMSTATION_PASS": "p", "ROMFETCH_CONTENT_DIR": "/c", "SSH_AUTH_SOCK": "/s", "PATH": "/usr/bin"} with unittest.mock.patch.dict(os.environ, host): - probe, fetch = campaign.child_env(), campaign.child_env(romfetch=True) + probe, fetch = probes_host.child_env(), probes_host.child_env(romfetch=True) for env in (probe, fetch): self.assertFalse({"GITHUB_TOKEN", "GH_TOKEN", "ROMSTATION_USER", "ROMSTATION_PASS", "SSH_AUTH_SOCK"} & set(env)) @@ -545,9 +556,9 @@ class ChildEnvironment(unittest.TestCase): host.run = lambda argv, **kw: (seen.append(kw.get("env")), subprocess.CompletedProcess([], 0, '{"id": "x"}', ""))[1] with tempfile.TemporaryDirectory(dir=TMP) as tmp: - paths = campaign.Paths(root=Path(tmp), home=Path(tmp) / "h", content=Path(tmp) / "c", - db=Path(tmp) / "db.json", content_file=campaign.CONTENT_FILE) - c = campaign.Campaign(paths, campaign.Settings(echo=False), host, lock_path=Path(tmp) / "l") + paths = probes_host.Paths(root=Path(tmp), home=Path(tmp) / "h", content=Path(tmp) / "c", + db=Path(tmp) / "db.json", content_file=probes_host.CONTENT_FILE) + c = probes_campaign.Campaign(paths, probes_host.Settings(echo=False), host, lock_path=Path(tmp) / "l") c.deadline = 10_000 with unittest.mock.patch.dict(os.environ, {"GITHUB_TOKEN": "t"}): c.probe(["run"], "x") @@ -561,7 +572,7 @@ class FailClosed(Workspace): host = FakeHost() host.results = [subprocess.CompletedProcess([], 0, "{}", "")] c = self.make(host) - with unittest.mock.patch.object(campaign.core_probe.shutil, "which", return_value=None): + with unittest.mock.patch.object(core_probe.shutil, "which", return_value=None): current = c.run(set(), None) self.assertEqual(current.result, "refused") self.assertIn("bwrap not found", current.detail) @@ -571,24 +582,24 @@ class FailClosed(Workspace): def test_the_override_lets_it_run(self) -> None: c = self.make(allow_unsandboxed=True) c.unit_cores = lambda *a, **k: [] - with unittest.mock.patch.object(campaign.core_probe.shutil, "which", return_value=None): + with unittest.mock.patch.object(core_probe.shutil, "which", return_value=None): self.assertEqual(c.run(set(), None).result, "complete") def test_every_probe_requires_the_sandbox(self) -> None: - core = campaign.Core("fake", self.tmp / "x.so", "a" * 64) + core = cores.Core("fake", self.tmp / "x.so", "a" * 64) self.assertIn("--require-sandbox", self.make().probe_args("run", core, "fake", "s", None, None)) self.assertNotIn("--require-sandbox", self.make(allow_unsandboxed=True).probe_args( "run", core, "fake", "s", None, None)) def test_a_build_without_a_sandbox_is_refused(self) -> None: c = self.make() - src = c.paths.home / "src" / campaign.slug("https://example.invalid/x") + src = c.paths.home / "src" / probes_host.slug("https://example.invalid/x") (src / ".git").mkdir(parents=True) (src / "Makefile").write_text("all:\n") host = c.host host.results = [subprocess.CompletedProcess([], 0, "", "")] - with unittest.mock.patch.object(campaign.core_probe.shutil, "which", return_value=None), \ - self.assertRaisesRegex(campaign.Unavailable, "refused: no sandbox"): + with unittest.mock.patch.object(core_probe.shutil, "which", return_value=None), \ + self.assertRaisesRegex(probes_host.Unavailable, "refused: no sandbox"): c.cores.compile("https://example.invalid/x", "a" * 40, self.tmp / "out") self.assertFalse(any(call[0] == "make" for call in host.calls)) @@ -646,24 +657,24 @@ class BuildIsolation(unittest.TestCase): def test_the_export_holds_the_tree_and_its_submodule_and_no_git(self) -> None: tree = self.tmp / "tree" - campaign.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, tree) + cores.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, tree) self.assertEqual((tree / "lib" / "sub.c").read_text(), "int x;\n") self.assertTrue((tree / "Makefile").is_file()) self.assertEqual([p for p in tree.rglob(".git")], []) def test_a_build_cannot_reach_the_mirror(self) -> None: tree = self.tmp / "tree" - prefix, isolation = campaign.core_probe.sandbox_argv([tree]) - if isolation != campaign.core_probe.SANDBOX: + prefix, isolation = core_probe.sandbox_argv([tree]) + if isolation != core_probe.SANDBOX: self.skipTest("no working bwrap on this host") - campaign.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, tree) + cores.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, tree) proc = subprocess.run(prefix + ["make"], cwd=tree, capture_output=True, text=True, - check=False, env=campaign.child_env()) + check=False, env=probes_host.child_env()) self.assertEqual(proc.returncode, 0, proc.stderr) mirror = self.mirrors[self.MAIN] self.assertFalse((mirror / "hooks" / "post-checkout").exists()) self.assertEqual((mirror / "config").read_text(), self.config) - campaign.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, self.tmp / "again") + cores.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, self.tmp / "again") self.assertFalse(self.pwned.exists()) def test_host_git_runs_nothing_a_repository_config_names(self) -> None: @@ -676,31 +687,31 @@ class BuildIsolation(unittest.TestCase): f'[filter "x"]\n\tsmudge = touch {self.pwned}\n') (mirror / "info").mkdir(exist_ok=True) (mirror / "info" / "attributes").write_text("* filter=x\n") - campaign.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, self.tmp / "tree") - campaign.git_out("-C", str(mirror), "update-ref", "refs/x", self.commit) + cores.export_commit(self.mirrors.__getitem__, self.MAIN, self.commit, self.tmp / "tree") + cores.git_out("-C", str(mirror), "update-ref", "refs/x", self.commit) self.assertFalse(self.pwned.exists()) # Plain git on the same mirror runs the planted hook: the test plants a live one. subprocess.run(["git", "-C", str(mirror), "update-ref", "refs/y", self.commit], check=True) self.assertTrue(self.pwned.exists()) def test_only_https_mirrors(self) -> None: - c = campaign.Campaign(campaign.Paths(root=self.tmp, home=self.tmp / "home", content=self.tmp, - db=self.tmp / "db.json", content_file=campaign.CONTENT_FILE), - campaign.Settings(echo=False), FakeHost(), lock_path=self.tmp / "l") + c = probes_campaign.Campaign(probes_host.Paths(root=self.tmp, home=self.tmp / "home", content=self.tmp, + db=self.tmp / "db.json", content_file=probes_host.CONTENT_FILE), + probes_host.Settings(echo=False), FakeHost(), lock_path=self.tmp / "l") for url in ("file:///etc", "/home/x/repo", "ext::sh -c touch", "ssh://h/r", "git@h:r"): - with self.subTest(url=url), self.assertRaises(campaign.Unavailable): + with self.subTest(url=url), self.assertRaises(probes_host.Unavailable): c.cores.mirror(url) - self.assertEqual(campaign.submodule_url(self.MAIN, "../sub.git"), self.SUB) - self.assertEqual(campaign.git_env()["GIT_ALLOW_PROTOCOL"], "https") + self.assertEqual(cores.submodule_url(self.MAIN, "../sub.git"), self.SUB) + self.assertEqual(cores.git_env()["GIT_ALLOW_PROTOCOL"], "https") def test_a_whole_build_wipes_old_clones_and_copies_a_regular_file(self) -> None: - if campaign.core_probe.sandbox_argv([])[1] != campaign.core_probe.SANDBOX: + if core_probe.sandbox_argv([])[1] != core_probe.SANDBOX: self.skipTest("no working bwrap on this host") home = self.tmp / "home" (home / "src" / "old" / ".git").mkdir(parents=True) - c = campaign.Campaign(campaign.Paths(root=self.tmp, home=home, content=self.tmp, - db=self.tmp / "db.json", content_file=campaign.CONTENT_FILE), - campaign.Settings(echo=False), campaign.Host(), lock_path=self.tmp / "l") + c = probes_campaign.Campaign(probes_host.Paths(root=self.tmp, home=home, content=self.tmp, + db=self.tmp / "db.json", content_file=probes_host.CONTENT_FILE), + probes_host.Settings(echo=False), probes_host.Host(), lock_path=self.tmp / "l") c.cores.mirror = self.mirrors.__getitem__ so, command = c.cores.compile(self.MAIN, self.commit, self.tmp / "out") self.assertEqual(so, self.tmp / "out" / "fake_libretro.so") @@ -719,17 +730,17 @@ class BuiltCore(unittest.TestCase): def test_a_link_is_never_taken_for_the_core(self) -> None: (self.tree / "a_libretro.so").symlink_to(self.secret) - with self.assertRaises(campaign.Unavailable): - campaign.built_core(self.tree) + with self.assertRaises(probes_host.Unavailable): + cores.built_core(self.tree) (self.tree / "sub").mkdir() (self.tree / "sub" / "b_libretro.so").write_bytes(b"\x7fELF") - self.assertEqual(campaign.built_core(self.tree), self.tree / "sub" / "b_libretro.so") + self.assertEqual(cores.built_core(self.tree), self.tree / "sub" / "b_libretro.so") def test_copy_refuses_a_link(self) -> None: link = self.tree / "c_libretro.so" link.symlink_to(self.secret) with self.assertRaises(OSError): - campaign.copy_regular(link, self.tree / "out.so") + cores.copy_regular(link, self.tree / "out.so") self.assertFalse((self.tree / "out.so").exists()) @@ -737,7 +748,7 @@ class ProbeRuns(Workspace): def completed(self, code: int, stdout: str = "", stderr: str = "") -> subprocess.CompletedProcess: return subprocess.CompletedProcess([], code, stdout, stderr) - def probe(self, *results: object) -> tuple[campaign.ProbeResult, FakeHost]: + def probe(self, *results: object) -> tuple[probes_campaign.ProbeResult, FakeHost]: host = FakeHost() host.results = list(results) c = self.make(host) @@ -764,13 +775,13 @@ class ProbeRuns(Workspace): self.assertEqual((result.status, result.record, len(host.calls)), ("done", record, 2)) def test_refusal_on_a_busy_host_pauses(self) -> None: - with self.assertRaisesRegex(campaign.Pause, "busy host"): + with self.assertRaisesRegex(probes_campaign.Pause, "busy host"): self.probe(self.completed(3, stderr="load average")) class Content(Workspace): - def content(self, name: str = "Fake Game (World)", pinned: bool = False) -> campaign.Content: - return campaign.Content("fake-system", "fakesys", name, "no-intro", "r", None, "", 12, 2, + def content(self, name: str = "Fake Game (World)", pinned: bool = False) -> probes_content.Content: + return probes_content.Content("fake-system", "fakesys", name, "no-intro", "r", None, "", 12, 2, pinned, None) def test_local_content_is_verified_by_its_identity(self) -> None: @@ -778,12 +789,12 @@ class Content(Workspace): c = self.make() self.assertEqual(c.store.get(self.content()), self.game) (self.game / "game.bin").write_bytes(b"EDIT") - with self.assertRaisesRegex(campaign.Unavailable, "does not match"): + with self.assertRaisesRegex(probes_host.Unavailable, "does not match"): self.make().store.get(self.content()) def test_without_romfetch_the_check_waits_for_content(self) -> None: c = self.make(romfetch=str(self.tmp / "absent-romfetch")) - with self.assertRaisesRegex(campaign.Unavailable, "romfetch not found"): + with self.assertRaisesRegex(probes_host.Unavailable, "romfetch not found"): c.store.get(self.content()) def test_romfetch_is_retried_on_a_source_error(self) -> None: @@ -813,7 +824,7 @@ class Content(Workspace): host.results = [subprocess.CompletedProcess( [], 1, json.dumps({"error": {"code": "no_entry", "message": "m", "hint": "h"}}), "")] c = self.make(host, romfetch=str(fetcher)) - with self.assertRaisesRegex(campaign.Unavailable, r"exit 1 \(no_entry\)"): + with self.assertRaisesRegex(probes_host.Unavailable, r"exit 1 \(no_entry\)"): c.store.get(self.content()) self.assertEqual(len(host.calls), 1) @@ -854,9 +865,9 @@ class Content(Workspace): def test_load_file(self) -> None: self.put_game() - self.assertEqual(campaign.load_file(self.game, ""), self.game / "game.bin") - with self.assertRaises(campaign.Unavailable): - campaign.load_file(self.game, "cue") + self.assertEqual(probes_content.load_file(self.game, ""), self.game / "game.bin") + with self.assertRaises(probes_host.Unavailable): + probes_content.load_file(self.game, "cue") class Findings(Workspace): @@ -865,10 +876,10 @@ class Findings(Workspace): def setUp(self) -> None: super().setUp() self.c = self.make() - self.c.current = campaign.Pass(started=campaign.now_iso()) - self.content = campaign.Content("fake-system", "fakesys", "Fake Game (World)", "no-intro", + self.c.current = probes_campaign.Pass(started=statefile.now_iso()) + self.content = probes_content.Content("fake-system", "fakesys", "Fake Game (World)", "no-intro", "r", None, "", 12, 2, False, None) - self.core = campaign.Core("fake", self.tmp / "fake_libretro.so", "a" * 64) + self.core = cores.Core("fake", self.tmp / "fake_libretro.so", "a" * 64) self.profile = self.root / "emulators" / "fake.yml" def lines(self) -> list[dict]: @@ -950,8 +961,8 @@ class Findings(Workspace): self.c.settle("fake", self.content, self.core, 0, self.entry(), [self.contradicted()]) key = self.lines()[-1]["key"] with self.assertRaises(ValueError): - campaign.review_finding(self.root, key, "applied", " ") - line = campaign.review_finding(self.root, key, "applied", "the core logs the md5 (x.c:1)", + reports.review_finding(self.root, key, "applied", " ") + line = reports.review_finding(self.root, key, "applied", "the core logs the md5 (x.c:1)", {"on_mismatch": "warn"}) self.assertEqual((line["status"], line["reason"]), ("applied", "the core logs the md5 (x.c:1)")) entry = self.entry() @@ -959,9 +970,9 @@ class Findings(Workspace): self.assertEqual(entry["evidence"], {"validation": [self.RID]}) text = self.profile.read_text() self.assertLess(text.index("validation: [size]"), text.index("on_mismatch")) - self.assertEqual(campaign.open_findings(self.root), []) + self.assertEqual(reports.open_findings(self.root), []) with self.assertRaises(ValueError): - campaign.review_finding(self.root, key, "rejected", "again") + reports.review_finding(self.root, key, "rejected", "again") try: from jsonschema import Draft202012Validator except ImportError: @@ -975,9 +986,9 @@ class Findings(Workspace): self.c.settle("fake", self.content, self.core, 0, self.entry(), [verdict]) key = self.lines()[-1]["key"] with self.assertRaises(ValueError): - campaign.review_finding(self.root, key, "rejected", "kept", {"required": False}) + reports.review_finding(self.root, key, "rejected", "kept", {"required": False}) out = io.StringIO() - with contextlib.redirect_stdout(out), unittest.mock.patch.object(campaign.Paths, "default", + with contextlib.redirect_stdout(out), unittest.mock.patch.object(probes_host.Paths, "default", return_value=self.paths): self.assertEqual(campaign.main(["review", key, "--status", "rejected", "--reason", "the md5 is checked (x.c:2)"]), 0) @@ -997,7 +1008,7 @@ class Findings(Workspace): ("chore: add campaign measurements", ["measurements/fake.jsonl", "measurements/findings.jsonl"]), ("chore: apply tested fields to fake", ["emulators/fake.yml"])]) for subject, _ in plan: - self.assertEqual(campaign.autorun.check_subject(subject), [], subject) + self.assertEqual(autorun.check_subject(subject), [], subject) # A file someone had changed before the pass is left to them. self.assertEqual(self.c.plan_commits({"emulators/fake.yml"})[1:], []) out = io.StringIO() @@ -1013,7 +1024,7 @@ class ContentFile(Workspace): "romfetch": "fakesys", "content": [{"name": "Other Game (Japan)", "catalog": "redump", "reason": "r"}]}}}), encoding="utf-8") out = io.StringIO() - with unittest.mock.patch.object(campaign.Paths, "default", return_value=self.paths), \ + with unittest.mock.patch.object(probes_host.Paths, "default", return_value=self.paths), \ contextlib.redirect_stdout(out): self.assertEqual(campaign.main(["run", "--dry-run", "--content-file", str(other)]), 0) self.assertIn("Other Game (Japan)", out.getvalue()) @@ -1025,7 +1036,7 @@ class Registry(unittest.TestCase): self.assertEqual(stems & set(mr.CAMPAIGN_FILES), set()) def test_content_list(self) -> None: - content = campaign.load_content(campaign.CONTENT_FILE) + content = probes_content.load_content(probes_host.CONTENT_FILE) systems = {s for p in (REPO_ROOT / "emulators").glob("*.yml") for s in (yaml.safe_load(p.read_text()) or {}).get("systems") or ()} self.assertTrue(content) @@ -1039,7 +1050,7 @@ class Registry(unittest.TestCase): def test_no_job_runs_a_standing_campaign(self) -> None: """A daily pass over every profile contradicted the rule that probes run on demand, for a question that names its profiles.""" - for name, job in campaign.autorun.load_jobs().items(): + for name, job in autorun.load_jobs().items(): for step in [*job.steps, *job.gate]: with self.subTest(job=name): self.assertNotIn("scripts/campaign.py", step.argv) @@ -1053,8 +1064,8 @@ class FakeCorePasses(Workspace): def setUpClass(cls) -> None: # These passes prove the cores run sandboxed. Without a working bwrap # the campaign refuses, and the cause is named here instead of a KeyError. - _prefix, isolation = campaign.core_probe.sandbox_argv([Path(tempfile.gettempdir())]) - if isolation != campaign.core_probe.SANDBOX: + _prefix, isolation = core_probe.sandbox_argv([Path(tempfile.gettempdir())]) + if isolation != core_probe.SANDBOX: raise unittest.SkipTest(f"no sandbox here ({isolation}): install bubblewrap") TMP.mkdir(parents=True, exist_ok=True) cls.build = Path(tempfile.mkdtemp(dir=TMP)) @@ -1072,17 +1083,17 @@ class FakeCorePasses(Workspace): shutil.rmtree(cls.build, ignore_errors=True) def passing(self, kind: str = "plain", core: Path | None = None, - **settings: object) -> campaign.Campaign: + **settings: object) -> probes_campaign.Campaign: self.put_game() # The core_probe threshold follows the host: a test never waits on the real load. - host = campaign.Host(loadavg=lambda: (0.0, 0.0, 0.0), free_gb=lambda path: 500.0, + host = probes_host.Host(loadavg=lambda: (0.0, 0.0, 0.0), free_gb=lambda path: 500.0, cpu_count=1_000_000) values = {"bench_warmup": 2, "bench_frames": 4, "check_repeat": 2, "probe_timeout": 30, "delays": (1,), "echo": False, **settings} - c = campaign.Campaign(self.paths, campaign.Settings(**values), host, + c = probes_campaign.Campaign(self.paths, probes_host.Settings(**values), host, lock_path=self.tmp / "auto.lock") so = core or self.cores[kind] - c.unit_cores = lambda *a, **k: [campaign.Core("fake", so, campaign.file_sha256(so))] + c.unit_cores = lambda *a, **k: [cores.Core("fake", so, probes_host.file_sha256(so))] return c def test_a_stand_in_is_proven_and_written(self) -> None: @@ -1091,7 +1102,7 @@ class FakeCorePasses(Workspace): self.assertEqual(current.result, "complete") records = [s.record for s in mr.read_records(self.root)] isolations = {rep["isolation"] for r in records for v in r["variants"] for rep in v["repetitions"]} - self.assertEqual(isolations, {campaign.core_probe.SANDBOX}) + self.assertEqual(isolations, {core_probe.SANDBOX}) kinds = sorted(r["subject"].split("-")[0] for r in records) self.assertEqual(kinds, ["alias", "files", "negative", "none"]) by_kind = {r["subject"].split("-")[0]: r for r in records} @@ -1205,15 +1216,15 @@ class FakeCorePasses(Workspace): self.assertLess(ends["b"][0], ends["a"][-1]) self.assertLess(ends["a"][0], ends["b"][-1]) - def passing_in(self, workspace: Workspace) -> campaign.Campaign: + def passing_in(self, workspace: Workspace) -> probes_campaign.Campaign: workspace.put_game() - host = campaign.Host(loadavg=lambda: (0.0, 0.0, 0.0), free_gb=lambda path: 500.0, + host = probes_host.Host(loadavg=lambda: (0.0, 0.0, 0.0), free_gb=lambda path: 500.0, cpu_count=1_000_000) - c = campaign.Campaign(workspace.paths, campaign.Settings( + c = probes_campaign.Campaign(workspace.paths, probes_host.Settings( check_repeat=2, probe_timeout=30, delays=(1,), echo=False), host, lock_path=workspace.tmp / "auto.lock") so = self.cores["hle"] - c.unit_cores = lambda *a, **k: [campaign.Core("fake", so, campaign.file_sha256(so))] + c.unit_cores = lambda *a, **k: [cores.Core("fake", so, probes_host.file_sha256(so))] return c def test_missing_content_leaves_the_checks_pending(self) -> None: diff --git a/tests/test_layers.py b/tests/test_layers.py index d339a0e90..be401b224 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -41,15 +41,24 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # Top-level modules other modules of scripts/ import: library code that a # later wave moves into a package. NOT_YET_PACKAGED = frozenset({ - "autorun", "build_port", "campaign", - "check_buildbot_system", "check_release_assets", "commit_rules", "core_probe", + "autorun", "build_port", + "check_buildbot_system", "check_release_assets", "commit_rules", "generate_event_schema", "pin_installer", "pr_checks", "release_record", "romfolders", }) +# Top-level files that stay whole at their path although packages import them: +# the file is the unit. core_probe.py runs alone in its sandbox, where nothing +# beside the standard library exists, and its records name and hash this file. +SELF_CONTAINED = frozenset({"core_probe"}) + # Imports from a package module to a top-level module, left for the wave that # packages the top-level side. PENDING_TOP_LEVEL_IMPORTS = frozenset({ + # autorun, the job runner, keeps its git helpers, which raise its own error. + ("probes.campaign", "autorun"), + ("probes.gate", "autorun"), + ("probes.host", "autorun"), ("sitegen.build", "release_record"), ("sitegen.config", "release_record"), ("sitegen.decorate", "release_record"), @@ -135,7 +144,7 @@ def layer_of(name: str) -> int: top = name.split(".")[0] if "." in name or top in PACKAGE_LAYERS: return PACKAGE_LAYERS[top] - return LIBRARY_LAYER if name in NOT_YET_PACKAGED else COMMAND_LAYER + return LIBRARY_LAYER if name in NOT_YET_PACKAGED | SELF_CONTAINED else COMMAND_LAYER def is_package_module(name: str) -> bool: @@ -218,7 +227,7 @@ class ImportLayers(unittest.TestCase): def test_package_modules_import_no_top_level_module(self): found = {(src, dst) for src, dst in self.graph.edges() - if is_package_module(src) and not is_package_module(dst)} + if is_package_module(src) and not is_package_module(dst) and dst not in SELF_CONTAINED} self.assertEqual(sorted(found - PENDING_TOP_LEVEL_IMPORTS), []) self.assertEqual(sorted(PENDING_TOP_LEVEL_IMPORTS - found), [], "a pending import no longer exists: remove it from the list") @@ -234,8 +243,25 @@ class ImportLayers(unittest.TestCase): if i.split(".")[0] != "core"] self.assertEqual(found, []) + def test_self_contained_files_load_the_standard_library_only(self): + """What a self-contained file imports when it loads is the standard + library: in its sandbox, the file is all of the repository there is.""" + stdlib = set(sys.stdlib_module_names) | {"__future__"} + found = [] + for name in sorted(SELF_CONTAINED): + tree = ast.parse(self.graph.modules[name].read_text(encoding="utf-8")) + for node in tree.body: + if isinstance(node, ast.Import): + found += [f"{name} imports {a.name}" for a in node.names + if a.name.split(".")[0] not in stdlib] + elif isinstance(node, ast.ImportFrom) and (node.level or (node.module or "").split(".")[0] + not in stdlib): + found.append(f"{name} imports from {node.module}") + self.assertEqual(found, []) + def test_not_yet_packaged_is_the_exact_set_of_top_level_libraries(self): - imported = {dst for _src, dst in self.graph.edges() if not is_package_module(dst)} + imported = {dst for _src, dst in self.graph.edges() + if not is_package_module(dst) and dst not in SELF_CONTAINED} self.assertEqual(sorted(imported - NOT_YET_PACKAGED), [], "a top-level module became a library: package it or list it") self.assertEqual(sorted(NOT_YET_PACKAGED - imported), [], diff --git a/tests/test_pack_probe.py b/tests/test_pack_probe.py index e24e9eb74..096308e4c 100644 --- a/tests/test_pack_probe.py +++ b/tests/test_pack_probe.py @@ -25,6 +25,7 @@ from pathlib import Path from model import measurements as mr import pack_probe as pp +from model import profiles as model_profiles REPO_ROOT = Path(__file__).resolve().parent.parent @@ -355,7 +356,7 @@ class RealLayouts(unittest.TestCase): self.assertEqual(set(lay.files), members) self.assertEqual(lay.files["scph5501.bin"], "scph5501.bin") self.assertEqual(lay.source["pack"]["members"], len(members)) - swan = pp.load_emulator_profiles(str(REPO_ROOT / "emulators"))["swanstation"] + swan = model_profiles.load_emulator_profiles(str(REPO_ROOT / "emulators"))["swanstation"] self.assertIn("scph5501.bin", pp.initial_stage(lay, swan, [])) def test_installer_path(self) -> None: