From 4ea44a027e6c19410a40a1d5b245109c8101ed5c Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:04:30 +0100 Subject: [PATCH] refactor: split the region check into probes --- scripts/probes/regioncheck.py | 371 ++++++++++++++++++++++++++++++++++ scripts/region_check.py | 360 +-------------------------------- tests/test_region_check.py | 60 +++--- 3 files changed, 402 insertions(+), 389 deletions(-) create mode 100644 scripts/probes/regioncheck.py diff --git a/scripts/probes/regioncheck.py b/scripts/probes/regioncheck.py new file mode 100644 index 000000000..80426f91b --- /dev/null +++ b/scripts/probes/regioncheck.py @@ -0,0 +1,371 @@ +"""Each regional game under four BIOS sets: full, own region, other regions, pack.""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +import tempfile +import time +import urllib.request +from collections.abc import Callable, Iterable +from pathlib import Path + +import yaml + +from core.paths import REPO_ROOT + + +CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" +CORES = REPO_ROOT / ".cache" / "region" / "cores" +NIGHTLY = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/{core}_libretro.so.zip" +VARIANTS = ("full", "own", "others", "pack") +SUBJECT = re.compile(r"^region-(?P[a-z0-9_]+)-(?P[a-z0-9-]+)-(?Pfull|own|others|pack)$") +# The territory a test game names, as generate_pack --region takes it. +PACK_REGION = {"japan": "jp", "north-america": "us", "europe": "eu"} +REGION_WORDS = {"japan": "Japanese", "north-america": "US", "europe": "European"} + + +# -------------------------------------------------------------------------- +# Pure rules +# -------------------------------------------------------------------------- + +def regions_of(entry: dict) -> list[str]: + regions = entry.get("region") or [] + return [regions] if isinstance(regions, str) else list(regions) + + +def entry_dest(entry: dict) -> str: + path = entry.get("path") + if isinstance(path, str) and path and not path.endswith("/"): + return path + return entry["name"] + + +def region_entries(profile: dict, system: str) -> list[dict]: + """The BIOS entries of a system that a `region:` ties to territories.""" + out = [] + for entry in profile.get("files") or (): + systems = entry.get("systems") or ([entry["system"]] if entry.get("system") + else profile.get("systems") or []) + if (system in systems and regions_of(entry) and "world" not in regions_of(entry) + and entry.get("category", "bios") == "bios" and entry.get("mode") != "standalone"): + out.append(entry) + return out + + +def plan_variants(entries: Iterable[dict], region: str, + local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]: + """The staged files of `full`, `own` and `others`, dest -> file. An entry + the collection does not hold is left out of every variant.""" + held = [(entry, path) for entry in entries if (path := local(entry))] + full = {entry_dest(e): p for e, p in held} + own = {entry_dest(e): p for e, p in held if region in regions_of(e)} + others = {entry_dest(e): p for e, p in held if region not in regions_of(e)} + return {"full": full, "own": own, "others": others} + + +def subject(core: str, game: str, variant: str) -> str: + words = re.findall(r"[a-z0-9]+", game.lower()) + return f"region-{core.lower().replace('-', '_')}-{'-'.join(words)[:60].strip('-')}-{variant}" + + +def opened(record: dict) -> set[str]: + return {item["path"] for variant in record["variants"] for rep in variant["repetitions"] + for item in rep.get("files_opened") or ()} + + +def frames(record: dict) -> list: + rep = record["variants"][0]["repetitions"][0] + return (rep.get("observables") or {}).get("frame_hashes") or [] + + +def verdict(record: dict) -> str: + return record["variants"][0].get("verdict") or "unknown" + + +def outcome(records: dict[str, dict], entries: list[dict], region: str) -> dict: + """What the four records of one game on one core settle. + + `selected` is the regional file the core opened with every one staged. + The `region:` claim is `confirmed` when every regional file it opened + holds the game's region, `contradicted` when none does, `ambiguous` + when it opened its own region's file and others too, `unread` when it + opened none. Each variant's result is its oracle verdict. While no + reference frame is known for the game, a variant that samples the same + frames as the full run (`as_full`) boots, and one that does not stays + without an answer: frames that differ never make a verdict. + """ + by_dest = {entry_dest(e): e for e in entries} + full = records.get("full") + selected = sorted(opened(full) & set(by_dest)) if full else [] + if not full: + claim = "unrun" + elif not selected: + claim = "unread" + elif all(region in regions_of(by_dest[d]) for d in selected): + claim = "confirmed" + elif any(region in regions_of(by_dest[d]) for d in selected): + # Opened every region's file, to hash them or to choose: the open + # alone does not say which one the core runs. + claim = "ambiguous" + else: + claim = "contradicted" + results: dict[str, dict] = {} + for label in VARIANTS: + record = records.get(label) + if not record: + continue + loaded = all(rep.get("loaded") for v in record["variants"] for rep in v["repetitions"]) + item = {"record": record["id"], "verdict": verdict(record), "loaded": loaded, + "staged": sorted(record["variants"][0]["system_files"]), + "bios_used": record["variants"][0].get("bios_used", "unknown")} + if full and label != "full": + item["as_full"] = loaded and frames(record) == frames(full) + results[label] = item + + full_verdict = verdict(full) if full else None + + def boots(label: str) -> bool | None: + item = results.get(label) + if not item: + return None + if item["verdict"] != "unknown": + return item["verdict"] == "boots" + # No verdict: the interim rule. The same frames as the full run is a + # boot, while the full run itself is not shown to fail. Other frames + # say nothing: the US disc reaches its game on the Japanese and + # European BIOS through another licence screen. + if full_verdict in ("boots", "unknown") and item.get("as_full"): + return True + return None + + return { + "region": region, + "selected": [by_dest[d]["name"] for d in selected], + "claim": claim, + "variants": results, + "own_boots": boots("own"), + "others_boot": boots("others"), + "pack_boots": boots("pack"), + # The BIOS each ran, from its log: a boot is not the staged file's + # until the log names it (core_probe.bios_used). + "own_on": (results.get("own") or {}).get("bios_used", "unknown"), + "others_on": (results.get("others") or {}).get("bios_used", "unknown"), + "judged_by": "verdict" if full_verdict not in (None, "unknown") else "full_run_frames", + } + + +BUILTIN = "builtin" + + +def staged_name(used: str | None) -> str | None: + """The file a bios_used names, or None.""" + return used.removeprefix("staged:") if used and used.startswith("staged:") else None + + +def sentence(game_region: str, result: dict) -> str: + """The outcome in words, for the site. A boot is said to be another + region's BIOS only when the core's log names that file: a core that + refuses the staged files and runs its own BIOS (OpenBIOS, HLE) boots + too, on that built-in BIOS.""" + word = REGION_WORDS.get(game_region, game_region) + own, others = result.get("own_boots"), result.get("others_boot") + if own is None: + return f"The {word} game has no run with its own BIOS yet." + if own and result.get("own_on") == BUILTIN: + first = f"The {word} game boots on the core's built-in BIOS, its own BIOS file was refused" + else: + first = f"The {word} BIOS {'boots' if own else 'does not boot'} the {word} game" + if others is None: + return first + ". The other regions' BIOS have no verdict yet." + if not others: + return first + ", the other regions' BIOS do not." + used = result.get("others_on") + if used == BUILTIN: + return first + ", and on its built-in BIOS with the others' files refused." + name = staged_name(used) + if name: + return first + f", and so does {name}, another region's BIOS." + return first + ", and with the others' files on a BIOS its log does not name." + + +# -------------------------------------------------------------------------- +# Runs +# -------------------------------------------------------------------------- + +def load_content(path: Path = CONTENT_FILE) -> dict[str, list[dict]]: + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + out: dict[str, list[dict]] = {} + for system, spec in (data.get("systems") or {}).items(): + for item in spec.get("content") or (): + out.setdefault(system, []).append({**item, "romfetch": spec["romfetch"]}) + return out + + +def content_file(item: dict, content_dir: Path) -> Path: + folder = content_dir / item["romfetch"] / item["name"] + if item.get("load") == "cue": + cues = sorted(folder.glob("*.cue")) + if len(cues) != 1: + raise FileNotFoundError(f"{folder}: {len(cues)} .cue files, one expected") + return cues[0] + if item.get("load"): + return folder / item["load"] + files = [p for p in sorted(folder.iterdir()) if p.is_file() and p.name != "identity.json"] + if len(files) != 1: + raise FileNotFoundError(f"{folder}: {len(files)} files, name one with load:") + return files[0] + + +def nightly_core(core: str) -> tuple[Path, str]: + """The buildbot nightly of a core, downloaded once, and its URL.""" + import zipfile + + url = NIGHTLY.format(core=core) + target = CORES / f"{core}_libretro.so" + if not target.is_file(): + CORES.mkdir(parents=True, exist_ok=True) + archive = CORES / f"{core}.zip" + with urllib.request.urlopen(url, timeout=300) as response, archive.open("wb") as out: + out.write(response.read()) + with zipfile.ZipFile(archive) as handle: + member = f"{core}_libretro.so" + if member not in handle.namelist(): + raise FileNotFoundError(f"{archive.name}: no {member} inside") + partial = target.with_suffix(".part") + partial.write_bytes(handle.read(member)) + partial.replace(target) + archive.unlink() + return target, url + + +def pack_files(emulator: str, region: str, work: Path) -> dict[str, Path]: + """The files generate_pack puts in the emulator's pack for one region, + extracted, by their path in the pack.""" + from core.ziptools import safe_extract_zip + + out_dir = work / "pack" + subprocess.run([sys.executable, str(REPO_ROOT / "scripts" / "generate_pack.py"), "--emulator", emulator, + "--region", PACK_REGION[region], "--output-dir", str(out_dir)], + cwd=REPO_ROOT, check=True, capture_output=True, text=True) + zips = sorted(out_dir.glob("*.zip")) + if len(zips) != 1: + raise FileNotFoundError(f"{out_dir}: {len(zips)} packs, one expected") + tree = work / "pack-tree" + safe_extract_zip(str(zips[0]), str(tree)) + return {p.relative_to(tree).as_posix(): p for p in sorted(tree.rglob("*")) if p.is_file() + and not p.name.upper().startswith("README")} + + +def local_resolver() -> Callable[[dict], Path | None]: + from model.database import load_database + from resolve.localfile import resolve_local_file + + db = load_database(str(REPO_ROOT / "database.json")) + + def local(entry: dict) -> Path | None: + hint = entry.get("path") if isinstance(entry.get("path"), str) else "" + path, status = resolve_local_file(entry, db, dest_hint=hint or "") + if not path or status in ("not_found", "hash_mismatch"): + return None + found = Path(path) if Path(path).is_absolute() else REPO_ROOT / path + return found if found.is_file() else None + + return local + + +BUSY = 3 # core_probe's exit status when it refuses to record on a busy host +POLL_S = 15 + + +def probe_when_idle(argv: list[str], max_wait: float, + clock: Callable[[], float] = time.monotonic, + pause: Callable[[float], None] = time.sleep, + runner: Callable[..., subprocess.CompletedProcess] = subprocess.run + ) -> subprocess.CompletedProcess: + """core_probe, run again while it refuses a busy host, as the campaign + does: every POLL_S seconds until max_wait seconds have passed. The load + threshold stays core_probe's own.""" + started = clock() + while True: + proc = runner(argv, cwd=REPO_ROOT, capture_output=True, text=True) + if proc.returncode != BUSY or clock() - started >= max_wait: + return proc + pause(POLL_S) + + +def run(args: argparse.Namespace) -> int: + from model.profiles import load_emulator_profiles + + profile = load_emulator_profiles(str(REPO_ROOT / "emulators"))[args.emulator] + entries = region_entries(profile, args.system) + if not entries: + print(f"ERROR: {args.emulator} declares no regional BIOS for {args.system}", file=sys.stderr) + return 2 + games = [g for g in load_content().get(args.system, []) if g.get("region") in PACK_REGION] + if not games: + print(f"ERROR: content.yml has no regional game for {args.system}", file=sys.stderr) + return 2 + core, url = (Path(args.core), args.core_artifact) if args.core else nightly_core(args.core_name) + local = local_resolver() + failures = 0 + for game in games: + load = content_file(game, Path(args.content_dir)) + with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as scratch: + variants = plan_variants(entries, game["region"], local) + variants["pack"] = pack_files(args.emulator, game["region"], Path(scratch)) + for label in args.variants or VARIANTS: + argv = [sys.executable, str(REPO_ROOT / "scripts" / "core_probe.py"), "run", + "--core", str(core), "--content", str(load), "--content-label", game["name"], + "--frames", str(game.get("frames", 3600)), + "--frame-hash-every", str(game.get("frame_hash_every", 10)), + "--record", str(REPO_ROOT), "--emulator", args.emulator, + "--subject", subject(core.name.removesuffix("_libretro.so"), game["name"], label), + "--require-sandbox", "--timeout", str(args.timeout)] + if url: + argv += ["--core-artifact", url] + for dest, src in sorted(variants[label].items()): + argv += ["--system-file", f"{dest}={src}"] + proc = probe_when_idle(argv, args.max_load_wait) + status = "recorded" if proc.returncode == 0 else f"exit {proc.returncode}" + print(json.dumps({"game": game["name"], "variant": label, "status": status, + "error": proc.stderr.strip()[-400:] if proc.returncode else None}), + flush=True) + failures += proc.returncode != 0 + return 1 if failures else 0 + + +def collect(root: Path = REPO_ROOT, stored_records: list | None = None) -> list[dict]: + """Every region outcome the records under measurements/ hold. A game + listed under several systems (sega-megacd and mega-cd) is judged under + the one whose profile ran it.""" + from model.profiles import load_emulator_profiles + from model.measurements import live, read_records + + content: dict[str, list[tuple[str, dict]]] = {} + for system, items in load_content(root / "tests" / "campaign" / "content.yml").items(): + for item in items: + content.setdefault(item["name"], []).append((system, item)) + profiles = load_emulator_profiles(str(root / "emulators")) + groups: dict[tuple[str, str, str], dict[str, dict]] = {} + for stored in read_records(root) if stored_records is None else stored_records: + match = SUBJECT.match(stored.record.get("subject", "")) + label = ((stored.record.get("inputs") or {}).get("content") or {}).get("label") + if not match or label not in content: + continue + key = (stored.emulator, match["core"], label) + groups.setdefault(key, {})[match["variant"]] = stored.record + out = [] + for (emulator, core, game), records in sorted(groups.items()): + records = {k: v for k, v in records.items() if v["id"] in {r["id"] for r in live(records.values())}} + profile = profiles.get(emulator, {}) + system, item = next(((s, i) for s, i in content[game] if s in (profile.get("systems") or ())), + content[game][0]) + entries = region_entries(profile, system) + result = outcome(records, entries, item["region"]) + out.append({"emulator": emulator, "core": core, "system": system, "game": game, **result, + "sentence": sentence(item["region"], result)}) + return out diff --git a/scripts/region_check.py b/scripts/region_check.py index 6d6e6b601..04595582d 100644 --- a/scripts/region_check.py +++ b/scripts/region_check.py @@ -27,13 +27,7 @@ from __future__ import annotations import argparse import json -import re -import subprocess import sys -import tempfile -import time -import urllib.request -from collections.abc import Callable, Iterable from pathlib import Path # The probe tools do not import core/cli.py, which states the 3.9 floor for the @@ -46,360 +40,8 @@ if sys.version_info < (3, 9): sys.path.insert(0, str(Path(__file__).resolve().parent)) -import yaml from core.paths import REPO_ROOT - -CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "content.yml" -CORES = REPO_ROOT / ".cache" / "region" / "cores" -NIGHTLY = "https://buildbot.libretro.com/nightly/linux/x86_64/latest/{core}_libretro.so.zip" -VARIANTS = ("full", "own", "others", "pack") -SUBJECT = re.compile(r"^region-(?P[a-z0-9_]+)-(?P[a-z0-9-]+)-(?Pfull|own|others|pack)$") -# The territory a test game names, as generate_pack --region takes it. -PACK_REGION = {"japan": "jp", "north-america": "us", "europe": "eu"} -REGION_WORDS = {"japan": "Japanese", "north-america": "US", "europe": "European"} - - -# -------------------------------------------------------------------------- -# Pure rules -# -------------------------------------------------------------------------- - -def regions_of(entry: dict) -> list[str]: - regions = entry.get("region") or [] - return [regions] if isinstance(regions, str) else list(regions) - - -def entry_dest(entry: dict) -> str: - path = entry.get("path") - if isinstance(path, str) and path and not path.endswith("/"): - return path - return entry["name"] - - -def region_entries(profile: dict, system: str) -> list[dict]: - """The BIOS entries of a system that a `region:` ties to territories.""" - out = [] - for entry in profile.get("files") or (): - systems = entry.get("systems") or ([entry["system"]] if entry.get("system") - else profile.get("systems") or []) - if (system in systems and regions_of(entry) and "world" not in regions_of(entry) - and entry.get("category", "bios") == "bios" and entry.get("mode") != "standalone"): - out.append(entry) - return out - - -def plan_variants(entries: Iterable[dict], region: str, - local: Callable[[dict], Path | None]) -> dict[str, dict[str, Path]]: - """The staged files of `full`, `own` and `others`, dest -> file. An entry - the collection does not hold is left out of every variant.""" - held = [(entry, path) for entry in entries if (path := local(entry))] - full = {entry_dest(e): p for e, p in held} - own = {entry_dest(e): p for e, p in held if region in regions_of(e)} - others = {entry_dest(e): p for e, p in held if region not in regions_of(e)} - return {"full": full, "own": own, "others": others} - - -def subject(core: str, game: str, variant: str) -> str: - words = re.findall(r"[a-z0-9]+", game.lower()) - return f"region-{core.lower().replace('-', '_')}-{'-'.join(words)[:60].strip('-')}-{variant}" - - -def opened(record: dict) -> set[str]: - return {item["path"] for variant in record["variants"] for rep in variant["repetitions"] - for item in rep.get("files_opened") or ()} - - -def frames(record: dict) -> list: - rep = record["variants"][0]["repetitions"][0] - return (rep.get("observables") or {}).get("frame_hashes") or [] - - -def verdict(record: dict) -> str: - return record["variants"][0].get("verdict") or "unknown" - - -def outcome(records: dict[str, dict], entries: list[dict], region: str) -> dict: - """What the four records of one game on one core settle. - - `selected` is the regional file the core opened with every one staged. - The `region:` claim is `confirmed` when every regional file it opened - holds the game's region, `contradicted` when none does, `ambiguous` - when it opened its own region's file and others too, `unread` when it - opened none. Each variant's result is its oracle verdict. While no - reference frame is known for the game, a variant that samples the same - frames as the full run (`as_full`) boots, and one that does not stays - without an answer: frames that differ never make a verdict. - """ - by_dest = {entry_dest(e): e for e in entries} - full = records.get("full") - selected = sorted(opened(full) & set(by_dest)) if full else [] - if not full: - claim = "unrun" - elif not selected: - claim = "unread" - elif all(region in regions_of(by_dest[d]) for d in selected): - claim = "confirmed" - elif any(region in regions_of(by_dest[d]) for d in selected): - # Opened every region's file, to hash them or to choose: the open - # alone does not say which one the core runs. - claim = "ambiguous" - else: - claim = "contradicted" - results: dict[str, dict] = {} - for label in VARIANTS: - record = records.get(label) - if not record: - continue - loaded = all(rep.get("loaded") for v in record["variants"] for rep in v["repetitions"]) - item = {"record": record["id"], "verdict": verdict(record), "loaded": loaded, - "staged": sorted(record["variants"][0]["system_files"]), - "bios_used": record["variants"][0].get("bios_used", "unknown")} - if full and label != "full": - item["as_full"] = loaded and frames(record) == frames(full) - results[label] = item - - full_verdict = verdict(full) if full else None - - def boots(label: str) -> bool | None: - item = results.get(label) - if not item: - return None - if item["verdict"] != "unknown": - return item["verdict"] == "boots" - # No verdict: the interim rule. The same frames as the full run is a - # boot, while the full run itself is not shown to fail. Other frames - # say nothing: the US disc reaches its game on the Japanese and - # European BIOS through another licence screen. - if full_verdict in ("boots", "unknown") and item.get("as_full"): - return True - return None - - return { - "region": region, - "selected": [by_dest[d]["name"] for d in selected], - "claim": claim, - "variants": results, - "own_boots": boots("own"), - "others_boot": boots("others"), - "pack_boots": boots("pack"), - # The BIOS each ran, from its log: a boot is not the staged file's - # until the log names it (core_probe.bios_used). - "own_on": (results.get("own") or {}).get("bios_used", "unknown"), - "others_on": (results.get("others") or {}).get("bios_used", "unknown"), - "judged_by": "verdict" if full_verdict not in (None, "unknown") else "full_run_frames", - } - - -BUILTIN = "builtin" - - -def staged_name(used: str | None) -> str | None: - """The file a bios_used names, or None.""" - return used.removeprefix("staged:") if used and used.startswith("staged:") else None - - -def sentence(game_region: str, result: dict) -> str: - """The outcome in words, for the site. A boot is said to be another - region's BIOS only when the core's log names that file: a core that - refuses the staged files and runs its own BIOS (OpenBIOS, HLE) boots - too, on that built-in BIOS.""" - word = REGION_WORDS.get(game_region, game_region) - own, others = result.get("own_boots"), result.get("others_boot") - if own is None: - return f"The {word} game has no run with its own BIOS yet." - if own and result.get("own_on") == BUILTIN: - first = f"The {word} game boots on the core's built-in BIOS, its own BIOS file was refused" - else: - first = f"The {word} BIOS {'boots' if own else 'does not boot'} the {word} game" - if others is None: - return first + ". The other regions' BIOS have no verdict yet." - if not others: - return first + ", the other regions' BIOS do not." - used = result.get("others_on") - if used == BUILTIN: - return first + ", and on its built-in BIOS with the others' files refused." - name = staged_name(used) - if name: - return first + f", and so does {name}, another region's BIOS." - return first + ", and with the others' files on a BIOS its log does not name." - - -# -------------------------------------------------------------------------- -# Runs -# -------------------------------------------------------------------------- - -def load_content(path: Path = CONTENT_FILE) -> dict[str, list[dict]]: - data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - out: dict[str, list[dict]] = {} - for system, spec in (data.get("systems") or {}).items(): - for item in spec.get("content") or (): - out.setdefault(system, []).append({**item, "romfetch": spec["romfetch"]}) - return out - - -def content_file(item: dict, content_dir: Path) -> Path: - folder = content_dir / item["romfetch"] / item["name"] - if item.get("load") == "cue": - cues = sorted(folder.glob("*.cue")) - if len(cues) != 1: - raise FileNotFoundError(f"{folder}: {len(cues)} .cue files, one expected") - return cues[0] - if item.get("load"): - return folder / item["load"] - files = [p for p in sorted(folder.iterdir()) if p.is_file() and p.name != "identity.json"] - if len(files) != 1: - raise FileNotFoundError(f"{folder}: {len(files)} files, name one with load:") - return files[0] - - -def nightly_core(core: str) -> tuple[Path, str]: - """The buildbot nightly of a core, downloaded once, and its URL.""" - import zipfile - - url = NIGHTLY.format(core=core) - target = CORES / f"{core}_libretro.so" - if not target.is_file(): - CORES.mkdir(parents=True, exist_ok=True) - archive = CORES / f"{core}.zip" - with urllib.request.urlopen(url, timeout=300) as response, archive.open("wb") as out: - out.write(response.read()) - with zipfile.ZipFile(archive) as handle: - member = f"{core}_libretro.so" - if member not in handle.namelist(): - raise FileNotFoundError(f"{archive.name}: no {member} inside") - partial = target.with_suffix(".part") - partial.write_bytes(handle.read(member)) - partial.replace(target) - archive.unlink() - return target, url - - -def pack_files(emulator: str, region: str, work: Path) -> dict[str, Path]: - """The files generate_pack puts in the emulator's pack for one region, - extracted, by their path in the pack.""" - from core.ziptools import safe_extract_zip - - out_dir = work / "pack" - subprocess.run([sys.executable, str(REPO_ROOT / "scripts" / "generate_pack.py"), "--emulator", emulator, - "--region", PACK_REGION[region], "--output-dir", str(out_dir)], - cwd=REPO_ROOT, check=True, capture_output=True, text=True) - zips = sorted(out_dir.glob("*.zip")) - if len(zips) != 1: - raise FileNotFoundError(f"{out_dir}: {len(zips)} packs, one expected") - tree = work / "pack-tree" - safe_extract_zip(str(zips[0]), str(tree)) - return {p.relative_to(tree).as_posix(): p for p in sorted(tree.rglob("*")) if p.is_file() - and not p.name.upper().startswith("README")} - - -def local_resolver() -> Callable[[dict], Path | None]: - from model.database import load_database - from resolve.localfile import resolve_local_file - - db = load_database(str(REPO_ROOT / "database.json")) - - def local(entry: dict) -> Path | None: - hint = entry.get("path") if isinstance(entry.get("path"), str) else "" - path, status = resolve_local_file(entry, db, dest_hint=hint or "") - if not path or status in ("not_found", "hash_mismatch"): - return None - found = Path(path) if Path(path).is_absolute() else REPO_ROOT / path - return found if found.is_file() else None - - return local - - -BUSY = 3 # core_probe's exit status when it refuses to record on a busy host -POLL_S = 15 - - -def probe_when_idle(argv: list[str], max_wait: float, - clock: Callable[[], float] = time.monotonic, - pause: Callable[[float], None] = time.sleep, - runner: Callable[..., subprocess.CompletedProcess] = subprocess.run - ) -> subprocess.CompletedProcess: - """core_probe, run again while it refuses a busy host, as the campaign - does: every POLL_S seconds until max_wait seconds have passed. The load - threshold stays core_probe's own.""" - started = clock() - while True: - proc = runner(argv, cwd=REPO_ROOT, capture_output=True, text=True) - if proc.returncode != BUSY or clock() - started >= max_wait: - return proc - pause(POLL_S) - - -def run(args: argparse.Namespace) -> int: - from model.profiles import load_emulator_profiles - - profile = load_emulator_profiles(str(REPO_ROOT / "emulators"))[args.emulator] - entries = region_entries(profile, args.system) - if not entries: - print(f"ERROR: {args.emulator} declares no regional BIOS for {args.system}", file=sys.stderr) - return 2 - games = [g for g in load_content().get(args.system, []) if g.get("region") in PACK_REGION] - if not games: - print(f"ERROR: content.yml has no regional game for {args.system}", file=sys.stderr) - return 2 - core, url = (Path(args.core), args.core_artifact) if args.core else nightly_core(args.core_name) - local = local_resolver() - failures = 0 - for game in games: - load = content_file(game, Path(args.content_dir)) - with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as scratch: - variants = plan_variants(entries, game["region"], local) - variants["pack"] = pack_files(args.emulator, game["region"], Path(scratch)) - for label in args.variants or VARIANTS: - argv = [sys.executable, str(REPO_ROOT / "scripts" / "core_probe.py"), "run", - "--core", str(core), "--content", str(load), "--content-label", game["name"], - "--frames", str(game.get("frames", 3600)), - "--frame-hash-every", str(game.get("frame_hash_every", 10)), - "--record", str(REPO_ROOT), "--emulator", args.emulator, - "--subject", subject(core.name.removesuffix("_libretro.so"), game["name"], label), - "--require-sandbox", "--timeout", str(args.timeout)] - if url: - argv += ["--core-artifact", url] - for dest, src in sorted(variants[label].items()): - argv += ["--system-file", f"{dest}={src}"] - proc = probe_when_idle(argv, args.max_load_wait) - status = "recorded" if proc.returncode == 0 else f"exit {proc.returncode}" - print(json.dumps({"game": game["name"], "variant": label, "status": status, - "error": proc.stderr.strip()[-400:] if proc.returncode else None}), - flush=True) - failures += proc.returncode != 0 - return 1 if failures else 0 - - -def collect(root: Path = REPO_ROOT, stored_records: list | None = None) -> list[dict]: - """Every region outcome the records under measurements/ hold. A game - listed under several systems (sega-megacd and mega-cd) is judged under - the one whose profile ran it.""" - from model.profiles import load_emulator_profiles - from model.measurements import live, read_records - - content: dict[str, list[tuple[str, dict]]] = {} - for system, items in load_content(root / "tests" / "campaign" / "content.yml").items(): - for item in items: - content.setdefault(item["name"], []).append((system, item)) - profiles = load_emulator_profiles(str(root / "emulators")) - groups: dict[tuple[str, str, str], dict[str, dict]] = {} - for stored in read_records(root) if stored_records is None else stored_records: - match = SUBJECT.match(stored.record.get("subject", "")) - label = ((stored.record.get("inputs") or {}).get("content") or {}).get("label") - if not match or label not in content: - continue - key = (stored.emulator, match["core"], label) - groups.setdefault(key, {})[match["variant"]] = stored.record - out = [] - for (emulator, core, game), records in sorted(groups.items()): - records = {k: v for k, v in records.items() if v["id"] in {r["id"] for r in live(records.values())}} - profile = profiles.get(emulator, {}) - system, item = next(((s, i) for s, i in content[game] if s in (profile.get("systems") or ())), - content[game][0]) - entries = region_entries(profile, system) - result = outcome(records, entries, item["region"]) - out.append({"emulator": emulator, "core": core, "system": system, "game": game, **result, - "sentence": sentence(item["region"], result)}) - return out +from probes.regioncheck import VARIANTS, collect, run def main(argv: list[str] | None = None) -> int: diff --git a/tests/test_region_check.py b/tests/test_region_check.py index 43e0dea93..933dbabc5 100644 --- a/tests/test_region_check.py +++ b/tests/test_region_check.py @@ -8,7 +8,7 @@ import tests import unittest from pathlib import Path -import region_check as rc +from probes import regioncheck ROOT = Path(__file__).resolve().parent.parent @@ -37,27 +37,27 @@ def record(rid: str, staged: list[str], opened: list[str], hashes: list, verdict class Entries(unittest.TestCase): def test_only_regional_bios_of_the_system_in_the_libretro_build(self) -> None: - names = [e["name"] for e in rc.region_entries(PROFILE, "sony-playstation")] + names = [e["name"] for e in regioncheck.region_entries(PROFILE, "sony-playstation")] self.assertEqual(names, ["scph5500.bin", "scph5501.bin", "scph5502.bin"]) def test_variants_split_by_the_game_region(self) -> None: - entries = rc.region_entries(PROFILE, "sony-playstation") - plan = rc.plan_variants(entries, "japan", lambda e: Path("/bios") / e["name"]) + entries = regioncheck.region_entries(PROFILE, "sony-playstation") + plan = regioncheck.plan_variants(entries, "japan", lambda e: Path("/bios") / e["name"]) self.assertEqual(sorted(plan["full"]), ["scph5500.bin", "scph5501.bin", "scph5502.bin"]) self.assertEqual(sorted(plan["own"]), ["scph5500.bin"]) self.assertEqual(sorted(plan["others"]), ["scph5501.bin", "scph5502.bin"]) def test_a_file_the_collection_lacks_is_in_no_variant(self) -> None: - entries = rc.region_entries(PROFILE, "sony-playstation") - plan = rc.plan_variants(entries, "europe", + entries = regioncheck.region_entries(PROFILE, "sony-playstation") + plan = regioncheck.plan_variants(entries, "europe", lambda e: None if e["name"] == "scph5502.bin" else Path(e["name"])) self.assertEqual(plan["own"], {}) self.assertNotIn("scph5502.bin", plan["full"]) def test_subject_names_core_game_and_variant(self) -> None: - slug = rc.subject("mednafen_psx", "Puzzle Bobble 2 (Japan)", "own") + slug = regioncheck.subject("mednafen_psx", "Puzzle Bobble 2 (Japan)", "own") self.assertEqual(slug, "region-mednafen_psx-puzzle-bobble-2-japan-own") - self.assertRegex(slug, rc.SUBJECT) + self.assertRegex(slug, regioncheck.SUBJECT) class BusyHost(unittest.TestCase): @@ -74,23 +74,23 @@ class BusyHost(unittest.TestCase): def pause(seconds: float) -> None: now[0] += seconds - proc = rc.probe_when_idle(["probe"], max_wait, clock=lambda: now[0], pause=pause, runner=runner) + proc = regioncheck.probe_when_idle(["probe"], max_wait, clock=lambda: now[0], pause=pause, runner=runner) return proc.returncode, len(calls) def test_a_refused_run_is_tried_again_once_the_host_settles(self) -> None: - self.assertEqual(self._run([rc.BUSY, rc.BUSY, 0], 600), (0, 3)) + self.assertEqual(self._run([regioncheck.BUSY, regioncheck.BUSY, 0], 600), (0, 3)) def test_it_gives_up_after_the_wait(self) -> None: - code, calls = self._run([rc.BUSY], 60) - self.assertEqual(code, rc.BUSY) - self.assertEqual(calls, 60 // rc.POLL_S + 1) + code, calls = self._run([regioncheck.BUSY], 60) + self.assertEqual(code, regioncheck.BUSY) + self.assertEqual(calls, 60 // regioncheck.POLL_S + 1) def test_another_failure_is_not_retried(self) -> None: self.assertEqual(self._run([1, 0], 600), (1, 1)) class Outcome(unittest.TestCase): - ENTRIES = rc.region_entries(PROFILE, "sony-playstation") + ENTRIES = regioncheck.region_entries(PROFILE, "sony-playstation") ALL = ["scph5500.bin", "scph5501.bin", "scph5502.bin"] def test_locked_bios_by_verdict(self) -> None: @@ -100,13 +100,13 @@ class Outcome(unittest.TestCase): "others": record("x", self.ALL[1:], [], [[0, "b"]], "bios_error", loaded=False), "pack": record("p", ["scph5500.bin"], ["scph5500.bin"], [[0, "a"]], "boots"), } - result = rc.outcome(records, self.ENTRIES, "japan") + result = regioncheck.outcome(records, self.ENTRIES, "japan") self.assertEqual(result["selected"], ["scph5500.bin"]) self.assertEqual(result["claim"], "confirmed") self.assertEqual((result["own_boots"], result["others_boot"], result["pack_boots"]), (True, False, True)) self.assertEqual(result["judged_by"], "verdict") - self.assertEqual(rc.sentence("japan", result), + self.assertEqual(regioncheck.sentence("japan", result), "The Japanese BIOS boots the Japanese game, the other regions' BIOS do not.") def test_interim_rule_counts_the_same_frames_as_a_boot_and_nothing_else(self) -> None: @@ -115,44 +115,44 @@ class Outcome(unittest.TestCase): "own": record("o", ["scph5501.bin"], ["scph5501.bin"], [[0, "a"], [10, "b"]]), "others": record("x", ["scph5500.bin", "scph5502.bin"], ["scph5500.bin"], [[0, "a"], [10, "c"]]), } - result = rc.outcome(records, self.ENTRIES, "north-america") + result = regioncheck.outcome(records, self.ENTRIES, "north-america") self.assertEqual(result["judged_by"], "full_run_frames") self.assertTrue(result["own_boots"]) # Other frames are no verdict: a US disc reaches its game on the # Japanese BIOS through another licence screen. self.assertIsNone(result["others_boot"]) self.assertIsNone(result["pack_boots"]) - self.assertEqual(rc.sentence("north-america", result), + self.assertEqual(regioncheck.sentence("north-america", result), "The US BIOS boots the US game. The other regions' BIOS have no verdict yet.") def test_no_interim_answer_when_the_full_run_fails(self) -> None: records = {"full": record("f", self.ALL, [], [[0, "a"]], "bios_error"), "own": record("o", ["scph5502.bin"], [], [[0, "a"]])} - result = rc.outcome(records, self.ENTRIES, "europe") + result = regioncheck.outcome(records, self.ENTRIES, "europe") self.assertIsNone(result["own_boots"]) self.assertEqual(result["claim"], "unread") def test_a_core_reading_another_region_contradicts_the_claim(self) -> None: records = {"full": record("f", self.ALL, ["scph5501.bin"], [[0, "a"]], "boots")} - self.assertEqual(rc.outcome(records, self.ENTRIES, "japan")["claim"], "contradicted") + self.assertEqual(regioncheck.outcome(records, self.ENTRIES, "japan")["claim"], "contradicted") def test_a_core_opening_every_region_file_settles_nothing(self) -> None: """PCSX-ReARMed opens the three regional files whatever the disc.""" records = {"full": record("f", self.ALL, self.ALL, [[0, "a"]], "boots")} - self.assertEqual(rc.outcome(records, self.ENTRIES, "japan")["claim"], "ambiguous") + self.assertEqual(regioncheck.outcome(records, self.ENTRIES, "japan")["claim"], "ambiguous") def test_region_free_bios(self) -> None: records = {"full": record("f", self.ALL, ["scph5501.bin"], [[0, "a"]], "boots"), "own": record("o", ["scph5502.bin"], [], [[0, "a"]], "boots"), "others": record("x", ["scph5501.bin"], ["scph5501.bin"], [[0, "a"]], "boots")} - result = rc.outcome(records, self.ENTRIES, "europe") + result = regioncheck.outcome(records, self.ENTRIES, "europe") # The log names no BIOS: the boot is not said to be the other region's. - self.assertEqual(rc.sentence("europe", result), + self.assertEqual(regioncheck.sentence("europe", result), "The European BIOS boots the European game, and with the others' files on a " "BIOS its log does not name.") records["others"] = record("x", ["scph5501.bin"], ["scph5501.bin"], [[0, "a"]], "boots", bios_used="staged:scph5501.bin") - self.assertEqual(rc.sentence("europe", rc.outcome(records, self.ENTRIES, "europe")), + self.assertEqual(regioncheck.sentence("europe", regioncheck.outcome(records, self.ENTRIES, "europe")), "The European BIOS boots the European game, and so does scph5501.bin, " "another region's BIOS.") @@ -165,14 +165,14 @@ class Outcome(unittest.TestCase): bios_used="staged:scph5501.bin"), "others": record("x", ["scph5500.bin", "scph5502.bin"], ["scph5500.bin", "scph5502.bin"], [[0, "a"]], "boots", bios_used="builtin")} - result = rc.outcome(records, self.ENTRIES, "north-america") - text = rc.sentence("north-america", result) + result = regioncheck.outcome(records, self.ENTRIES, "north-america") + text = regioncheck.sentence("north-america", result) self.assertEqual(text, "The US BIOS boots the US game, and on its built-in BIOS with the " "others' files refused.") self.assertNotIn("so do the other regions", text) def test_no_own_run(self) -> None: - self.assertEqual(rc.sentence("japan", rc.outcome({}, self.ENTRIES, "japan")), + self.assertEqual(regioncheck.sentence("japan", regioncheck.outcome({}, self.ENTRIES, "japan")), "The Japanese game has no run with its own BIOS yet.") @@ -184,14 +184,14 @@ class ContentList(unittest.TestCase): import yaml - data = yaml.safe_load(rc.CONTENT_FILE.read_text(encoding="utf-8")) - content = rc.load_content() + data = yaml.safe_load(regioncheck.CONTENT_FILE.read_text(encoding="utf-8")) + content = regioncheck.load_content() uncovered = data.get("uncovered") or {} profiles = load_emulator_profiles(str(ROOT / "emulators")) regional: set[str] = set() for profile in profiles.values(): for system in profile.get("systems") or (): - regions = {r for e in rc.region_entries(profile, system) for r in rc.regions_of(e)} + regions = {r for e in regioncheck.region_entries(profile, system) for r in regioncheck.regions_of(e)} if {"japan", "north-america", "europe"} <= regions: regional.add(system) for system in sorted(regional):