From a39b1c25f3f810b79e38cc163d075de6478f3f3c Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sun, 22 Nov 2026 02:13:26 +0100 Subject: [PATCH] fix: choose a release asset by one rule resolve_file picked and fetched a release asset in one step, and verify re-derived the choice in pending_release_asset, which refused any record whose size differed from a declared size. fbneo's donpachi, sfz3mix and twotiger samples declare an approximate size with no validation: an online build shipped them while verify reported them missing. release_asset_paths now chooses on the database record under the rules declared_hash_verdict applies to bytes, and both the builder and verify call it. The builder then fetches that revision and holds its bytes to the declaration. --- scripts/packs/coverage.py | 8 +- scripts/packs/emulatorcheck.py | 8 +- scripts/packs/extras.py | 8 +- scripts/resolve/content.py | 37 +++++++++ scripts/resolve/packfiles.py | 131 ++++++++++++------------------- tests/test_audit_regressions.py | 4 +- tests/test_game_data_homonyms.py | 66 ++++++++++++---- 7 files changed, 154 insertions(+), 108 deletions(-) diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 834d2947d..74103973e 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -314,7 +314,7 @@ def _resolve_for_platform( disk and the large-file cache: verify never downloads. A frontend that never reads the bytes takes the filename-free core's own image. """ - from resolve.packfiles import pending_release_asset, resolve_declaration, run_is_offline + from resolve.packfiles import release_asset_paths, resolve_declaration, run_is_offline override = slot_overrides.get( declared_destination(file_entry) @@ -326,9 +326,9 @@ def _resolve_for_platform( if status in ("not_found", "hash_mismatch") and not run_is_offline(): # Not in the cache, and the release holds a copy that answers the # declaration: an online build fetches and packs it (resolve_file). - asset = pending_release_asset(file_entry, db) - if asset: - return asset, RELEASE_ASSET_PENDING + assets = release_asset_paths(file_entry, db) + if assets: + return assets[0], RELEASE_ASSET_PENDING if status == "not_found" and not reads_file_contents(mode): found = agnostic_substitute(file_entry, sys_id, db, platform_profiles) if found: diff --git a/scripts/packs/emulatorcheck.py b/scripts/packs/emulatorcheck.py index 4d501abb9..bb6ad5c84 100644 --- a/scripts/packs/emulatorcheck.py +++ b/scripts/packs/emulatorcheck.py @@ -155,15 +155,15 @@ class _EmulatorPack: content_ids: dict[str, str | None] = field(default_factory=dict) def pending(self, entry: dict, local_path: str | None, status: str) -> tuple[str | None, str]: - from resolve.packfiles import pending_release_asset, run_is_offline + from resolve.packfiles import release_asset_paths, run_is_offline # Read from disk and the cache, as _resolve_for_platform does: a # release asset the cache lacks is fetched by an online build # (generate_emulator_pack resolves with offline=offline). if status in ("not_found", "hash_mismatch") and not run_is_offline(): - asset = pending_release_asset(entry, self.db) - if asset: - return asset, RELEASE_ASSET_PENDING + assets = release_asset_paths(entry, self.db) + if assets: + return assets[0], RELEASE_ASSET_PENDING return local_path, status def content_id(self, path: str | None) -> str | None: diff --git a/scripts/packs/extras.py b/scripts/packs/extras.py index 6f1b7ee0c..4baae0fa3 100644 --- a/scripts/packs/extras.py +++ b/scripts/packs/extras.py @@ -326,7 +326,7 @@ class ExtraResolver: def resolve(self, fe: dict, dest: str) -> tuple[str | None, str, str]: """(local copy or None, resolver status, the core's disagreement).""" - from resolve.packfiles import pending_release_asset, resolve_file, run_is_offline + from resolve.packfiles import release_asset_paths, resolve_file, run_is_offline from resolve.validation import core_size_refusal, validated_choice local_path, status = resolve_file( @@ -340,9 +340,9 @@ class ExtraResolver: ): # The asset the online builder fetches in resolve_file. Its record # answers the declaration, and there are no bytes on disk to check. - asset = pending_release_asset(fe, self.db) - if asset: - return asset, "release_asset", "" + assets = release_asset_paths(fe, self.db) + if assets: + return assets[0], "release_asset", "" if status in ("not_found", "external", "user_provided") or not local_path: return None, status, "" # The cores reading a moved layout's file are found under the diff --git a/scripts/resolve/content.py b/scripts/resolve/content.py index 6b018cb74..9b81b6b8c 100644 --- a/scripts/resolve/content.py +++ b/scripts/resolve/content.py @@ -322,3 +322,40 @@ def declared_hash_verdict( ): return "hash_mismatch" return "data_dir_hash_exact" + + +def record_answers_declaration( + record: dict, file_entry: dict, declared: dict[str, list[str]], +) -> bool: + """Whether a database record carries what declared_hash_verdict asks of the bytes. + + The same rules read without the file: with no hash declared, a size + counts only under ``validation: [size]``, an md5 matches by prefix and + is skipped beside a zipped_file, a crc32 is bounded by the declared + size. What only the bytes tell (the ROM inside a zipped_file, Adler-32, + content tests) is left to declared_hash_verdict once they are there. + """ + size = record.get("size") + if not declared: + return name_match_size_ok(file_entry, size if isinstance(size, int) else None) + + def field(name: str) -> str: + return str(record.get(name, "")).lower() + + if "sha1" in declared and field("sha1") not in declared["sha1"]: + return False + if "sha256" in declared and field("sha256") not in declared["sha256"]: + return False + if "md5" in declared and not file_entry.get("zipped_file") and not any( + field("md5").startswith(expected) for expected in declared["md5"] + ): + return False + if "crc32" in declared: + if field("crc32") not in declared["crc32"]: + return False + declared_size = file_entry.get("size") + if declared_size is not None: + allowed = declared_size if isinstance(declared_size, list) else [declared_size] + if size not in allowed: + return False + return True diff --git a/scripts/resolve/packfiles.py b/scripts/resolve/packfiles.py index c3cdf9c5a..93a6e5f4e 100644 --- a/scripts/resolve/packfiles.py +++ b/scripts/resolve/packfiles.py @@ -15,10 +15,10 @@ from dataclasses import dataclass from pathlib import Path from core import upstream -from model.database import record_at, record_for_hash -from model.largefiles import fetch_large_file +from model.database import record_at, record_for_hash, sha1_at +from model.largefiles import asset_candidates, asset_names, fetch_large_file from core.hashing import declared_hash_lists, file_digest -from resolve.content import declared_hash_verdict +from resolve.content import declared_hash_verdict, record_answers_declaration from resolve.localfile import resolution_is_hash_exact, resolve_local_file from core.paths import REPO_ROOT, declared_destination from core.ziptools import is_archive_path, readable_zip_member_crcs @@ -92,40 +92,25 @@ def download_external( return False return True -def _verified_asset( - name: str, declared: dict[str, list[str]], file_entry: dict, offline: bool -) -> str | None: - """The release asset of that name, if it is a copy the entry accepts. - - The store is asked once per accepted sha1 (or md5), since it keeps one - revision under a name. What it returns is held against every hash the - entry declares, sha256 and crc32 included. - """ - attempts = ( - [(sha1, "") for sha1 in declared.get("sha1", [])] - or [("", md5) for md5 in declared.get("md5", [])] - or [("", "")] +def _fetched_asset(path: str, sha1: str, file_entry: dict, offline: bool) -> str | None: + """The release asset of a registered path, downloaded if allowed and + held to the record's sha1, then to every hash the entry declares.""" + declared = declared_hash_lists(file_entry) + cached = fetch_large_file(path, expected_sha1=sha1, offline=offline) + if not cached: + return None + verdict = declared_hash_verdict( + cached, + has_strong_hash=bool(declared), + sha1_candidates=set(declared.get("sha1", [])), + sha256_candidates=set(declared.get("sha256", [])), + md5_list=declared.get("md5", []), + crc_candidates=set(declared.get("crc32", [])), + zipped_file=file_entry.get("zipped_file"), + declared_size=file_entry.get("size"), + file_entry=file_entry, ) - for sha1, md5 in attempts: - cached = fetch_large_file( - name, expected_sha1=sha1, expected_md5=md5, offline=offline, - ) - if not cached: - continue - verdict = declared_hash_verdict( - cached, - has_strong_hash=bool(declared), - sha1_candidates=set(declared.get("sha1", [])), - sha256_candidates=set(declared.get("sha256", [])), - md5_list=declared.get("md5", []), - crc_candidates=set(declared.get("crc32", [])), - zipped_file=file_entry.get("zipped_file"), - declared_size=file_entry.get("size"), - file_entry=file_entry, - ) - if verdict != "hash_mismatch": - return cached - return None + return None if verdict == "hash_mismatch" else cached def run_is_offline(offline: bool | None = None) -> bool: @@ -136,44 +121,43 @@ def run_is_offline(offline: bool | None = None) -> bool: ) -def pending_release_asset( +def release_asset_paths( file_entry: dict, db: dict, registered: list[str] | None = None, -) -> str | None: - """The release asset an online build fetches for an entry, if one does. +) -> list[str]: + """The registered paths whose release asset answers an entry, best first. - The registered path whose database record carries what the entry - declares, read without a download: verify never fetches, and a release - asset the cache lacks was reported missing while an online build packed - it. ``registered`` is the .gitignore registry (load_registered_paths). + Decided on the database record, without a download: the builder fetches + the first that verifies (resolve_file), and verify, which never fetches, + counts the first as packed. ``registered`` is the .gitignore registry + (load_registered_paths). """ - from model.largefiles import asset_candidates, asset_names, load_registered_paths - name = file_entry.get("name", "") if not name or name.endswith("/") or file_entry.get("type") == "directory": - return None + # The asset store holds files, not trees. + return [] declared = declared_hash_lists(file_entry) if file_entry.get("unsourceable") and not declared: - return None - if file_entry.get("zipped_file") and not declared: - return None + # The asset store is addressed by file name: with no hash to check, + # it would hand back the same-named file of another game, which is + # exactly what the flag forbids. + return [] if registered is None: + # Looked up at call time, so a test's registry patch reaches it. + from model.largefiles import load_registered_paths + registered = load_registered_paths() - assets = set(asset_candidates(name, registered)) - if not assets: - return None - declared_size = file_entry.get("size") - for path, asset in sorted(asset_names(registered).items()): + by_asset: dict[str, str] = {} + for path, asset in asset_names(registered).items(): + by_asset.setdefault(asset, path) + paths: list[str] = [] + for asset in asset_candidates(name, registered): + path = by_asset.get(asset) record = record_at(db, path) - if asset not in assets or record is None: - continue - if isinstance(declared_size, int) and record.get("size") != declared_size: - continue - if all( - str(record.get(field, "")).lower() in values - for field, values in declared.items() + if path and record is not None and path not in paths and ( + record_answers_declaration(record, file_entry, declared) ): - return path - return None + paths.append(path) + return paths def sha1_for_hash(hash_type: str, hash_val: str, db: dict) -> str | None: @@ -261,22 +245,11 @@ def resolve_file( # Large files from GitHub release assets: tried when local file is # missing OR has a hash mismatch (wrong variant on disk) - name = file_entry.get("name", "") - if file_entry.get("type") == "directory" or name.endswith("/"): - # A tree the collection does not hold is missing, as verify says, - # since the asset store holds files, not trees. - return (path, status) if path else (None, "not_found") - declared = declared_hash_lists(file_entry) - if file_entry.get("unsourceable") and not declared: - # The asset store is addressed by file name: with no hash to check, - # it would hand back the same-named file of another game, which is - # exactly what the flag forbids. - return (path, status) if path else (None, "not_found") - cached = _verified_asset( - name, declared, file_entry, run_is_offline(offline), - ) - if cached: - return cached, "release_asset" + for asset_path in release_asset_paths(file_entry, db): + sha1 = sha1_at(db, asset_path) or "" + cached = _fetched_asset(asset_path, sha1, file_entry, run_is_offline(offline)) + if cached: + return cached, "release_asset" # Fall back to hash_mismatch local file if release asset unavailable if path: diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index a049709a5..f03d200be 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -1600,9 +1600,11 @@ class OneBaselineVerdict(unittest.TestCase): "name": "BIG.PUP", "sha1": sha1}}, "indexes": {"by_name": {"BIG.PUP": [sha1]}}} entry = {"name": "BIG.PUP", "sha1": sha1, "destination": "BIG.PUP"} + # The record's path is a registered release asset. + registered = [f"{directory}/absent/BIG.PUP"] with mock.patch.object( packresolve, "fetch_large_file", return_value=str(cached) - ): + ), mock.patch("model.largefiles.load_registered_paths", return_value=registered): found = _resolve_for_platform( entry, "sys", db, {}, None, {"BIG.PUP": "bios/other.bin"}, "md5", {}, diff --git a/tests/test_game_data_homonyms.py b/tests/test_game_data_homonyms.py index 975ec5e91..e9b472152 100644 --- a/tests/test_game_data_homonyms.py +++ b/tests/test_game_data_homonyms.py @@ -281,42 +281,76 @@ class ReleaseAssetIsNotANameMatch(unittest.TestCase): class ReleaseAssetAnswersEveryDeclaredHash(unittest.TestCase): """The fallback passed only the first sha1 or md5 to the asset store: an entry declaring sha256 or crc32 alone got the same-named asset back - unchecked, and one accepting two sha1s lost a cached copy of the second.""" + unchecked, and one accepting two sha1s lost a cached copy of the second. + The asset is chosen on its database record, then its bytes are held to + the declaration once fetched.""" - def _resolve(self, entry: dict, cached_bytes: bytes): + def _resolve(self, entry: dict, record_bytes: bytes, cached_bytes: bytes): import tempfile from unittest import mock from resolve import packfiles as packresolve - db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}} + registered = ["bios/Big/big.bin"] + sha1 = hashlib.sha1(record_bytes).hexdigest() + db = { + "files": {sha1: { + "path": registered[0], "name": "big.bin", "size": len(record_bytes), + "sha1": sha1, "md5": hashlib.md5(record_bytes).hexdigest(), + "sha256": hashlib.sha256(record_bytes).hexdigest(), + }}, + "indexes": {"by_name": {}, "by_md5": {}, "by_path_suffix": {}}, + } with tempfile.TemporaryDirectory() as tmp: cached = Path(tmp) / entry["name"] cached.write_bytes(cached_bytes) + asked: list[tuple[str, str]] = [] def fetch(name, expected_sha1="", expected_md5="", offline=True): - digest = hashlib.sha1(cached_bytes).hexdigest() - return str(cached) if expected_sha1 in ("", digest) else None + asked.append((name, expected_sha1)) + return str(cached) - with mock.patch.object(packresolve, "fetch_large_file", side_effect=fetch): - path, status = packresolve.resolve_file(entry, db, "bios", {}, offline=True) + with ( + mock.patch("model.largefiles.load_registered_paths", return_value=registered), + mock.patch.object(packresolve, "fetch_large_file", side_effect=fetch), + ): + path, status = packresolve.resolve_file(entry, db, tmp, {}, offline=True) + for name, expected in asked: + self.assertEqual((name, expected), (registered[0], sha1)) return (Path(path).name if path else None), status def test_a_sha256_alone_is_checked(self): wanted = hashlib.sha256(b"right").hexdigest() - self.assertEqual( - self._resolve({"name": "big.bin", "sha256": wanted}, b"wrong"), - (None, "not_found"), - ) - self.assertEqual( - self._resolve({"name": "big.bin", "sha256": wanted}, b"right"), - ("big.bin", "release_asset"), - ) + entry = {"name": "big.bin", "sha256": wanted} + self.assertEqual(self._resolve(entry, b"wrong", b"wrong"), (None, "not_found")) + self.assertEqual(self._resolve(entry, b"right", b"wrong"), (None, "not_found")) + self.assertEqual(self._resolve(entry, b"right", b"right"), ("big.bin", "release_asset")) def test_the_second_accepted_sha1_is_found(self): second = hashlib.sha1(b"second").hexdigest() entry = {"name": "big.bin", "sha1": [hashlib.sha1(b"first").hexdigest(), second]} - self.assertEqual(self._resolve(entry, b"second"), ("big.bin", "release_asset")) + self.assertEqual( + self._resolve(entry, b"second", b"second"), ("big.bin", "release_asset"), + ) + + +class ReleaseAssetSizeIsReadAsTheBuilderReadsIt(unittest.TestCase): + """fbneo declares donpachi.zip with an approximate size and no hash. The + builder accepted the fetched sample (a size counts only under + ``validation: [size]``) while verify refused the record over its exact + size and reported the file missing.""" + + def test_an_informative_size_rejects_nothing_and_a_validated_one_does(self): + from resolve import packfiles as packresolve + + registered = ["bios/Other/fbneo/samples/donpachi.zip"] + db = {"files": {"a" * 40: { + "path": registered[0], "name": "donpachi.zip", "size": 208549253, "sha1": "a" * 40, + }}} + entry = {"name": "donpachi.zip", "size": 209000000, "storage": "release"} + self.assertEqual(packresolve.release_asset_paths(entry, db, registered), registered) + entry["validation"] = ["size"] + self.assertEqual(packresolve.release_asset_paths(entry, db, registered), []) class ForeignCopyYieldsToADataDirectory(unittest.TestCase):