fix: check each built variant as verify-packs does

The build skipped conformance on every required-only, platform-only and
truth pack while --verify-packs held the same pack to its own variant,
so an --all-variants run passed packs the verifier could fail.
check_pack_conformance reads the variant from the pack name and both
paths call it; the finalizer is told the variants the run built.
baseline_shortfall moves beside the check, narrows_contents goes.
This commit is contained in:
Abdessamad Derraz committed 2026-11-21 21:42:19 +01:00
1 parent e0cbf35adc
commit 3df143cbe1
9 files changed
+181 -124

No files matched your search

+24 -39
View File
@@ -17,24 +17,14 @@ from core.options import reject_unknown
from model.registry import list_registered_platforms
from model.targets import load_target_config
from packs.archive import write_generated_member
from packs.integrity import verify_pack, verify_pack_against_platform
from packs.naming import expected_pack_names, narrows_contents, pack_archives
from packs.integrity import check_pack_conformance, verify_pack
from packs.naming import expected_pack_names, pack_archives
from packs.scope import annotate_pack_systems
if TYPE_CHECKING:
from typing_extensions import Unpack
def baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
parts.append(f"{excluded} unsafe excluded")
if absent:
parts.append(f"{absent} not in the collection")
return parts
# Post-generation pack verification + manifest
@@ -94,6 +84,7 @@ class FinalizeOptions(TypedDict, total=False):
no_game_data: bool
pack_systems_by_name: dict[str, dict] | None
built: Iterable[str] | None
variants: tuple[tuple[str, bool], ...]
@dataclass(frozen=True)
@@ -109,23 +100,14 @@ class _FinalizeSettings:
no_game_data: bool = False
pack_systems_by_name: dict[str, dict] | None = None
built: Iterable[str] | None = None
variants: tuple[tuple[str, bool], ...] = (("full", False),)
def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> bool:
"""Stage 2 for one platform of a pack: extract and verify against its
config. Prints the platform's line and its errors."""
(
p_ok,
_total,
_matched,
p_errors,
bl_checked,
bl_present,
core_checked,
core_present,
bl_excluded,
bl_absent,
) = verify_pack_against_platform(
config, under the variant the pack was built as. Prints the platform's
line and its errors."""
result = check_pack_conformance(
zip_path,
pname,
opts.platforms_dir,
@@ -136,19 +118,20 @@ def _conforms(zip_path: str, pname: str, db: dict, opts: _FinalizeSettings) -> b
target_cores=_target_cores_for(pname, opts.target_name, opts.platforms_dir),
no_game_data=opts.no_game_data,
)
status = "OK" if p_ok else "FAILED"
exclusion_note = "".join(
f", {part}" for part in baseline_shortfall(bl_excluded, bl_absent)
)
if result is None:
# One BIOS per slot: the slot choice is not replayed.
return True
status = "OK" if result.ok else "FAILED"
exclusion_note = "".join(f", {part}" for part in result.shortfall)
print(
f" platform {pname}: {bl_present}/{bl_checked} baseline present"
f" platform {pname}: {result.baseline_present}/{result.baseline_checked} baseline present"
f"{exclusion_note}, "
f"{core_present}/{core_checked} cores present, {status}"
f"{result.core_present}/{result.core_checked} cores present, {status}"
)
if not p_ok:
for err in p_errors:
if not result.ok:
for err in result.errors:
print(f" {err}")
return p_ok
return result.ok
def verify_and_finalize_packs(
@@ -166,6 +149,9 @@ def verify_and_finalize_packs(
reopened, recompressed and given a manifest without its pack_systems,
which made the installer refuse to narrow it. None takes every pack.
``variants`` lists the (source, required_only) combinations the run
built, so each narrowed pack is checked as --verify-packs checks it.
Two-stage verification:
1. Hash check against database.json (integrity)
2. Extract + verify against platform config (conformance)
@@ -183,7 +169,7 @@ def verify_and_finalize_packs(
registered = list_registered_platforms(opts.platforms_dir)
expected = expected_pack_names(
registered, opts.platforms_dir, opts.regions, opts.target_name,
no_game_data=opts.no_game_data,
opts.variants, no_game_data=opts.no_game_data,
)
packs = pack_archives(output_dir)
if opts.built is not None:
@@ -214,12 +200,11 @@ def verify_and_finalize_packs(
annotate_pack_systems(manifest, (opts.pack_systems_by_name or {}).get(name))
inject_manifest(zip_path, manifest)
# Stage 2: platform conformance (extract + verify)
# Skipped for filtered/split/custom packs (intentionally partial)
# Stage 2: platform conformance (extract + verify), each variant
# held to its own expectation. Skipped for split and system packs
# (intentionally partial).
if opts.skip_conformance:
continue
if narrows_contents(name):
continue
for pname in pack_to_platform.get(name, []):
if not _conforms(zip_path, pname, db, opts):
all_ok = False
+66 -3
View File
@@ -32,6 +32,7 @@ from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
import os
from packs.extras import platform_region_groups
from packs.naming import pack_variant
from packs.paths import flat_arcname
from resolve.nativemode import reads_file_contents
from resolve import regions as resolve_regions
@@ -596,16 +597,21 @@ def _same_content(zf: zipfile.ZipFile, member: str, local: str) -> bool:
return is_archive_path(local) and _same_members(zf, member, local)
class PlatformCheckOptions(TypedDict, total=False):
"""The keyword options of verify_pack_against_platform."""
class ConformanceOptions(TypedDict, total=False):
"""The keyword options of check_pack_conformance."""
emulators_dir: str
emu_profiles: dict | None
regions: list[str] | None
data_registry: dict | None
no_game_data: bool
class PlatformCheckOptions(ConformanceOptions, total=False):
"""The keyword options of verify_pack_against_platform."""
source: str
required_only: bool
no_game_data: bool
@dataclass(frozen=True)
@@ -1006,3 +1012,60 @@ def verify_pack_against_platform(
baseline.excluded,
baseline.absent,
)
def baseline_shortfall(excluded: int, absent: int) -> list[str]:
"""Why a verified pack holds fewer baseline files than the platform declares."""
parts = []
if excluded:
parts.append(f"{excluded} unsafe excluded")
if absent:
parts.append(f"{absent} not in the collection")
return parts
@dataclass(frozen=True)
class PackConformance:
"""A pack checked against one platform, as verify_pack_against_platform returns it."""
ok: bool
checked: int
present: int
errors: list[str]
baseline_checked: int
baseline_present: int
core_checked: int
core_present: int
baseline_excluded: int
baseline_absent: int
@property
def shortfall(self) -> list[str]:
"""Why the baseline holds fewer files than the platform declares."""
return baseline_shortfall(self.baseline_excluded, self.baseline_absent)
def check_pack_conformance(
zip_path: str,
platform_name: str,
platforms_dir: str,
db: dict | None = None,
*,
target_cores: set[str] | None = None,
**options: Unpack[ConformanceOptions],
) -> PackConformance | None:
"""A pack checked against its platform under the variant its name says.
The build and --verify-packs both read this, so a pack gets one verdict:
a required-only, platform-only or truth pack is held to its own
expectation, never skipped by one and failed by the other. None for a
one-per-slot pack, whose slot choice the check does not replay.
"""
variant = pack_variant(os.path.basename(zip_path))
if variant is None:
return None
source, required_only = variant
return PackConformance(*verify_pack_against_platform(
zip_path, platform_name, platforms_dir, db,
target_cores=target_cores, source=source, required_only=required_only, **options,
))
+3 -38
View File
@@ -261,48 +261,13 @@ def expected_pack_names(
return names
def _content_narrowing_tags() -> tuple[str, ...]:
"""Tags naming a pack that holds fewer files than the platform declares.
Read from the name builder rather than retyped, so the two cannot drift.
Region and target are absent on purpose: both are handed to the check
itself, which narrows its expectation instead of skipping it.
"""
# (source, one_per_slot, required_only), one dimension at a time.
dimensions = (
("platform", False, False),
("truth", False, False),
("full", True, False),
("full", False, True),
)
tags: list[str] = []
for source, one_per_slot, required_only in dimensions:
tags.extend(
tag
for tag, _label in pack_narrowings(source, None, None, one_per_slot, required_only)
)
return tuple(tags)
_CONTENT_NARROWING_TAGS = _content_narrowing_tags()
def narrows_contents(pack_name: str) -> bool:
"""True when a pack holds fewer files than the platform declares.
A source-restricted or required-only build is narrower by design, so the
full platform expectation does not apply to it and conformance is skipped.
Region is not listed: the region filter is passed to the check itself, and
a hardware target is passed the same way.
"""
return any(f"{tag}_" in pack_name for tag in _CONTENT_NARROWING_TAGS)
def pack_variant(pack_name: str) -> tuple[str, bool] | None:
"""The (source, required_only) a pack was built as, read from its name.
None for a one-per-slot pack, whose slot choice the check does not
replay. The tags come from the name builder, as for narrows_contents.
replay. The tags come from the name builder rather than retyped, so the
two cannot drift. Region and target are not variants: both are handed to
the check itself, which narrows its expectation instead of skipping it.
"""
def tagged(**dimension: object) -> bool:
tags = [
+17 -24
View File
@@ -12,9 +12,8 @@ from model.database import load_database
from model.profiles import load_emulator_profiles
from model.registry import list_release_pack_platforms, load_data_dir_registry
from model.targets import target_scope
from packs.finalize import baseline_shortfall
from packs.integrity import verify_pack_against_platform
from packs.naming import expected_pack_names, pack_variant
from packs.integrity import check_pack_conformance
from packs.naming import expected_pack_names
from packs.variants import ALL_VARIANTS
@@ -56,16 +55,7 @@ def _check_pack(
tc: set[str] | None,
) -> list[str] | None:
"""Check one pack and print its line. Its errors, or None when it passed."""
variant = pack_variant(pack_name)
if variant is None:
# One BIOS per slot: the slot choice is not replayed here.
print(
f" {platform_name} [{pack_name}]: hashes checked during the build; "
"one per slot by design, so not compared to the platform's full list"
)
return None
source, required_only = variant
result = verify_pack_against_platform(
result = check_pack_conformance(
zip_path,
platform_name,
check.platforms_dir,
@@ -75,28 +65,31 @@ def _check_pack(
regions=check.regions,
data_registry=check.data_registry,
target_cores=tc,
source=source,
required_only=required_only,
no_game_data=check.no_game_data,
)
(ok, _checked, _present, errors, bl_checked, bl_present,
core_checked, core_present, bl_excluded, bl_absent) = result
if result is None:
# One BIOS per slot: the slot choice is not replayed here.
print(
f" {platform_name} [{pack_name}]: hashes checked during the build; "
"one per slot by design, so not compared to the platform's full list"
)
return None
# These explain a baseline short of its total: a dump whose hash
# the frontend refuses is left out on purpose, and a file the
# collection does not hold cannot be packed (verify reports it).
shortfall = ", ".join(baseline_shortfall(bl_excluded, bl_absent))
shortfall = ", ".join(result.shortfall)
excluded = f" ({shortfall})" if shortfall else ""
counts = (
f"{bl_present}/{bl_checked} baseline{excluded}, "
f"{core_present}/{core_checked} cores"
f"{result.baseline_present}/{result.baseline_checked} baseline{excluded}, "
f"{result.core_present}/{result.core_checked} cores"
)
if ok:
if result.ok:
print(f" {platform_name} [{pack_name}]: OK ({counts})")
return None
print(f" {platform_name} [{pack_name}]: FAIL ({counts}, {len(errors)} errors)")
for err in errors:
print(f" {platform_name} [{pack_name}]: FAIL ({counts}, {len(result.errors)} errors)")
for err in result.errors:
print(f" {err}")
return errors
return result.errors
def run_verify_packs(args: argparse.Namespace) -> bool:
+1
View File
@@ -234,6 +234,7 @@ def finalize_platform_packs(
regions=getattr(args, "regions", None),
target_name=args.target,
no_game_data=getattr(args, "no_game_data", False),
variants=run_variants(args),
)
if args.split:
for entry in os.listdir(args.output_dir):
+2 -2
View File
@@ -4941,8 +4941,8 @@ class VerifyPacksSaysWhatItExcluded(unittest.TestCase):
source = script_source("generate_pack.py")
body = source[source.index("def _check_pack"):]
body = body[:body.index("\ndef ")]
self.assertIn("bl_excluded, bl_absent) = result", body)
self.assertIn("baseline_shortfall(bl_excluded, bl_absent)", body)
self.assertIn("result.shortfall", body)
self.assertIn("for err in result.errors", body)
shortfall = source[source.index("def baseline_shortfall"):]
self.assertIn("unsafe excluded", shortfall[:shortfall.index("\ndef ")])
self.assertNotIn("errors[:5]", body)
+15 -15
View File
@@ -6374,13 +6374,13 @@ struct BurnDriver BurnDrvneogeo = {
held every targeted pack to the platform's whole system list and
core set, so a correct build exited non-zero on hundreds of files it
was never asked to carry. Region was already passed to the check, and
target has to travel the same way, which is why the pack is not in
the skip list.
target has to travel the same way, which is why the pack is checked
as a full pack.
"""
import inspect
from packs import integrity as packverify
from packs.naming import narrows_contents, pack_narrowings
from packs.naming import pack_narrowings, pack_variant
source = inspect.getsource(packverify.verify_pack_against_platform)
self.assertIn(
@@ -6402,9 +6402,9 @@ struct BurnDriver BurnDrvneogeo = {
# And the pack must not be skipped instead: skipping checks nothing.
for target in ("nintendo-switch", "switch", "rpi4"):
tag = pack_narrowings("full", None, target, False, False)[0][0]
self.assertFalse(
narrows_contents(f"Platform_1.0{tag}_BIOS_Pack.zip"),
f"a pack built for {target} would skip conformance entirely",
self.assertEqual(
pack_variant(f"Platform_1.0{tag}_BIOS_Pack.zip"), ("full", False),
f"a pack built for {target} would be checked as a narrowed variant",
)
def test_standalone_mode_names_itself(self):
@@ -6661,23 +6661,23 @@ struct BurnDriver BurnDrvneogeo = {
)
self.assertEqual(len(result), len(annotated))
def test_narrowed_variants_skip_conformance(self):
from packs.naming import narrows_contents
def test_narrowed_variants_are_checked_as_built(self):
from packs.naming import pack_variant
for narrowed in (
"EmuDeck_2.3.8_Required_BIOS_Pack.zip",
"EmuDeck_2.3.8_Platform_BIOS_Pack.zip",
"EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip",
"EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip",
for narrowed, variant in (
("EmuDeck_2.3.8_Required_BIOS_Pack.zip", ("full", True)),
("EmuDeck_2.3.8_Platform_BIOS_Pack.zip", ("platform", False)),
("EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip", ("truth", True)),
("EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip", ("full", True)),
):
self.assertTrue(narrows_contents(narrowed), narrowed)
self.assertEqual(pack_variant(narrowed), variant, narrowed)
for full in (
"EmuDeck_2.3.8_BIOS_Pack.zip",
"EmuDeck_2.3.8_NorthAmerica_BIOS_Pack.zip",
"RetroArch_v1.22.2_Switch_BIOS_Pack.zip",
):
self.assertFalse(narrows_contents(full), full)
self.assertEqual(pack_variant(full), ("full", False), full)
def test_target_tag_formats_hardware_names(self):
from packs.naming import _target_tag
+50 -1
View File
@@ -75,7 +75,6 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase):
), \
mock.patch.object(packs_finalize, "inject_manifest"), \
mock.patch.object(packs_finalize, "_target_cores_for", return_value=None), \
mock.patch.object(packs_finalize, "verify_pack_against_platform", record), \
mock.patch.object(packverify, "verify_pack_against_platform", record):
packs_finalize.verify_and_finalize_packs(
str(out), {"files": {}, "indexes": {}},
@@ -85,5 +84,55 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase):
self.assertEqual(seen.get("emulators_dir"), "fixture-emulators")
class TheBuildChecksEachVariantAsVerifyPacksDoes(unittest.TestCase):
"""The build skipped conformance on every narrowed pack while
--verify-packs held the same pack to its own expectation, so one pack
had two verdicts."""
def test_a_narrowed_pack_is_checked_under_its_variant(self):
seen: list[tuple] = []
def record(zip_path, platform_name, *args, **kwargs):
seen.append((Path(zip_path).name, kwargs.get("source"), kwargs.get("required_only")))
return True, 0, 0, [], 0, 0, 0, 0, 0, 0
names = ["Fix_BIOS_Pack.zip", "Fix_Required_BIOS_Pack.zip", "Fix_Truth_BIOS_Pack.zip"]
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(packs_finalize, "list_registered_platforms", return_value=["fix"]), \
mock.patch.object(packs_finalize, "expected_pack_names",
return_value={"fix": set(names)}), \
mock.patch.object(packs_finalize, "pack_archives", return_value=names), \
mock.patch.object(
packs_finalize, "verify_pack",
return_value=(True, {"summary": {
"verified": 0, "total_files": 0, "untracked": 0, "errors": 0,
}, "errors": []}),
), \
mock.patch.object(packs_finalize, "inject_manifest"), \
mock.patch.object(packs_finalize, "_target_cores_for", return_value=None), \
mock.patch.object(packverify, "verify_pack_against_platform", record):
packs_finalize.verify_and_finalize_packs(
tmp, {"files": {}, "indexes": {}}, platforms_dir="fixture-platforms",
)
self.assertEqual(seen, [
("Fix_BIOS_Pack.zip", "full", False),
("Fix_Required_BIOS_Pack.zip", "full", True),
("Fix_Truth_BIOS_Pack.zip", "truth", False),
])
def test_the_run_names_the_variants_it_built(self):
with tempfile.TemporaryDirectory() as tmp, mock.patch.object(
platformrun, "verify_and_finalize_packs", return_value=True
) as finalize:
args = argparse.Namespace(
all_variants=True, source="full", required_only=False,
platforms_dir="p", target=None, split=False, emulators_dir="e",
regions=[], one_per_slot=False, offline=True, bios_dir="bios",
output_dir=tmp, verify_packs=False,
)
platformrun.run_platform_packs(args, [], {}, {}, {}, {}, {}, None)
self.assertEqual(len(finalize.call_args.kwargs["variants"]), 6)
if __name__ == "__main__":
unittest.main()
+3 -2
View File
@@ -15,6 +15,7 @@ import json
import os
import tempfile
import unittest
from packs import integrity
from packs import naming
from packs import packcheck
from packs import variants
@@ -70,7 +71,7 @@ class VerifyPackChoice(unittest.TestCase):
self.variants: list[tuple[str, bool]] = []
with mock.patch.object(packcheck, "verify_pack_against_platform", record):
with mock.patch.object(integrity, "verify_pack_against_platform", record):
self.ok = packcheck.run_verify_packs(args)
return checked
@@ -143,7 +144,7 @@ class VerifyPackChoice(unittest.TestCase):
self._touch(pack)
out, err = io.StringIO(), io.StringIO()
failed = (False, 0, 0, ["x: missing"], 1, 0, 1, 1, 0, 0)
with mock.patch.object(packcheck, "verify_pack_against_platform",
with mock.patch.object(integrity, "verify_pack_against_platform",
return_value=failed), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
self.assertFalse(packcheck.run_verify_packs(self._args()))