From 4916b4a44e4169c30f36dedcd36d72ed1c131239 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 05:58:02 +0100 Subject: [PATCH] refactor: move the declaration tally to its module --- .github/workflows/deploy-site.yml | 1 + scripts/packs/coverage.py | 433 +------------------------- scripts/packs/platformtally.py | 422 +++++++++++++++++++++++++ scripts/sitegen/emulatorpage.py | 181 ----------- tests/sources.py | 3 +- tests/test_audit_regressions.py | 6 +- tests/test_retrodeck_component_md5.py | 3 +- tests/test_slots.py | 2 +- tests/test_tool_messages.py | 4 +- 9 files changed, 447 insertions(+), 608 deletions(-) create mode 100644 scripts/packs/platformtally.py diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 1ee069196..ea49db98f 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -94,6 +94,7 @@ on: - "scripts/packs/naming.py" - "scripts/packs/parts.py" - "scripts/packs/paths.py" + - "scripts/packs/platformtally.py" - "scripts/packs/shares.py" - "scripts/packs/slots.py" - "scripts/packs/supplemental.py" diff --git a/scripts/packs/coverage.py b/scripts/packs/coverage.py index 49b06b21d..672d0c875 100644 --- a/scripts/packs/coverage.py +++ b/scripts/packs/coverage.py @@ -5,45 +5,38 @@ from __future__ import annotations from pathlib import Path from model.dbpaths import collection_root import os -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import TYPE_CHECKING, TypedDict -from core.paths import BIOS_DIR, EMULATORS_DIR, declared_destination +from core.paths import BIOS_DIR, EMULATORS_DIR from core.ziptools import build_zip_contents_index from model.alternatives import core_file_spares -from model.declarations import OUTER_ROOTS, declared_components, platform_declarations +from model.declarations import OUTER_ROOTS, platform_declarations from model.profiles import lists_files, load_emulator_profiles from model.systems import select_systems from packs import slots from packs.crossreflaunchers import launcher_reads_not_held from packs.gaps import find_exclusion_notes, scan_core_files from packs.verdicts import ( - RELEASE_ASSET_PENDING, - Severity, Status, - SEVERITY_ORDER, - STATUS_ORDER, - storage_verdict, - compute_severity, - verify_entry_existence, - verify_entry_md5, - verify_entry_sha1, ) -from resolve.categories import BIOS, EntryCategories +from resolve.categories import EntryCategories from resolve.cores import platform_scope_systems, resolve_platform_cores from resolve.launcherconfig import launcher_unproven -from resolve.nativemode import digest_algorithm, platform_mode, reads_file_contents -from resolve.validation import accepted_hashes, build_validation_index, build_ground_truth -from resolve.acceptance import ( - agnostic_substitute, - baseline_verdict, - destination_owners, - validated_choice, -) +from resolve.nativemode import platform_mode, reads_file_contents +from resolve.validation import build_validation_index +from resolve.acceptance import destination_owners if TYPE_CHECKING: from packs.extras import ExtraResolver from typing_extensions import Unpack +from packs.platformtally import ( + DeclarationResolver, + PlatformRun, + PlatformTally, + dest_key, + twin_index, +) # Platform verification @@ -175,404 +168,6 @@ def _builder_placement( return shipped, occupied -def dest_key(file_entry: dict, sys_id: str) -> str: - """The path a declaration occupies, as the builder keys its pack.""" - dest = declared_destination(file_entry) - return dest or f"{sys_id}/{file_entry.get('name', '')}" - - -def twin_index( - verify_systems: dict, db: dict, base_dest: str, zip_contents: dict, -) -> tuple[dict[str, int], dict[int, tuple[str, dict]]]: - """Which declaration the pack ships at each destination, and every declaration by id.""" - # From the module that defines the rule, not the builder's CLI: importing - # generate_pack made every verify depend on its argparse and manifest code. - from resolve.packfiles import preferred_entries as _preferred_entries - - preferred_entries = _preferred_entries( - verify_systems, db, BIOS_DIR, base_dest, False, - zip_contents, True, - ) - winners = { - id(fe): (sid, fe) - for sid, system in verify_systems.items() - for fe in system.get("files", []) - } - return preferred_entries, winners - - -@dataclass(frozen=True) -class DeclarationResolver: - """How a platform run resolves its declarations, as the builder does.""" - - db: dict - zip_contents: dict - data_dir_registry: dict | None - slot_overrides: dict[str, str] - mode: str - platform_profiles: dict - # Which declaration the pack ships at each destination, and every - # declaration by id (twin_index). - preferred_entries: dict[str, int] - winners: dict[int, tuple[str, dict]] - base_dest: str - - -def _resolve_declaration( - file_entry: dict, sys_id: str, resolver: DeclarationResolver, -) -> tuple[str | None, str, str | None, dict]: - """Resolve a declaration to the file the pack ships at its destination. - - When another declaration holds the destination, that one's file is - returned and the evidence reset: the winner's hash match is not this - declaration's, which is hashed against the shipped file. The - declaration that holds the path comes last. - """ - base_dest = resolver.base_dest - bare = declared_destination(file_entry) - preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) - held_by, winner = (None, file_entry) - if preferred is not None and preferred != id(file_entry): - held_by, winner = resolver.winners[preferred] - local_path, resolve_status = _resolve_for_platform( - winner, held_by or sys_id, resolver.db, resolver.zip_contents, - resolver.data_dir_registry, resolver.slot_overrides, resolver.mode, - resolver.platform_profiles, - ) - return local_path, "" if held_by else resolve_status, held_by, winner - - -def _expects(entry: dict) -> str: - """The first hash a declaration names, as the message quotes it.""" - return next( - (f" ({h} {str(entry[h]).split(',')[0]})" - for h in ("sha1", "md5", "crc32") if entry.get(h)), - "", - ) - - -def _side(sys_id: str, entry: dict) -> str: - """One declaration named by the platform's own system, or its component.""" - native = entry.get("native_system") or ", ".join( - declared_components(entry.get("component")) - ) - return f"{sys_id} ({native})" if native else sys_id - - -def _twin_unmet( - result: dict, - held_by: str | None, - file_entry: dict | None = None, - sys_id: str = "", - destination: str = "", - holder: dict | None = None, -) -> bool: - """Mark a declaration unmet at a path another declaration holds. - - The path is answered by the winner's file, which the pack counts once. - This declaration's failure is reported, never folded into the - destination's status. The message names the path, both systems and - what this declaration expects: "is not met at the path coco holds" - named neither the path nor the file wanted there. Two declarations of - one system are told apart by the platform's own system (RetroDECK - declares decocass.zip for MAME and for FBNeo, both arcade here), and by - the hash the holder names when that is the same too (its three - 64DD_IPL.bin revisions). - """ - if held_by is None or result["status"] == Status.OK: - return False - entry = file_entry or {} - expects = _expects(entry) - owner, other, held = sys_id or "this", held_by, "" - if owner == other and holder is not None: - owner, other = _side(owner, entry), _side(other, holder) - if owner == other: - held = _expects(holder) - result["discrepancy"] = ( - f"{destination or result.get('name', '')} is declared for {owner}" - f" and for {other}. The {owner} declaration{expects} is not met at" - f" the path, which holds the {other} file{held}" - ) - # Read by reports that list entries: the destination itself is held, and - # a count by destination does not include this one. - result["settled_by"] = held_by - return True - - -def _resolve_for_platform( - file_entry: dict, - sys_id: str, - db: dict, - zip_contents: dict, - data_dir_registry: dict | None, - slot_overrides: dict[str, str], - mode: str, - platform_profiles: dict, -) -> tuple[str | None, str]: - """Resolve one platform entry the way the pack builder does. - - The builder's own resolution (packresolve.resolve_declaration), read from - 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 release_asset_paths, resolve_declaration, run_is_offline - - override = slot_overrides.get( - declared_destination(file_entry) - ) - local_path, status = resolve_declaration( - file_entry, db, BIOS_DIR, zip_contents, data_dir_registry, - override, offline=True, - ) - 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). - 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: - return found[0], "agnostic_fallback" - return local_path, status - - -@dataclass(frozen=True) -class PlatformRun: - """The inputs of one verify_platform run, read by each of its stages.""" - - config: dict - db: dict - emulators_dir: str - emu_profiles: dict | None - profiles: dict - target_cores: set[str] | None - data_dir_registry: dict | None - zip_contents: dict - system_filter: list[str] | None - required_only: bool - mode: str - base_dest: str - - def full(self, destination: str) -> str: - return f"{self.base_dest}/{destination}" if self.base_dest else destination - - -@dataclass -class PlatformTally: - """Each declaration's verdict, and the verdicts aggregated by destination.""" - - run: PlatformRun - platform: str - resolver: DeclarationResolver - region_drops: set[str] - validation_index: dict - validation_owners: dict[str, list[tuple[str, str]]] - hle_index: dict[str, bool] - categories: EntryCategories - details: list[dict] = field(default_factory=list) - file_status: dict[str, str] = field(default_factory=dict) - file_required: dict[str, bool] = field(default_factory=dict) - file_severity: dict[str, str] = field(default_factory=dict) - # What each entry is: firmware, a game's data, or a name no core the - # platform runs opens. Only firmware gaps carry a severity. - file_category: dict[str, str] = field(default_factory=dict) - # (system, full destination, local copy) of each declaration the builder - # writes, and None for one whose slot it keeps without a file from the - # collection (user_provided, external). Placed below in the builder's order. - packed_order: list[tuple[str, str, str | None]] = field(default_factory=list) - shipped_keys: set[str] = field(default_factory=set) - results_at: dict[str, list[dict]] = field(default_factory=dict) - - def judge(self, sys_id: str, file_entry: dict) -> None: - """Verify one declaration and add it to its destination's tally.""" - destination = declared_destination(file_entry) - if self.region_drops and destination in self.region_drops: - return - local_path, resolve_status, held_by, holder = _resolve_declaration( - file_entry, sys_id, self.resolver, - ) - result, local_path = self._verdict( - file_entry, sys_id, local_path, resolve_status, destination, - ) - result["system"] = sys_id - result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False) - result["ground_truth"] = build_ground_truth( - file_entry.get("name", ""), - self.validation_index, - ) - self.details.append(result) - config = self.run.config - mode = self.run.mode - # Occupied only where the builder ships the declaration: a hash - # the frontend refuses is left out, and the destination stays free - # for a core's file the pack does carry. - if ( - local_path - and result["status"] != Status.MISSING - and baseline_verdict( - file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") - )[1] is None - ): - self.packed_order.append((sys_id, self.run.full(destination), local_path)) - self.shipped_keys.add(dest_key(file_entry, sys_id)) - if _twin_unmet( - result, held_by, file_entry, sys_id, self.run.full(destination), holder, - ): - return - self._aggregate(sys_id, file_entry, destination, result) - - def _verdict( - self, file_entry: dict, sys_id: str, local_path: str | None, - resolve_status: str, destination: str, - ) -> tuple[dict, str | None]: - """The declaration's result, and the local copy the pack writes for it.""" - config = self.run.config - mode = self.run.mode - stored = storage_verdict(file_entry, emulator_pack=False) - if resolve_status == RELEASE_ASSET_PENDING: - # Counted as an online build counts it, which fetches the - # asset. Under --offline the builder cannot, and neither - # does this report (_resolve_for_platform). - result = { - "name": file_entry.get("name", ""), - "required": file_entry.get("required", True), - "status": Status.OK, - "release_asset": local_path, - "reason": "release asset, fetched when the pack is built", - } - # Written at its path like any held file: keyed to None, it - # stayed out of pack_destinations and step 5 read the pack's - # copy as a file only the pack holds. - self.packed_order.append((sys_id, self.run.full(destination), local_path)) - self.shipped_keys.add(dest_key(file_entry, sys_id)) - return result, None - if stored is not None: - # The builder keeps the slot: instructions for a user_provided - # file, the download for an external one, whether it arrives - # or not. No core file goes there. - self.packed_order.append((sys_id, self.run.full(destination), None)) - return stored, None - if not reads_file_contents(mode): - return verify_entry_existence( - file_entry, - local_path, - self.validation_index, - self.run.db, - destination, - self.validation_owners, - resolve_status, - config.get("platform", ""), - ), local_path - if digest_algorithm(mode) == "sha1": - return verify_entry_sha1(file_entry, local_path), local_path - result = verify_entry_md5( - file_entry, local_path, resolve_status, config.get("hash_rule", "") - ) - # Emulator-level validation: informational for platform packs. - # Platform verification (MD5) is the authority. Emulator - # mismatches are reported as discrepancies, not failures. - if result["status"] == Status.OK: - _chosen, disagreement = validated_choice( - file_entry, local_path, self.run.db, self.validation_index, "bios", - digest_algorithm(mode), destination, self.validation_owners, - ) - if disagreement: - result["discrepancy"] = f"{self.platform} says OK but {disagreement}" - if accepted := accepted_hashes(disagreement): - result["accepted"] = accepted - return result, local_path - - def _aggregate( - self, sys_id: str, file_entry: dict, destination: str, result: dict, - ) -> None: - # Aggregate by destination, keyed as the builder keys its pack. - # A declaration that finds nothing leaves the path to one that - # holds a file: the builder packs that file there, whatever the - # order the two are read in. - dest = dest_key(file_entry, sys_id) - self.results_at.setdefault(dest, []).append(result) - required = file_entry.get("required", True) - cur = result["status"] - prev = self.file_status.get(dest) - hle = self.hle_index.get(file_entry.get("name", ""), False) - sev = compute_severity(cur, required, self.run.mode, hle) - explained = self.categories.explain(file_entry, destination, sys_id) - category = explained.pop("category") - result["category"] = category - result["category_evidence"] = explained - if cur != Status.MISSING: - # A held entry is firmware for the counts: its category only - # documents it. - category = BIOS - if self.file_category.get(dest, category) == BIOS: - category = BIOS - self.file_category[dest] = category - if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): - if cur == Status.MISSING: - return - del self.file_status[dest], self.file_severity[dest] - prev = None - if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get(prev, 0): - self.file_status[dest] = cur - self.file_required[dest] = required - prev_sev = self.file_severity.get(dest) - if prev_sev is None or SEVERITY_ORDER.get(sev, 0) > SEVERITY_ORDER.get( - prev_sev, 0 - ): - self.file_severity[dest] = sev - - def settle_groups(self) -> None: - """RetroBat's group: one file of it held is enough, and the others are - reported OPTIONAL (batocera-systems/Program.cs). None held, each stays - required.""" - members: dict[tuple[str, str], list[str]] = {} - for sys_id, system in self.run.config.get("systems", {}).items(): - for file_entry in system.get("files", []): - if file_entry.get("group"): - dest = dest_key(file_entry, sys_id) - if dest in self.file_status: - members.setdefault((sys_id, file_entry["group"]), []).append(dest) - for dests in members.values(): - if not any(self.file_status[d] == Status.OK for d in dests): - continue - for dest in dests: - if self.file_status[dest] == Status.MISSING: - self.file_required[dest] = False - self.file_severity[dest] = compute_severity( - Status.MISSING, False, self.run.mode - ) - for result in self.results_at.get(dest, []): - result["required"] = False - - def credit_placed(self, placed: set[str]) -> None: - """An existence frontend is satisfied by any file at the path, and the - builder fills a free platform destination with a core's file.""" - for dest, status in self.file_status.items(): - if status == Status.MISSING and self.run.full(dest) in placed: - self.file_status[dest] = Status.OK - self.file_severity[dest] = Severity.OK - for result in self.results_at.get(dest, []): - result["status"] = Status.OK - - def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]: - """Destinations by severity, and the missing ones that are not firmware.""" - counts = { - Severity.OK: 0, - Severity.INFO: 0, - Severity.WARNING: 0, - Severity.CRITICAL: 0, - } - not_firmware: dict[str, list[str]] = {} - for dest, s in self.file_severity.items(): - category = self.file_category.get(dest, BIOS) - if category != BIOS and self.file_status.get(dest) == Status.MISSING: - not_firmware.setdefault(category, []).append(dest) - continue - counts[s] = counts.get(s, 0) + 1 - return counts, not_firmware - - def _cut_game_data( config: dict, emu_profiles: dict | None, diff --git a/scripts/packs/platformtally.py b/scripts/packs/platformtally.py new file mode 100644 index 000000000..a409716fe --- /dev/null +++ b/scripts/packs/platformtally.py @@ -0,0 +1,422 @@ +"""Each declaration of a platform resolved and tallied by verify.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +from core.paths import BIOS_DIR, declared_destination +from model.declarations import declared_components +from packs.verdicts import ( + RELEASE_ASSET_PENDING, + SEVERITY_ORDER, + STATUS_ORDER, + Severity, + Status, + compute_severity, + storage_verdict, + verify_entry_existence, + verify_entry_md5, + verify_entry_sha1, +) +from resolve.categories import BIOS, EntryCategories +from resolve.nativemode import digest_algorithm, reads_file_contents +from resolve.validation import accepted_hashes, build_ground_truth +from resolve.acceptance import agnostic_substitute, baseline_verdict, validated_choice + + +def dest_key(file_entry: dict, sys_id: str) -> str: + """The path a declaration occupies, as the builder keys its pack.""" + dest = declared_destination(file_entry) + return dest or f"{sys_id}/{file_entry.get('name', '')}" + + +def twin_index( + verify_systems: dict, db: dict, base_dest: str, zip_contents: dict, +) -> tuple[dict[str, int], dict[int, tuple[str, dict]]]: + """Which declaration the pack ships at each destination, and every declaration by id.""" + # From the module that defines the rule, not the builder's CLI: importing + # generate_pack made every verify depend on its argparse and manifest code. + from resolve.packfiles import preferred_entries as _preferred_entries + + preferred_entries = _preferred_entries( + verify_systems, db, BIOS_DIR, base_dest, False, + zip_contents, True, + ) + winners = { + id(fe): (sid, fe) + for sid, system in verify_systems.items() + for fe in system.get("files", []) + } + return preferred_entries, winners + + +@dataclass(frozen=True) +class DeclarationResolver: + """How a platform run resolves its declarations, as the builder does.""" + + db: dict + zip_contents: dict + data_dir_registry: dict | None + slot_overrides: dict[str, str] + mode: str + platform_profiles: dict + # Which declaration the pack ships at each destination, and every + # declaration by id (twin_index). + preferred_entries: dict[str, int] + winners: dict[int, tuple[str, dict]] + base_dest: str + + +def _resolve_declaration( + file_entry: dict, sys_id: str, resolver: DeclarationResolver, +) -> tuple[str | None, str, str | None, dict]: + """Resolve a declaration to the file the pack ships at its destination. + + When another declaration holds the destination, that one's file is + returned and the evidence reset: the winner's hash match is not this + declaration's, which is hashed against the shipped file. The + declaration that holds the path comes last. + """ + base_dest = resolver.base_dest + bare = declared_destination(file_entry) + preferred = resolver.preferred_entries.get(f"{base_dest}/{bare}" if base_dest else bare) + held_by, winner = (None, file_entry) + if preferred is not None and preferred != id(file_entry): + held_by, winner = resolver.winners[preferred] + local_path, resolve_status = _resolve_for_platform( + winner, held_by or sys_id, resolver.db, resolver.zip_contents, + resolver.data_dir_registry, resolver.slot_overrides, resolver.mode, + resolver.platform_profiles, + ) + return local_path, "" if held_by else resolve_status, held_by, winner + + +def _expects(entry: dict) -> str: + """The first hash a declaration names, as the message quotes it.""" + return next( + (f" ({h} {str(entry[h]).split(',')[0]})" + for h in ("sha1", "md5", "crc32") if entry.get(h)), + "", + ) + + +def _side(sys_id: str, entry: dict) -> str: + """One declaration named by the platform's own system, or its component.""" + native = entry.get("native_system") or ", ".join( + declared_components(entry.get("component")) + ) + return f"{sys_id} ({native})" if native else sys_id + + +def _twin_unmet( + result: dict, + held_by: str | None, + file_entry: dict | None = None, + sys_id: str = "", + destination: str = "", + holder: dict | None = None, +) -> bool: + """Mark a declaration unmet at a path another declaration holds. + + The path is answered by the winner's file, which the pack counts once. + This declaration's failure is reported, never folded into the + destination's status. The message names the path, both systems and + what this declaration expects: "is not met at the path coco holds" + named neither the path nor the file wanted there. Two declarations of + one system are told apart by the platform's own system (RetroDECK + declares decocass.zip for MAME and for FBNeo, both arcade here), and by + the hash the holder names when that is the same too (its three + 64DD_IPL.bin revisions). + """ + if held_by is None or result["status"] == Status.OK: + return False + entry = file_entry or {} + expects = _expects(entry) + owner, other, held = sys_id or "this", held_by, "" + if owner == other and holder is not None: + owner, other = _side(owner, entry), _side(other, holder) + if owner == other: + held = _expects(holder) + result["discrepancy"] = ( + f"{destination or result.get('name', '')} is declared for {owner}" + f" and for {other}. The {owner} declaration{expects} is not met at" + f" the path, which holds the {other} file{held}" + ) + # Read by reports that list entries: the destination itself is held, and + # a count by destination does not include this one. + result["settled_by"] = held_by + return True + + +def _resolve_for_platform( + file_entry: dict, + sys_id: str, + db: dict, + zip_contents: dict, + data_dir_registry: dict | None, + slot_overrides: dict[str, str], + mode: str, + platform_profiles: dict, +) -> tuple[str | None, str]: + """Resolve one platform entry the way the pack builder does. + + The builder's own resolution (packresolve.resolve_declaration), read from + 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 release_asset_paths, resolve_declaration, run_is_offline + + override = slot_overrides.get( + declared_destination(file_entry) + ) + local_path, status = resolve_declaration( + file_entry, db, BIOS_DIR, zip_contents, data_dir_registry, + override, offline=True, + ) + 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). + 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: + return found[0], "agnostic_fallback" + return local_path, status + + +@dataclass(frozen=True) +class PlatformRun: + """The inputs of one verify_platform run, read by each of its stages.""" + + config: dict + db: dict + emulators_dir: str + emu_profiles: dict | None + profiles: dict + target_cores: set[str] | None + data_dir_registry: dict | None + zip_contents: dict + system_filter: list[str] | None + required_only: bool + mode: str + base_dest: str + + def full(self, destination: str) -> str: + return f"{self.base_dest}/{destination}" if self.base_dest else destination + + +@dataclass +class PlatformTally: + """Each declaration's verdict, and the verdicts aggregated by destination.""" + + run: PlatformRun + platform: str + resolver: DeclarationResolver + region_drops: set[str] + validation_index: dict + validation_owners: dict[str, list[tuple[str, str]]] + hle_index: dict[str, bool] + categories: EntryCategories + details: list[dict] = field(default_factory=list) + file_status: dict[str, str] = field(default_factory=dict) + file_required: dict[str, bool] = field(default_factory=dict) + file_severity: dict[str, str] = field(default_factory=dict) + # What each entry is: firmware, a game's data, or a name no core the + # platform runs opens. Only firmware gaps carry a severity. + file_category: dict[str, str] = field(default_factory=dict) + # (system, full destination, local copy) of each declaration the builder + # writes, and None for one whose slot it keeps without a file from the + # collection (user_provided, external). Placed below in the builder's order. + packed_order: list[tuple[str, str, str | None]] = field(default_factory=list) + shipped_keys: set[str] = field(default_factory=set) + results_at: dict[str, list[dict]] = field(default_factory=dict) + + def judge(self, sys_id: str, file_entry: dict) -> None: + """Verify one declaration and add it to its destination's tally.""" + destination = declared_destination(file_entry) + if self.region_drops and destination in self.region_drops: + return + local_path, resolve_status, held_by, holder = _resolve_declaration( + file_entry, sys_id, self.resolver, + ) + result, local_path = self._verdict( + file_entry, sys_id, local_path, resolve_status, destination, + ) + result["system"] = sys_id + result["hle_fallback"] = self.hle_index.get(file_entry.get("name", ""), False) + result["ground_truth"] = build_ground_truth( + file_entry.get("name", ""), + self.validation_index, + ) + self.details.append(result) + config = self.run.config + mode = self.run.mode + # Occupied only where the builder ships the declaration: a hash + # the frontend refuses is left out, and the destination stays free + # for a core's file the pack does carry. + if ( + local_path + and result["status"] != Status.MISSING + and baseline_verdict( + file_entry, local_path, resolve_status, mode, config.get("hash_rule", "") + )[1] is None + ): + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(dest_key(file_entry, sys_id)) + if _twin_unmet( + result, held_by, file_entry, sys_id, self.run.full(destination), holder, + ): + return + self._aggregate(sys_id, file_entry, destination, result) + + def _verdict( + self, file_entry: dict, sys_id: str, local_path: str | None, + resolve_status: str, destination: str, + ) -> tuple[dict, str | None]: + """The declaration's result, and the local copy the pack writes for it.""" + config = self.run.config + mode = self.run.mode + stored = storage_verdict(file_entry, emulator_pack=False) + if resolve_status == RELEASE_ASSET_PENDING: + # Counted as an online build counts it, which fetches the + # asset. Under --offline the builder cannot, and neither + # does this report (_resolve_for_platform). + result = { + "name": file_entry.get("name", ""), + "required": file_entry.get("required", True), + "status": Status.OK, + "release_asset": local_path, + "reason": "release asset, fetched when the pack is built", + } + # Written at its path like any held file: keyed to None, it + # stayed out of pack_destinations and step 5 read the pack's + # copy as a file only the pack holds. + self.packed_order.append((sys_id, self.run.full(destination), local_path)) + self.shipped_keys.add(dest_key(file_entry, sys_id)) + return result, None + if stored is not None: + # The builder keeps the slot: instructions for a user_provided + # file, the download for an external one, whether it arrives + # or not. No core file goes there. + self.packed_order.append((sys_id, self.run.full(destination), None)) + return stored, None + if not reads_file_contents(mode): + return verify_entry_existence( + file_entry, + local_path, + self.validation_index, + self.run.db, + destination, + self.validation_owners, + resolve_status, + config.get("platform", ""), + ), local_path + if digest_algorithm(mode) == "sha1": + return verify_entry_sha1(file_entry, local_path), local_path + result = verify_entry_md5( + file_entry, local_path, resolve_status, config.get("hash_rule", "") + ) + # Emulator-level validation: informational for platform packs. + # Platform verification (MD5) is the authority. Emulator + # mismatches are reported as discrepancies, not failures. + if result["status"] == Status.OK: + _chosen, disagreement = validated_choice( + file_entry, local_path, self.run.db, self.validation_index, "bios", + digest_algorithm(mode), destination, self.validation_owners, + ) + if disagreement: + result["discrepancy"] = f"{self.platform} says OK but {disagreement}" + if accepted := accepted_hashes(disagreement): + result["accepted"] = accepted + return result, local_path + + def _aggregate( + self, sys_id: str, file_entry: dict, destination: str, result: dict, + ) -> None: + # Aggregate by destination, keyed as the builder keys its pack. + # A declaration that finds nothing leaves the path to one that + # holds a file: the builder packs that file there, whatever the + # order the two are read in. + dest = dest_key(file_entry, sys_id) + self.results_at.setdefault(dest, []).append(result) + required = file_entry.get("required", True) + cur = result["status"] + prev = self.file_status.get(dest) + hle = self.hle_index.get(file_entry.get("name", ""), False) + sev = compute_severity(cur, required, self.run.mode, hle) + explained = self.categories.explain(file_entry, destination, sys_id) + category = explained.pop("category") + result["category"] = category + result["category_evidence"] = explained + if cur != Status.MISSING: + # A held entry is firmware for the counts: its category only + # documents it. + category = BIOS + if self.file_category.get(dest, category) == BIOS: + category = BIOS + self.file_category[dest] = category + if prev is not None and (cur == Status.MISSING) != (prev == Status.MISSING): + if cur == Status.MISSING: + return + del self.file_status[dest], self.file_severity[dest] + prev = None + if prev is None or STATUS_ORDER.get(cur, 0) > STATUS_ORDER.get(prev, 0): + self.file_status[dest] = cur + self.file_required[dest] = required + prev_sev = self.file_severity.get(dest) + if prev_sev is None or SEVERITY_ORDER.get(sev, 0) > SEVERITY_ORDER.get( + prev_sev, 0 + ): + self.file_severity[dest] = sev + + def settle_groups(self) -> None: + """RetroBat's group: one file of it held is enough, and the others are + reported OPTIONAL (batocera-systems/Program.cs). None held, each stays + required.""" + members: dict[tuple[str, str], list[str]] = {} + for sys_id, system in self.run.config.get("systems", {}).items(): + for file_entry in system.get("files", []): + if file_entry.get("group"): + dest = dest_key(file_entry, sys_id) + if dest in self.file_status: + members.setdefault((sys_id, file_entry["group"]), []).append(dest) + for dests in members.values(): + if not any(self.file_status[d] == Status.OK for d in dests): + continue + for dest in dests: + if self.file_status[dest] == Status.MISSING: + self.file_required[dest] = False + self.file_severity[dest] = compute_severity( + Status.MISSING, False, self.run.mode + ) + for result in self.results_at.get(dest, []): + result["required"] = False + + def credit_placed(self, placed: set[str]) -> None: + """An existence frontend is satisfied by any file at the path, and the + builder fills a free platform destination with a core's file.""" + for dest, status in self.file_status.items(): + if status == Status.MISSING and self.run.full(dest) in placed: + self.file_status[dest] = Status.OK + self.file_severity[dest] = Severity.OK + for result in self.results_at.get(dest, []): + result["status"] = Status.OK + + def severity_counts(self) -> tuple[dict[str, int], dict[str, list[str]]]: + """Destinations by severity, and the missing ones that are not firmware.""" + counts = { + Severity.OK: 0, + Severity.INFO: 0, + Severity.WARNING: 0, + Severity.CRITICAL: 0, + } + not_firmware: dict[str, list[str]] = {} + for dest, s in self.file_severity.items(): + category = self.file_category.get(dest, BIOS) + if category != BIOS and self.file_status.get(dest) == Status.MISSING: + not_firmware.setdefault(category, []).append(dest) + continue + counts[s] = counts.get(s, 0) + 1 + return counts, not_firmware diff --git a/scripts/sitegen/emulatorpage.py b/scripts/sitegen/emulatorpage.py index 8ef5f4cbc..6964a293b 100644 --- a/scripts/sitegen/emulatorpage.py +++ b/scripts/sitegen/emulatorpage.py @@ -83,187 +83,6 @@ def availability_check( return _file_available -||||||| parent of 068513702 (refactor: move entry sources out of crossref) -def _emulator_slots(files: list[dict]) -> list[list[dict]]: - """The entries of each slot, as verify --emulator and the gaps page - count them, leaving out the slots the app ships.""" - from packs.crossrefsource import slot_key - - slots: dict[tuple, list[dict]] = {} - for f in files: - slots.setdefault(slot_key(f), []).append(f) - return [group for group in slots.values() if not all(comes_with_app(f) for f in group)] - - -def _set_names(value: object) -> list[str]: - """The sets an entry belongs to: group takes a name, a list or a map.""" - if isinstance(value, str): - return [value] - if isinstance(value, (list, dict)): - return [str(name) for name in value] - return [] - - -def _requirements(files: list[dict], groups: dict | None) -> list[list[dict]]: - """Each thing the emulator needs: the members of a required set, any one - of which fills it (DuckStation's ps-bios, 105 images), or a required - file of its own. load_emulator_profiles marks every member of a - required set required, so counted per file DuckStation read "105 - required" for one BIOS.""" - required_sets = {name for name, spec in (groups or {}).items() - if isinstance(spec, dict) and spec.get("required")} - sets: dict[str, list[dict]] = {} - alone: list[list[dict]] = [] - for f in files: - if f.get("required") is not True or comes_with_app(f): - continue - names = [name for name in _set_names(f.get("group")) if name in required_sets] - if names: - for name in names: - sets.setdefault(name, []).append(f) - else: - alone.append([f]) - return [*sets.values(), *alone] - - -def _regional_set(requirements: list[list[dict]]) -> list[dict]: - """The one requirement, a set whose members the code picks by the game's - region, or [] when there is no such single choice.""" - if len(requirements) != 1 or len(requirements[0]) < 2: - return [] - members = requirements[0] - if not all(f.get("region") for f in members): - return [] - return members if len({region_words(f["region"]) for f in members}) >= 2 else [] - - -def _emulator_file_summary(files: list[dict], groups: dict | None = None) -> list[str]: - """What the emulator reads, above its file table, and its categories. - - Counted by slot, as verify --emulator and the gaps page count: raze - lists every GRP its code accepts under one name, and holding one fills - the slot. Counted per entry, the page announced 46 missing where 12 - slots are empty. The files the app ships are counted apart: NetherSX2 - said "4 required" for one BIOS and three fonts in its package. A - required set counts once (`groups`). - """ - slots = _emulator_slots(files) - shipped = sum(1 for f in files if comes_with_app(f)) - requirements = _requirements(files, groups) - in_sets = {id(f) for members in requirements for f in members} - req_slots = sum(1 for group in slots if any(id(f) in in_sets for f in group)) - req_count = len(requirements) - optional = len(slots) - req_slots - hle_count = sum(1 for group in slots if any(f.get("hle_fallback") for f in group)) - - # Sentences, one number format: the line read "1,563 files | 164 - # required, 1399 optional | 1563 in repo". - total = f"**{count_text(len(slots), 'file')}**" - if sum(len(group) for group in slots) != len(slots): - total += f" ({sum(len(group) for group in slots):,} accepted versions)" - line = f"{total}: {req_count:,} required, {optional:,} optional." - if any(len(members) > 1 for members in requirements): - line += " Any one file of a required set fills it." - regional = _regional_set(requirements) or ( - [f for members in requirements for f in members] - if _regional_choice([f for members in requirements for f in members]) else []) - if regional: - # DuckStation takes the BIOS of the game's region: "3 required" - # read as "get all three". - line = f"{total}. One of {len(regional):,} is required, for the games' region." - if optional: - line += f" {optional:,} {'is' if optional == 1 else 'are'} optional." - if hle_count: - line += f" {hle_count:,} {'has' if hle_count == 1 else 'have'} an HLE fallback." - if shipped: - line += f" {count_text(shipped, 'more file')} {'comes' if shipped == 1 else 'come'} with the app." - lines = [line, ""] - - categories = [f.get("category", "bios") for f in files] - if "game_data" in categories or "bios_zip" in categories: - cats = [ - f"{categories.count(key):,} {label}" - for key, label in ( - ("bios", "BIOS"), ("bios_zip", "BIOS ZIPs"), ("game_data", "game data") - ) - if categories.count(key) - ] - lines.extend([f"By kind: {series(cats)}.", ""]) - return lines - - -def _emulator_held_line(files: list[dict], available: Callable[[dict], bool]) -> list[str]: - """What this collection holds of them, one quiet line under the table: - a reader comes for what the emulator needs, the project's counts after.""" - slots = _emulator_slots(files) - if not slots: - return [] - in_repo = sum(1 for group in slots if any(available(f) for f in group)) - unsourceable = sum( - 1 for group in slots - if not any(available(f) for f in group) and all(f.get("unsourceable") for f in group) - ) - held = [f"{in_repo:,} in repo", f"{len(slots) - in_repo - unsourceable:,} missing"] - if unsourceable: - held.append(f"{unsourceable:,} unsourceable") - return [f"

