diff --git a/scripts/model/database.py b/scripts/model/database.py index 9a97c8d08..57d8ecb6e 100644 --- a/scripts/model/database.py +++ b/scripts/model/database.py @@ -97,26 +97,33 @@ def sha1_at(db: dict, path: str | None) -> str | None: _HASH_INDEXES = {"md5": "by_md5", "crc32": "by_crc32", "sha256": "by_sha256"} -def record_for_hash(db: dict, kind: str, value: object) -> str | None: - """The sha1 the database keys the file one hash value names under. +def records_for_hash(db: dict, kind: str, value: object) -> list[str]: + """The sha1 of every held record one hash value names, index order kept. A cut md5 (Batocera writes 29 characters) names the one held md5 it - starts, as cut_md5_owner reads it. + starts, as cut_md5_owner reads it. An index value that is a list names + several records, all returned. """ if not (value and isinstance(value, str)): - return None + return [] files = db.get("files", {}) value = value.strip().lower() if kind == "sha1": - return value if value in files else None + return [value] if value in files else [] index = db.get("indexes", {}).get(_HASH_INDEXES[kind], {}) found = index.get(value) if found is None and kind == "md5": owner = cut_md5_owner(value, index) found = index.get(owner) if owner else None - if isinstance(found, list): - found = found[0] if found else None - return found if found in files else None + if found is None: + return [] + named = [found] if isinstance(found, str) else list(found) + return [sha1 for sha1 in named if sha1 in files] + + +def record_for_hash(db: dict, kind: str, value: object) -> str | None: + """The sha1 of the first held record one hash value names.""" + return next(iter(records_for_hash(db, kind, value)), None) _mame_clone_map_cache: dict[str, dict[str, str]] = {} diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index 4ded349d2..cb336a0e1 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -38,7 +38,7 @@ from resolve.launchers import ( suffixed_stem, ) from resolve.layout import system_dir_path -from resolve.localfile import resolve_local_file +from resolve.localfile import held_record_for, resolve_local_file from resolve.ownership import foreign_tree, owner_tokens from resolve.standalone import platform_layouts from resolve.validation import ( @@ -624,19 +624,14 @@ def entry_source(f: dict, index: dict) -> str | None: return source found = found or source - def values(field: str) -> list[str]: - return parse_hash_list(f.get(field)) - # The declared content anywhere in bios/ comes before a data/ copy, as in - # the resolver: the hash steps run before the data directories. - held = ( - any(index["by_md5"].get(v) for v in parse_hash_list(f.get("md5"))) - or any(v in db_files for v in values("sha1")) - # rust_dos names its SC-55 ROMs by sha256 alone - or any(v in index["by_sha256"] for v in values("sha256")) - or any(index["by_crc32"].get(v) for v in values("crc32")) - ) - return "bios" if held else found + # the resolver: the hash steps run before the data directories, and the + # held record is the one every declared hash agrees with. + held = held_record_for(f, { + "files": db_files, + "indexes": {key: index[key] for key in ("by_md5", "by_sha256", "by_crc32")}, + }) + return "bios" if held is not None else found def _resolve_archive_source( diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index 52de843e1..15cdd2117 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, TypedDict from core.artifacts import build_timestamp from packs.paths import MEDIA_MARKER, has_path_conflict -from core.ziptools import build_zip_contents_index +from core.ziptools import build_zip_contents_index, is_archive_path from core.ziptools import safe_member_parts from resolve.nativemode import digest_algorithm, platform_mode from resolve.validation import ( @@ -22,7 +22,8 @@ from resolve.nativemode import hash_mismatch_excludes_file import sys from resolve.cores import filter_systems_by_target from core.hashing import ( - compute_hashes, file_digest, md5_composite_of, md5sum, parse_hash_list, stream_hashes, + compute_hashes, file_digest, md5_composite, md5_composite_of, md5sum, parse_hash_list, + stream_hashes, ) from core.options import reject_unknown import io @@ -34,6 +35,7 @@ from packs.paths import flat_arcname from resolve.nativemode import reads_file_contents from resolve import regions as resolve_regions from packs import slots +from resolve.localfile import held_record_for from resolve.packfiles import resolve_declaration, resolve_file from resolve.categories import BIOS, EntryCategories from resolve.gamedata import without_game_data @@ -386,28 +388,32 @@ def _check_member_hash( def _repo_satisfies_declaration( entries: list[dict], db: dict, mode: str ) -> bool: - """Check whether any repo file matches one of the declared hashes. + """Check whether any repo file matches one of the declarations. Used to separate pack divergence (a matching file exists but was not packed) from data coverage gaps (no repo file matches the upstream - declaration): only the former is a pack generation error. + declaration): only the former is a pack generation error. A held file + is the resolver's: every declared hash agrees with it, and a zipped_file + md5 names a member of a held archive, not a loose file. The verdict + compares whole digests as the frontend does, so a cut md5 names a held + file without being satisfied by it. """ - from core.hashing import md5_composite - files_db = db.get("files", {}) - by_md5 = db.get("indexes", {}).get("by_md5", {}) by_name = db.get("indexes", {}).get("by_name", {}) for fe in entries: + if fe.get("zipped_file"): + if _repo_holds_member(fe, db): + return True + continue hashes = parse_hash_list(fe.get(mode)) if not hashes: continue - for h in hashes: - if mode == "sha1": - entry = files_db.get(h) - else: - entry = files_db.get(by_md5.get(h, "")) - if entry and os.path.exists(entry.get("path", "")): + held_sha1 = held_record_for(fe, db) + if held_sha1 is not None: + held = files_db[held_sha1] + digest = held_sha1 if mode == "sha1" else str(held.get(mode, "")) + if digest.lower() in hashes and os.path.exists(held.get("path", "")): return True if mode == "md5": hash_set = set(hashes) @@ -416,7 +422,7 @@ def _repo_satisfies_declaration( if not entry: continue path = entry.get("path", "") - if not path.endswith(".zip") or not os.path.exists(path): + if not is_archive_path(path) or not os.path.exists(path): continue try: if md5_composite(path).lower() in hash_set: @@ -430,7 +436,7 @@ def _repo_holds_member(file_entry: dict, db: dict) -> bool: files_db = db.get("files", {}) for sha1 in db.get("indexes", {}).get("by_name", {}).get(file_entry.get("name", ""), []): path = (files_db.get(sha1) or {}).get("path", "") - if not path.endswith(".zip") or not os.path.exists(path): + if not is_archive_path(path) or not os.path.exists(path): continue if inner_rom_check(file_entry, path) == "ok": return True diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index cb0dafb07..c39f7e1d5 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -23,6 +23,7 @@ from resolve.content import ( size_refusal, ) from resolve.archives import archive_members +from model.database import records_for_hash from model.profiles import CONTENT_CHECKS, entry_system_ids, lists_files from core.hashing import compute_hashes, parse_hash_list from core.paths import BIOS_DIR, sanitize_pack_path @@ -799,23 +800,18 @@ def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]: return set() -def _variant_candidates(expected: dict, indexes: dict, fname: str) -> Iterator[str]: - """The sha1 of each held file that may stand for a name, best evidence first.""" +def _variant_candidates(expected: dict, db: dict, fname: str) -> Iterator[str]: + """The sha1 of each held file that may stand for a name, best evidence first. + + Any one accepted value names a candidate: the index merges what several + emulators accept, and their own checks then judge each file. + """ # Sorted: the index holds sets, whose order follows the per-process # string hash, and the first passing candidate is the one shipped. - for hash_type, index_key in ( - ("sha1", None), ("md5", "by_md5"), ("crc32", "by_crc32"), ("sha256", "by_sha256"), - ): + for hash_type in ("sha1", "md5", "crc32", "sha256"): for value in sorted(expected.get(hash_type) or []): - if index_key is None: - yield value - continue - found = indexes.get(index_key, {}).get(value) - if isinstance(found, str): - yield found - elif isinstance(found, list): - yield from found - yield from indexes.get("by_name", {}).get(fname, []) + yield from records_for_hash(db, hash_type, value) + yield from db.get("indexes", {}).get("by_name", {}).get(fname, []) def find_validated_variant( @@ -848,11 +844,10 @@ def find_validated_variant( accepted = _platform_accepted(file_entry, platform_digest) files_db = db.get("files", {}) - indexes = db.get("indexes", {}) current_real = os.path.realpath(current_path) seen: set[str] = set() - for sha1 in _variant_candidates(validation_index[fname], indexes, fname): + for sha1 in _variant_candidates(validation_index[fname], db, fname): entry = files_db.get(sha1) or {} path = entry.get("path", "") if not path or not os.path.exists(path): diff --git a/tests/test_cross_reference_sources.py b/tests/test_cross_reference_sources.py index 24f2dc867..8fa2aee3f 100644 --- a/tests/test_cross_reference_sources.py +++ b/tests/test_cross_reference_sources.py @@ -34,7 +34,8 @@ def _index(**over) -> dict: class GapReportSources(unittest.TestCase): def test_a_sha256_alone_finds_the_file(self): entry = {"name": "wave1.bin", "sha256": "AB" * 32} - self.assertEqual(entry_source(entry, _index(by_sha256={"ab" * 32: "s"})), "bios") + index = _index(by_sha256={"ab" * 32: "s"}, db_files={"s": {"sha256": "ab" * 32}}) + self.assertEqual(entry_source(entry, index), "bios") def test_a_name_never_wins_over_a_declared_hash(self): """zquestclassic pins ending.mid by sha1, the collection holds only diff --git a/tests/test_e2e.py b/tests/test_e2e.py index bb3ba2ced..b296f5a85 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -6735,7 +6735,7 @@ struct BurnDriver BurnDrvneogeo = { @staticmethod def _gap_db(repo_name: str, sha1: str, crc32: str) -> dict: return { - "files": {sha1: {"path": f"bios/{repo_name}", "size": 8192}}, + "files": {sha1: {"path": f"bios/{repo_name}", "size": 8192, "crc32": crc32}}, "indexes": { "by_name": {repo_name: [sha1]}, "by_md5": {}, diff --git a/tests/test_held_record.py b/tests/test_held_record.py new file mode 100644 index 000000000..49b88cef8 --- /dev/null +++ b/tests/test_held_record.py @@ -0,0 +1,119 @@ +"""The gap report, the pack check and the variant search find a held file +by the resolver's rule. + +The gap report counted a file held on any crc32 hit, without the declared +size and even when a stronger declared hash contradicted it. The pack check +split md5 lists by hand and took a loose ROM for the member a zipped_file +md5 names. The variant search kept its own kind-to-index table. +""" + +from __future__ import annotations + +import tests + +import tempfile +import unittest +from pathlib import Path + +from model.database import record_for_hash, records_for_hash +from packs.crossref import entry_source +from packs.integrity import _repo_satisfies_declaration +from resolve.localfile import held_record_for +from resolve.validation import _variant_candidates + +SHA_A, SHA_B = "a" * 40, "b" * 40 +MD5_A, MD5_B = "1" * 32, "2" * 32 + + +def _db(files: dict, **indexes: dict) -> dict: + return {"files": files, "indexes": { + "by_md5": {}, "by_sha256": {}, "by_crc32": {}, "by_name": {}, **indexes, + }} + + +def _index(db: dict) -> dict: + return { + "by_name": {}, "by_name_lower": {}, "by_path_suffix": {}, + "by_md5": db["indexes"]["by_md5"], "by_sha256": db["indexes"]["by_sha256"], + "by_crc32": db["indexes"]["by_crc32"], "db_files": db["files"], + "data_names": set(), + } + + +class RecordsForHash(unittest.TestCase): + def test_a_list_valued_index_entry_names_every_held_record(self): + db = _db( + {SHA_A: {"path": "a"}, SHA_B: {"path": "b"}}, + by_crc32={"deadbeef": [SHA_A, "c" * 40, SHA_B]}, + ) + self.assertEqual(records_for_hash(db, "crc32", "DEADBEEF"), [SHA_A, SHA_B]) + self.assertEqual(record_for_hash(db, "crc32", "deadbeef"), SHA_A) + + def test_a_cut_md5_names_the_one_held_md5_it_starts(self): + db = _db({SHA_A: {"path": "a"}}, by_md5={MD5_A: SHA_A}) + self.assertEqual(records_for_hash(db, "md5", MD5_A[:29]), [SHA_A]) + self.assertEqual(records_for_hash(db, "md5", MD5_B[:29]), []) + + +class GapReportHeldRule(unittest.TestCase): + def setUp(self): + self.db = _db( + {SHA_A: {"path": "bios/x.bin", "md5": MD5_A, "crc32": "deadbeef", "size": 4}}, + by_md5={MD5_A: SHA_A}, by_crc32={"deadbeef": SHA_A}, + ) + + def test_a_crc32_hit_outside_the_declared_size_is_not_held(self): + index = _index(self.db) + self.assertEqual(entry_source({"name": "y", "crc32": "deadbeef", "size": 4}, index), + "bios") + self.assertIsNone(entry_source({"name": "y", "crc32": "deadbeef", "size": 8}, index)) + + def test_a_contradicting_stronger_hash_wins_over_the_crc32(self): + index = _index(self.db) + entry = {"name": "y", "sha1": "c" * 40, "crc32": "deadbeef"} + self.assertIsNone(entry_source(entry, index)) + self.assertIsNone(held_record_for(entry, self.db)) + + +class PackCheckHeldRule(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + loose = Path(tmp.name) / "rom.bin" + loose.write_bytes(b"rom") + self.db = _db( + {SHA_A: {"path": str(loose), "name": "rom.bin", "md5": MD5_A}}, + by_md5={MD5_A: SHA_A}, + ) + + def test_an_md5_list_is_read_as_its_values(self): + entries = [{"name": "rom.bin", "md5": [MD5_B, MD5_A]}] + self.assertTrue(_repo_satisfies_declaration(entries, self.db, "md5")) + + def test_a_cut_md5_is_never_satisfied(self): + """Batocera compares whole digests: a held file a cut md5 names + would still be refused, so the gap is coverage, not divergence.""" + entries = [{"name": "rom.bin", "md5": MD5_A[:29]}] + self.assertFalse(_repo_satisfies_declaration(entries, self.db, "md5")) + + def test_a_zipped_file_md5_is_no_loose_file(self): + entries = [{"name": "set.zip", "md5": MD5_A, "zipped_file": "rom.bin"}] + self.assertFalse(_repo_satisfies_declaration(entries, self.db, "md5")) + + def test_a_contradicting_sha1_refuses_the_md5_match(self): + entries = [{"name": "rom.bin", "md5": MD5_A, "sha1": SHA_B}] + self.assertFalse(_repo_satisfies_declaration(entries, self.db, "md5")) + + +class VariantCandidates(unittest.TestCase): + def test_every_record_of_a_list_valued_entry_is_a_candidate(self): + db = _db( + {SHA_A: {"path": "a"}, SHA_B: {"path": "b"}}, + by_md5={MD5_A: [SHA_A, SHA_B]}, by_name={"rom.bin": [SHA_B]}, + ) + found = list(_variant_candidates({"md5": {MD5_A}, "sha1": {"c" * 40}}, db, "rom.bin")) + self.assertEqual(found, [SHA_A, SHA_B, SHA_B]) + + +if __name__ == "__main__": + unittest.main() diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index 9b8ef89e0..0cb76ffd7 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -63,7 +63,7 @@ Every module in `tests/`, by the area it guards. |------|----------|---------| | Core regression suites | synthetic | `test_e2e`, `test_audit_regressions`, `test_tool_messages` | | Import layers | the source of `scripts/` | `test_layers` | -| File resolution and identity | synthetic + collection | `test_adler32_resolution`, `test_agnostic_scan`, `test_agnostic_scan_mode`, `test_agnostic_scope`, `test_agnostic_substitute`, `test_archive_build`, `test_archive_choice`, `test_archive_recipes`, `test_bios_companions`, `test_bundled_identity`, `test_casefold_cache`, `test_db_aliases`, `test_declared_names`, `test_derivations`, `test_directory_entries`, `test_extra_identity`, `test_foreign_tree`, `test_foreign_tree_names`, `test_frontend_digest`, `test_game_data_homonyms`, `test_hashing`, `test_identity`, `test_maker_folder_names`, `test_md5_pack_context`, `test_name_tiebreak`, `test_nec_filing`, `test_np2_fonts`, `test_owner_resolution`, `test_path_suffix`, `test_proven_name`, `test_resolution_evidence`, `test_sega_filing`, `test_shipped_content`, `test_switch_nca`, `test_twin_declaration_status`, `test_twin_declarations`, `test_validated_choice`, `test_variant_choice`, `test_variant_identity`, `test_zipped_member` | +| File resolution and identity | synthetic + collection | `test_adler32_resolution`, `test_agnostic_scan`, `test_agnostic_scan_mode`, `test_agnostic_scope`, `test_agnostic_substitute`, `test_archive_build`, `test_archive_choice`, `test_archive_recipes`, `test_bios_companions`, `test_bundled_identity`, `test_casefold_cache`, `test_db_aliases`, `test_declared_names`, `test_derivations`, `test_directory_entries`, `test_extra_identity`, `test_foreign_tree`, `test_foreign_tree_names`, `test_frontend_digest`, `test_game_data_homonyms`, `test_hashing`, `test_held_record`, `test_identity`, `test_maker_folder_names`, `test_md5_pack_context`, `test_name_tiebreak`, `test_nec_filing`, `test_np2_fonts`, `test_owner_resolution`, `test_path_suffix`, `test_proven_name`, `test_resolution_evidence`, `test_sega_filing`, `test_shipped_content`, `test_switch_nca`, `test_twin_declaration_status`, `test_twin_declarations`, `test_validated_choice`, `test_variant_choice`, `test_variant_identity`, `test_zipped_member` | | Verification, cross-reference and profile checks | synthetic + profiles | `test_bios_layout`, `test_cache_independent_counts`, `test_case_insensitive_platforms`, `test_checks_have_values`, `test_content_checks`, `test_content_declarations`, `test_core_file_fills_declaration`, `test_core_size_refusal`, `test_cross_reference_sources`, `test_crypto_aes`, `test_crypto_unique_data`, `test_crypto_verify`, `test_data_only_refs`, `test_entry_categories`, `test_file_consumers`, `test_fileless_audit`, `test_flycast_layout`, `test_gap_settlement`, `test_hidden_extras`, `test_launcher_aliases`, `test_launcher_evidence`, `test_launcher_gaps`, `test_launcher_layer`, `test_launcher_paths`, `test_launcher_placement`, `test_native_mode`, `test_no_case_collisions`, `test_path_conflict_status`, `test_path_null_copies`, `test_profile_checks`, `test_profile_names`, `test_profile_paths`, `test_profile_repositories`, `test_romm_hash_rule`, `test_shared_groups`, `test_standalone_links`, `test_standalone_mode`, `test_undeclared_dedup`, `test_unplaced_extras`, `test_validation_scope`, `test_verify_all_dir`, `test_verify_data_dir_notice`, `test_verify_emulator_evidence`, `test_verify_listing`, `test_verify_pack_choice`, `test_verify_release_asset` | | Packs and manifests | synthetic + real packs | `test_artifact_lock`, `test_atomic_artifacts`, `test_batocera_cores`, `test_core_data_trees`, `test_deterministic_zip`, `test_emulator_pack_counts`, `test_finalize_pack_names`, `test_large_file_cache`, `test_libretro_layout`, `test_manifest_entry`, `test_minui_platform`, `test_no_game_data`, `test_pack_conformance_dirs`, `test_pack_core_extras`, `test_pack_counts`, `test_pack_destinations`, `test_pack_failures`, `test_pack_file_names`, `test_pack_grouping`, `test_pack_integrity`, `test_pack_member_identity`, `test_pack_readme`, `test_platform_inheritance`, `test_platform_keys`, `test_release_packs`, `test_required_only_archives`, `test_required_only_twins`, `test_save_root`, `test_split_extras`, `test_split_names`, `test_split_pack`, `test_system_pack_extras`, `test_system_pack_parity`, `test_torrentzip`, `test_which_pack` | | Slots and regions | synthetic + profiles | `test_region`, `test_region_agnostic_scan`, `test_region_groups`, `test_region_held`, `test_region_platform_index`, `test_region_required_only`, `test_slot`, `test_slots`, `test_slots_shipped_file` |