From 3e55385410623facc2a6f4c12462750ca71489e1 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 16:08:28 +0100 Subject: [PATCH] fix: hash-check region games in the main cache probes.content holds where test games live (content_root, the main checkout's .cache/test-content) and that a game is checked against its identity.json before it runs (ready_folder). campaign, pack_probe and region_check all go through it. region_check ran a game without the identity check and looked for games and cores in the current tree, which a linked worktree does not have. packprobe looked the main checkout up at import, running git: the content root and core cache are now computed when a run needs them. --- scripts/probes/content.py | 25 ++++++++++++-- scripts/probes/host.py | 11 ++++-- scripts/probes/packprobe.py | 21 +++++------- scripts/probes/regioncheck.py | 15 ++++++--- scripts/region_check.py | 3 +- tests/test_pack_probe.py | 13 ++++++++ tests/test_region_check.py | 63 +++++++++++++++++++++++++++++++++++ 7 files changed, 126 insertions(+), 25 deletions(-) diff --git a/scripts/probes/content.py b/scripts/probes/content.py index 29b4e8477..3b523ccc1 100644 --- a/scripts/probes/content.py +++ b/scripts/probes/content.py @@ -18,7 +18,7 @@ import yaml from core.hashing import file_digest from core.statefile import now_iso -from probes.host import NETWORK_DELAYS, Unavailable, child_env, run_group +from probes.host import NETWORK_DELAYS, Unavailable, child_env, main_cache, run_group if TYPE_CHECKING: from probes.campaign import Campaign @@ -101,6 +101,25 @@ def verify_identity(folder: Path) -> dict: return identity +def content_root() -> Path: + """Where romfetch keeps the test games: the main checkout's .cache/test-content.""" + return main_cache() / "test-content" + + +def content_folder(root: Path, content: Content) -> Path: + return root / content.romfetch_system / content.name + + +def ready_folder(content: Content, root: Path, + fetch: Callable[[Content], None] | None = None) -> tuple[Path, dict]: + """The game's folder and its identity, fetched first when absent and a + fetch is given. Unavailable unless every file matches its identity.""" + folder = content_folder(root, content) + if fetch is not None and not (folder / "identity.json").is_file(): + fetch(content) + return folder, verify_identity(folder) + + def folder_size(folder: Path) -> int: return sum(p.stat().st_size for p in folder.rglob("*") if p.is_file()) @@ -155,7 +174,7 @@ class ContentStore: self.verified: set[str] = set() def folder(self, content: Content) -> Path: - return self.c.paths.content / content.romfetch_system / content.name + return content_folder(self.c.paths.content, content) def hold(self, content: Content, user: str) -> None: self.refs.setdefault(content.key, set()).add(user) @@ -170,7 +189,7 @@ class ContentStore: self.fetch(content) entry["fetched_by_campaign"] = True if content.key not in self.verified: - identity = verify_identity(folder) + _, identity = ready_folder(content, self.c.paths.content) entry["identity"] = {"catalog": identity.get("catalog"), "dat": identity.get("dat"), "entry": identity.get("entry")} self.verified.add(content.key) diff --git a/scripts/probes/host.py b/scripts/probes/host.py index fa6274788..ff2c99e9d 100644 --- a/scripts/probes/host.py +++ b/scripts/probes/host.py @@ -184,9 +184,14 @@ class Paths: @classmethod def default(cls) -> Paths: - main = worktree.main_checkout() - return cls(root=REPO_ROOT, home=main / ".cache" / "campaign", - content=main / ".cache" / "test-content", db=REPO_ROOT / DB_FILE) + cache = main_cache() + return cls(root=REPO_ROOT, home=cache / "campaign", + content=cache / "test-content", db=REPO_ROOT / DB_FILE) + + +def main_cache() -> Path: + """The main checkout's .cache, which a linked worktree never holds.""" + return worktree.main_checkout() / ".cache" ROMFETCH_PASSED = ("XDG_CONFIG_HOME", "XDG_CACHE_HOME", "XDG_DATA_HOME") diff --git a/scripts/probes/packprobe.py b/scripts/probes/packprobe.py index 8d69c444a..2386833da 100644 --- a/scripts/probes/packprobe.py +++ b/scripts/probes/packprobe.py @@ -13,7 +13,6 @@ from collections.abc import Iterable, Sequence from dataclasses import dataclass from pathlib import Path -from unattended import worktree from core_probe import (EXIT_BUSY, PROBE_LOCK_ENV, PROBE_LOCK_HELD_ENV, VERDICTS, head_commit, host_probe_lock, probe_lock_path) from core.paths import REPO_ROOT @@ -23,10 +22,10 @@ from model.platforms import load_platform_config from model.profiles import load_emulator_profiles from model.systems import norm_system_id from model.targets import load_target_config -from probes.content import Content, fetch_content, find_romfetch, load_content, load_file, verify_identity +from probes.content import Content, content_root, fetch_content, find_romfetch, load_content, load_file, ready_folder from probes.cores import buildbot_listing, cached_nightly from probes.entries import entry_dest -from probes.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, run_group, run_when_idle +from probes.host import CONTENT_FILE, PROBE_TIMEOUT, Unavailable, main_cache, run_group, run_when_idle from probes.packlayout import ( Layout, ProbeFailure, @@ -41,10 +40,7 @@ from resolve.standalone import standalone_set from resolve.validation import filter_files_by_mode -MAIN = worktree.main_checkout() PACK_CONTENT_FILE = REPO_ROOT / "tests" / "campaign" / "pack_content.yml" -CONTENT_DIR = MAIN / ".cache" / "test-content" -CORE_CACHE = MAIN / ".cache" / "pack-probe" / "cores" MAX_ROUNDS = 6 @@ -230,7 +226,7 @@ def map_run(layout: Layout, staged: set[str], rep: dict, profile: dict) -> tuple def fetch_core(name: str, refresh: bool = False) -> dict: """The buildbot nightly of a core, kept with where and when it came from. refresh asks the buildbot whether a newer build replaced it.""" - return cached_nightly(name, CORE_CACHE / name, check=refresh) + return cached_nightly(name, main_cache() / "pack-probe" / "cores" / name, check=refresh) def load_contents(files: Sequence[Path]) -> dict[str, list[Content]]: @@ -244,14 +240,15 @@ def load_contents(files: Sequence[Path]) -> dict[str, list[Content]]: def content_folder(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: + root = content_root() + + def get(wanted: Content) -> None: romfetch = find_romfetch() if not romfetch: raise Unavailable("romfetch not found") - fetch_content(content, CONTENT_DIR, romfetch) - verify_identity(folder) - return folder + fetch_content(wanted, root, romfetch) + + return ready_folder(content, root, get if fetch else None)[0] # -------------------------------------------------------------------------- diff --git a/scripts/probes/regioncheck.py b/scripts/probes/regioncheck.py index dbc37237e..f4654cb2a 100644 --- a/scripts/probes/regioncheck.py +++ b/scripts/probes/regioncheck.py @@ -14,14 +14,13 @@ from pathlib import Path from core.paths import DB_FILE, REPO_ROOT from model.profiles import entry_system_ids from core_probe import BUILTIN -from probes.content import Content, load_content, load_file +from probes.content import Content, content_root, load_content, load_file, ready_folder from probes.cores import cached_nightly from probes.entries import entry_dest, held_file, regions_of -from probes.host import CONTENT_FILE, run_when_idle +from probes.host import CONTENT_FILE, Unavailable, main_cache, run_when_idle from resolve.validation import read_by_build -CORES = REPO_ROOT / ".cache" / "region" / "cores" 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. @@ -186,7 +185,7 @@ def sentence(game_region: str, result: dict) -> str: def nightly_core(core: str) -> tuple[Path, str]: """The buildbot nightly of a core, downloaded again when the buildbot replaced it, and its URL.""" - record = cached_nightly(core, CORES / core) + record = cached_nightly(core, main_cache() / "region" / "cores" / core) return Path(record["path"]), record["url"] @@ -230,8 +229,14 @@ def run(args: argparse.Namespace) -> int: core, url = (Path(args.core), args.core_artifact) if args.core else nightly_core(args.core_name) local = local_resolver() failures = 0 + root = Path(args.content_dir) if args.content_dir else content_root() for game in games: - load = load_file(Path(args.content_dir) / game.romfetch_system / game.name, game.load) + try: + load = load_file(ready_folder(game, root)[0], game.load) + except Unavailable as exc: + print(f"ERROR: {exc}", file=sys.stderr) + failures += 1 + continue 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)) diff --git a/scripts/region_check.py b/scripts/region_check.py index 04595582d..552e0a771 100644 --- a/scripts/region_check.py +++ b/scripts/region_check.py @@ -40,7 +40,6 @@ if sys.version_info < (3, 9): sys.path.insert(0, str(Path(__file__).resolve().parent)) -from core.paths import REPO_ROOT from probes.regioncheck import VARIANTS, collect, run @@ -53,7 +52,7 @@ def main(argv: list[str] | None = None) -> int: go.add_argument("--core-name", help="buildbot core name, e.g. mednafen_psx (downloads the nightly)") go.add_argument("--core", help="a core .so to use instead of the nightly") go.add_argument("--core-artifact", help="where --core was downloaded from") - go.add_argument("--content-dir", default=str(REPO_ROOT / ".cache" / "test-content"), + go.add_argument("--content-dir", help="where romfetch keeps the test games (default: .cache/test-content)") go.add_argument("--variants", nargs="*", choices=VARIANTS, help="a subset of the four runs") go.add_argument("--timeout", type=int, default=900, help="seconds per run") diff --git a/tests/test_pack_probe.py b/tests/test_pack_probe.py index f12d26ea6..dabfd077d 100644 --- a/tests/test_pack_probe.py +++ b/tests/test_pack_probe.py @@ -67,6 +67,19 @@ def layout(files: dict[str, int], entries: dict[str, str | None] | None = None) sizes=dict(files)) +class ImportDoesNoIO(unittest.TestCase): + def test_import_runs_no_git(self) -> None: + """The main checkout is looked up when a run needs it, never on import: + without git on PATH the module still imports.""" + import subprocess + import sys + + env = {**os.environ, "PATH": "/nonexistent"} + proc = subprocess.run([sys.executable, "-c", "import probes.packprobe, probes.regioncheck"], + cwd=REPO_ROOT / "scripts", env=env, capture_output=True, text=True, check=False) + self.assertEqual(proc.returncode, 0, proc.stderr) + + class CoreChoice(unittest.TestCase): def test_system_ids_compare_normalised(self) -> None: config = {"systems": {"megacd": {}, "psx": {}}} diff --git a/tests/test_region_check.py b/tests/test_region_check.py index 5db4a3509..f034e7401 100644 --- a/tests/test_region_check.py +++ b/tests/test_region_check.py @@ -5,6 +5,7 @@ from __future__ import annotations import tests +import dataclasses import unittest from pathlib import Path @@ -177,6 +178,68 @@ class Outcome(unittest.TestCase): "The Japanese game has no run with its own BIOS yet.") +class ContentChecked(unittest.TestCase): + """A game whose files no longer match romfetch's identity never runs: the + record would blame the BIOS for a defect in the content.""" + + def setUp(self) -> None: + import shutil + import tempfile + + (ROOT / "tmp").mkdir(exist_ok=True) + self.root = Path(tempfile.mkdtemp(dir=ROOT / "tmp")) + self.addCleanup(shutil.rmtree, self.root) + game = regioncheck.load_content(regioncheck.CONTENT_FILE)["sony-playstation"][0] + self.game = dataclasses.replace(game, load="game.bin") + + def write_game(self, data: bytes) -> None: + import hashlib + import json + + folder = self.root / self.game.romfetch_system / self.game.name + folder.mkdir(parents=True) + (folder / "game.bin").write_bytes(data) + (folder / "identity.json").write_text(json.dumps({"status": "verified", "files": [ + {"name": "game.bin", "size": 4, "sha1": hashlib.sha1(b"good").hexdigest()}]}), encoding="utf-8") + + def run_region(self) -> tuple[int, list]: + import argparse + from unittest import mock + + args = argparse.Namespace(emulator="beetle_psx", system="sony-playstation", core="core.so", + core_artifact=None, content_dir=str(self.root), variants=None, + timeout=1, max_load_wait=1) + with mock.patch("model.profiles.load_emulator_profiles", return_value={"beetle_psx": PROFILE}), \ + mock.patch.object(regioncheck, "load_content", + return_value={"sony-playstation": [self.game]}), \ + mock.patch.object(regioncheck, "local_resolver", return_value=lambda e: None), \ + mock.patch.object(regioncheck, "pack_files", return_value={}), \ + mock.patch.object(regioncheck, "run_when_idle") as runs: + runs.return_value.returncode = 0 + code = regioncheck.run(args) + return code, runs.call_args_list + + def test_altered_game_is_refused(self) -> None: + self.write_game(b"bad!") + code, runs = self.run_region() + self.assertEqual((code, runs), (1, [])) + + def test_verified_game_runs(self) -> None: + self.write_game(b"good") + code, runs = self.run_region() + self.assertEqual(code, 0) + self.assertEqual(len(runs), len(regioncheck.VARIANTS)) + + def test_default_content_and_cores_are_the_main_checkout_cache(self) -> None: + """A linked worktree holds no .cache: the default reads the main checkout's.""" + from probes import content + from unattended import worktree + + cache = worktree.main_checkout() / ".cache" + self.assertEqual(content.content_root(), cache / "test-content") + self.assertEqual(host.Paths.default().content, content.content_root()) + + class ContentList(unittest.TestCase): def test_every_region_system_has_a_game_per_region_or_says_why(self) -> None: """A system whose BIOS a profile ties to JP, US and EU has a game for