In this collection: {series(held)}.

", ""] - - -def _data_member_table(members: dict[str, dict], names: list[str], anchors: set[str]) -> list[str]: - """A data directory's files with their size and sha1, each sha1 an - anchor the first time the page lists it (``anchors``, the page's ids).""" - table = ["| File | Size | SHA1 |", "|------|-----:|------|"] - for member in names: - info = members[member] - sha1 = str(info.get("sha1", "")) - # One id per page: two members can hold the same bytes (every empty - # file), and Dolphin's trees share Sys. - anchor = card_anchor(sha1) - span = "" if anchor in anchors else f'' - anchors.add(anchor) - table.append(f"| {span}{code_span(member)} | {size_text(int(info.get('size', 0)))} | {code_span(sha1)} |") - return table - - -def _data_tree_page(ref: str, entry: dict, pages: list[tuple[str, list[str]]], - index: int, registry: PageRegistry) -> str: - """One page of a large data directory's file list.""" - stem, names = pages[index] - members = registry.data_members.get(ref) or {} - part = f" (part {index + 1} of {len(pages)})" if len(pages) > 1 else "" - read_by = series([f"[{escape_tags(display)}]({key}.md#data-directories)" - for key, display in registry.data_readers.get(ref, [])]) - # A file list out of the search: "dolphin" found three parts of the - # dolphin-sys tree, on their title, before the Dolphin page. - front: dict = {"level": "reference", "search": "exclude"} - # The reader the tree is named after (dolphin for dolphin-sys), else - # the first by name. - readers = registry.data_readers.get(ref) or [] - owner = max(readers, default=None, - key=lambda reader: len(reader[0]) if ref.startswith(f"{reader[0]}-") else 0) - if owner: - head = _part_front_matter( - (owner[1], f"{owner[0]}.md"), - [(f"The {ref} data directory, part {n}", f"{other}.md") - for n, (other, _names) in enumerate(pages, 1)], index, front) - else: - head = ["---", yaml.safe_dump(front, sort_keys=False, allow_unicode=True).rstrip("\n"), - "---", ""] - lines = [ - *head, - f"# The {ref} data directory{part}", "", - f"{entry.get('description') or 'A data directory'}: " - f"{count_text(len(members), 'file')}, as the packs ship them." - + (f" Read by {read_by}." if read_by else ""), "", - ] - if len(pages) > 1: - lines.extend([", ".join(f"[part {i}]({other}.md)" if other != stem else f"part {i}" - for i, (other, _names) in enumerate(pages, 1)), ""]) - lines.extend(search_excluded(_data_member_table(members, names, set()))) - lines.extend(["", date_line()]) - return "\n".join(lines) + "\n" - - # An emulator page lists at most this many file cards: MAME's 1,564 made a # 3 MB page. Past it, the cards go to pages of their own and the emulator's # page keeps a table of every entry, each row holding the card's old diff --git a/tests/sources.py b/tests/sources.py index 939770340..178bd443e 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -28,7 +28,8 @@ COMMANDS = { "packs/declsettle.py", ), "verify.py": ( - "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", + "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/platformtally.py", + "packs/emulatorcheck.py", "packs/report.py", "packs/shares.py", "packs/verifyplatforms.py", "packs/verifysummary.py", "packs/verifyoutput.py", "packs/strictgate.py", "packs/verifyoptions.py", "packs/verifyprint.py", "packs/runscope.py", "packs/verifyrun.py", diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index b64f41607..841f652e7 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -1595,7 +1595,7 @@ class OneBaselineVerdict(unittest.TestCase): def test_verify_finds_the_cached_release_asset(self): # verify imports the scripts directory's modules by their bare names. from resolve import packfiles as packresolve - from scripts.packs.coverage import _resolve_for_platform + from scripts.packs.platformtally import _resolve_for_platform with tempfile.TemporaryDirectory() as directory: cached = Path(directory) / "BIG.PUP" @@ -5870,11 +5870,11 @@ class GapsPageCountsOneWay(unittest.TestCase): self.assertIn("bios/quasi88/N88_KNJ1.ROM", shown) def test_verify_marks_the_settled_entry(self): - from packs import coverage as packs_coverage + from packs import platformtally from packs import verdicts result = {"name": "cdibios.zip", "status": verdicts.Status.UNTESTED} - self.assertTrue(packs_coverage._twin_unmet(result, "arcade")) + self.assertTrue(platformtally._twin_unmet(result, "arcade")) self.assertEqual(result["settled_by"], "arcade") diff --git a/tests/test_retrodeck_component_md5.py b/tests/test_retrodeck_component_md5.py index cab71a153..36b80fb53 100644 --- a/tests/test_retrodeck_component_md5.py +++ b/tests/test_retrodeck_component_md5.py @@ -26,7 +26,8 @@ from pathlib import Path from exporter import discover_exporters from model.declarations import declared_components -from packs.coverage import _twin_unmet, verify_platform +from packs.platformtally import _twin_unmet +from packs.coverage import verify_platform from resolve.reconcile import build_native_model from scraper.base_scraper import systems_from_requirements from scripts.scraper import retrodeck_scraper diff --git a/tests/test_slots.py b/tests/test_slots.py index ca1bc6e3b..7446d9f13 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -545,7 +545,7 @@ class TestBuilderAndVerifierAgree(unittest.TestCase): # override lookup both sides must perform. The old anchor was a string # the test above forbids, so the window was the whole file. mode_test = re.compile(r"""[=!]=\s*["'](?:md5|sha1|existence)["']""") - for name in ("packs/platformpack.py", "packs/manifestbuild.py", "packs/coverage.py"): + for name in ("packs/platformpack.py", "packs/manifestbuild.py", "packs/platformtally.py"): source = Path(__file__).resolve().parents[1] / "scripts" / name body = source.read_text(encoding="utf-8") anchors = [m.start() for m in re.finditer(r"slot_overrides\.get\(", body)] diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 4c9d0c627..6e90ccd8f 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -25,7 +25,7 @@ import pipeline from orchestrate import guards, labels, prepare, runner from resolve import truth from resolve.platformdiff import diff_platform_truth -from packs import coverage +from packs import platformtally from packs import report as packs_report from packs import verdicts from packs import verifysummary @@ -564,7 +564,7 @@ class TheVerifySummaryCountsDiscrepancies(unittest.TestCase): def test_a_shared_destination_names_the_path_and_both_sides(self): result = {"name": "disk.rom", "status": verdicts.Status.UNTESTED} entry = {"name": "disk.rom", "md5": "793f8678" + "0" * 24} - self.assertTrue(coverage._twin_unmet( + self.assertTrue(platformtally._twin_unmet( result, "coco", entry, "nec-pc-88", "bios/disk.rom" )) message = result["discrepancy"]