From 9814bb1234fdc40399e0e65db463ba71b6b8da19 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:52:09 +0100 Subject: [PATCH] refactor: step 5 reads counts both tools record --- scripts/generate_pack.py | 4 + scripts/orchestrate/build.py | 48 +++++--- scripts/orchestrate/checks.py | 16 +-- scripts/orchestrate/consistency.py | 191 ++++++++++++++--------------- scripts/orchestrate/reports.py | 143 --------------------- scripts/packs/packcounts.py | 53 ++++++++ scripts/packs/packoptions.py | 16 +++ scripts/packs/platformpack.py | 14 ++- scripts/packs/platformrun.py | 27 ++-- scripts/packs/report.py | 30 +++-- scripts/packs/variants.py | 2 +- scripts/packs/verifyoutput.py | 21 +++- scripts/pipeline.py | 6 +- scripts/verify.py | 4 +- tests/sources.py | 4 +- tests/test_audit_regressions.py | 161 +++++++++--------------- tests/test_e2e.py | 55 +++++++++ tests/test_pack_destinations.py | 16 ++- tests/test_release_packs.py | 37 +++--- tests/test_verify_release_asset.py | 2 +- wiki/tools.md | 10 +- 21 files changed, 428 insertions(+), 432 deletions(-) delete mode 100644 scripts/orchestrate/reports.py create mode 100644 scripts/packs/packcounts.py diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 8e4232a8d..23d2bc9a0 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -166,6 +166,10 @@ def build_parser() -> argparse.ArgumentParser: action="store_true", help="Extract and verify pack integrity (path + hash)", ) + parser.add_argument( + "--counts", metavar="FILE", + help="Also write each full pack's counts as JSON (the pipeline's consistency check)", + ) return parser diff --git a/scripts/orchestrate/build.py b/scripts/orchestrate/build.py index c38c28f0e..4deec5729 100644 --- a/scripts/orchestrate/build.py +++ b/scripts/orchestrate/build.py @@ -19,13 +19,23 @@ from orchestrate.results import SKIPPED from packs.datadirs import hold_data_dirs +def scratch_file(prefix: str) -> str: + """An empty JSON file in the repository's tmp/, removed when the run ends.""" + scratch = REPO_ROOT / "tmp" + scratch.mkdir(exist_ok=True) + fd, path = tempfile.mkstemp(prefix=prefix, suffix=".json", dir=scratch) + os.close(fd) + atexit.register(Path(path).unlink, missing_ok=True) + return path + + def verify_steps( args: argparse.Namespace, results: dict, held: contextlib.ExitStack -) -> tuple[bool, str, str]: +) -> tuple[bool, str]: """Steps 3 to 3b: verify, identities, slots. - Returns whether they passed, verify's output and the file of the paths - each pack holds by its report. + Returns whether they passed and the file of what each pack holds by + verify's report: its counts and paths. """ all_ok = True # Every step from here reads the data directory trees: verify, the packs, @@ -36,15 +46,9 @@ def verify_steps( # exclusive. hold_data_dirs(held, load_data_dir_registry(PLATFORMS_DIR)) - # Step 3: Verify. The paths each pack holds by this report go to a file - # step 5 compares with the archives. - scratch = REPO_ROOT / "tmp" - scratch.mkdir(exist_ok=True) - fd, destinations_file = tempfile.mkstemp( - prefix="verify-destinations.", suffix=".json", dir=scratch - ) - os.close(fd) - atexit.register(Path(destinations_file).unlink, missing_ok=True) + # Step 3: Verify. The counts and paths each pack holds by this report go + # to a file step 5 compares with the build's own counts and archives. + destinations_file = scratch_file("verify-destinations.") verify_cmd = [ sys.executable, "scripts/verify.py", "--all", "--strict", "--destinations", destinations_file, @@ -55,7 +59,7 @@ def verify_steps( # The packs of step 4 fetch no release asset: a missing one is # missing on both sides. verify_cmd.append("--offline") - ok, verify_output = runner.run(verify_cmd, STEP_LABELS["verify"]) + ok, _ = runner.run(verify_cmd, STEP_LABELS["verify"]) results["verify"] = ok all_ok = all_ok and ok @@ -82,7 +86,7 @@ def verify_steps( ok, _ = runner.run(slots_cmd, "3b slot arbitration") results["slots"] = ok all_ok &= ok - return all_ok, verify_output, destinations_file + return all_ok, destinations_file def purge_stale_packs(output_dir: str) -> None: @@ -111,14 +115,16 @@ def purge_stale_packs(output_dir: str) -> None: sys.exit(1) -def pack_command(args: argparse.Namespace) -> list[str]: - """The step 4 command: every platform's pack.""" +def pack_command(args: argparse.Namespace, counts_file: str) -> list[str]: + """The step 4 command: every platform's pack, its counts to *counts_file*.""" pack_cmd = [ sys.executable, "scripts/generate_pack.py", "--all", "--output-dir", args.output_dir, + "--counts", + counts_file, ] if args.offline: pack_cmd.append("--offline") @@ -138,14 +144,16 @@ def pack_command(args: argparse.Namespace) -> list[str]: def pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]: """Steps 4 to 4c: packs, install manifests, target manifests. - Returns whether they passed and the pack build's output. + Returns whether they passed and the file of the full packs' counts, + empty when no pack was built. """ all_ok = True # Step 4: Generate packs - pack_output = "" + pack_counts_file = "" if not args.skip_packs: purge_stale_packs(args.output_dir) - ok, pack_output = runner.run(pack_command(args), STEP_LABELS["generate_packs"]) + pack_counts_file = scratch_file("pack-counts.") + ok, _ = runner.run(pack_command(args, pack_counts_file), STEP_LABELS["generate_packs"]) results["generate_packs"] = ok all_ok = all_ok and ok else: @@ -193,7 +201,7 @@ def pack_steps(args: argparse.Namespace, results: dict) -> tuple[bool, str]: else: skip_notice("generate_target_manifests", "--skip-packs") results["generate_target_manifests"] = SKIPPED - return all_ok, pack_output + return all_ok, pack_counts_file def index_steps(results: dict) -> bool: diff --git a/scripts/orchestrate/checks.py b/scripts/orchestrate/checks.py index eecb977e4..5b18348e3 100644 --- a/scripts/orchestrate/checks.py +++ b/scripts/orchestrate/checks.py @@ -5,12 +5,13 @@ from __future__ import annotations import argparse import sys +from core.paths import PLATFORMS_DIR +from model.registry import list_release_pack_platforms from orchestrate import runner from orchestrate.consistency import check_consistency, check_pack_destinations from orchestrate.emulatorpacks import check_emulator_packs from orchestrate.labels import STEP_LABELS, skip_notice, step_title from orchestrate.narrowed import check_narrowed_packs -from orchestrate.reports import release_pack_keys from orchestrate.results import SKIPPED from orchestrate.splitcheck import check_split_packs @@ -36,8 +37,7 @@ def check_steps( args: argparse.Namespace, results: dict, *, - pack_output: str, - verify_output: str, + pack_counts_file: str, destinations_file: str, ) -> bool: """Steps 5 and 6: verify against the packs, then the packs' integrity.""" @@ -46,16 +46,16 @@ def check_steps( # built only a reduced one (--source platform or truth) has nothing to # compare it with, and says so instead of failing on an empty parse. full_pack_built = args.source == "full" or args.all_variants - if pack_output and verify_output and not full_pack_built: + if pack_counts_file and not full_pack_built: skip_notice("consistency", "no full pack built") results["consistency"] = SKIPPED - elif pack_output and verify_output: + elif pack_counts_file: ok = check_consistency( - verify_output, pack_output, - release_pack_keys(), + destinations_file, pack_counts_file, + set(list_release_pack_platforms(PLATFORMS_DIR)), ) # Counts can agree while the paths differ, both ways at once. - ok = check_pack_destinations(destinations_file, pack_output) and ok + ok = check_pack_destinations(destinations_file, pack_counts_file) and ok ok = check_emulator_packs(full=args.full_narrowings) and ok ok = check_narrowed_packs(full=args.full_narrowings) and ok ok = check_split_packs() and ok diff --git a/scripts/orchestrate/consistency.py b/scripts/orchestrate/consistency.py index 96ecb5e23..c1b5c3540 100644 --- a/scripts/orchestrate/consistency.py +++ b/scripts/orchestrate/consistency.py @@ -2,108 +2,107 @@ from __future__ import annotations +import json from pathlib import Path from core.paths import PLATFORMS_DIR from orchestrate import compare -from packs.archive import is_pack_note from orchestrate.labels import STEP_LABELS, step_title -from orchestrate.reports import ( - match_key, - parse_pack_counts, - parse_pack_exclusions, - parse_pack_extras, - parse_pack_paths, - parse_verify_counts, - parse_verify_extras, -) +from packs.archive import is_pack_note +from packs.packcounts import read_pack_counts + + +def read_records(destinations_file: str, counts_file: str) -> tuple[dict, list[dict]] | None: + """verify's records by registry id and the build's full packs, or None + when either file cannot be read (the step that writes it failed).""" + try: + verify = json.loads(Path(destinations_file).read_text()) + packs = read_pack_counts(counts_file) + except (OSError, ValueError) as exc: + print(f" unreadable counts ({exc})") + return None + if not isinstance(verify, dict): + print(f" unreadable counts ({destinations_file} holds no record per platform)") + return None + return verify, packs + + +def _platform_agrees(record: dict, pack: dict) -> bool: + """One platform's verify record against the pack built for it, printed.""" + label, ok = record["label"], True + if record["core_files"] != pack["core_files"]: + # The cores' share: the base check passed RomM while verify + # counted 412 core files and game data and the pack held 60. + print( + f" {label}: MISMATCH core files verify " + f"{record['core_files']} != pack {pack['core_files']}" + ) + ok = False + v_ok, v_total, p_ok, p_total = record["ok"], record["total"], pack["ok"], pack["total"] + if v_total != p_total: + print(f" {label}: MISMATCH total verify {v_total} != pack {p_total}") + return False + if p_ok == v_ok: + print(f" {label}: verify {v_ok}/{v_total} == pack {p_ok}/{p_total} OK") + return ok + # Both ways are a disagreement. A pack exclusion never covers a file + # verify counts OK: an existence platform ships a file whose hash + # disagrees, and a hash platform's verify reports it untested, so the + # counts can only differ by a defect. + print( + f" {label}: MISMATCH pack {p_ok}/{p_total} OK " + f"({pack['unsafe_excluded']} unsafe excluded) != verify {v_ok}/{v_total}" + ) + return False + + +def compare_counts(verify: dict, packs: list[dict], released: set[str] | None = None) -> bool: + """Each platform's verify record against the full pack built for it. + + Both sides are keyed by registry id: *verify* as verify.py --destinations + writes it, *packs* as generate_pack.py --counts does. *released* holds + the registry ids of the platforms with a release pack. verify judges + every platform, the build only those: a platform outside it has no pack + to compare, which is no failure. + """ + all_ok = True + if not verify or not packs: + # Nothing read is nothing compared: a build that recorded no pack + # would otherwise pass the check without a single platform in it. + print(f" parsed {len(verify)} verify and {len(packs)} pack results: nothing to compare") + all_ok = False + pack_of = {platform: pack for pack in packs for platform in pack["platforms"]} + for pack in sorted(packs, key=lambda p: p["label"]): + if not any(platform in verify for platform in pack["platforms"]): + print(f" {pack['label']}: pack with no verify result") + all_ok = False + for platform, record in sorted(verify.items(), key=lambda item: (item[1]["label"], item[0])): + if platform in pack_of: + all_ok = _platform_agrees(record, pack_of[platform]) and all_ok + elif released is not None and platform not in released: + print(f" {record['label']}: {record['ok']}/{record['total']} " + "(no release pack, served by the installer)") + else: + print(f" {record['label']}: MISSING pack: verify judged " + f"{record['ok']}/{record['total']} but the build wrote no pack for it") + all_ok = False + return all_ok def check_consistency( - verify_output: str, pack_output: str, released: set[str] | None = None, + destinations_file: str, counts_file: str, released: set[str] | None = None, ) -> bool: - """Verify that check counts match between verify and pack for each platform. - - *released* holds the identities of the platforms with a release pack - (release_pack_keys). verify judges every platform, the build only those: - a platform outside it has no pack to compare, which is no failure. - """ - v = parse_verify_counts(verify_output) - p = parse_pack_counts(pack_output) - excluded = parse_pack_exclusions(pack_output) - verify_extras = parse_verify_extras(verify_output) - pack_extras = parse_pack_extras(pack_output) - + """Verify that check counts match between verify and pack for each platform.""" print(f"\n--- {step_title(STEP_LABELS['consistency'])} ---") - all_ok = True - if not v or not p: - # Nothing parsed is nothing compared: a changed output format would - # otherwise pass the check without a single platform in it. - print(f" parsed {len(v)} verify and {len(p)} pack results: nothing to compare") - all_ok = False - for p_label in sorted(p): - if not any(match_key(p_label) & match_key(v_label) for v_label in v): - print(f" {p_label}: pack with no verify result") - all_ok = False - - for v_label, (v_ok, v_total) in sorted(v.items()): - # Match by normalized name overlap. Platform display labels and - # registry IDs legitimately differ in punctuation and spacing - # (notably ``MiSTer FPGA`` vs ``misterfpga``). - p_match = None - v_names = match_key(v_label) - for p_label in p: - if v_names & match_key(p_label): - p_match = p_label - break - - if ( - p_match - and p_match in pack_extras - and v_label in verify_extras - and verify_extras[v_label] != pack_extras[p_match] - ): - # The cores' share: the base check passed RomM while verify - # counted 412 core files and game data and the pack held 60. - print( - f" {v_label}: MISMATCH core files verify " - f"{verify_extras[v_label]} != pack {pack_extras[p_match]}" - ) - all_ok = False - if p_match: - p_ok, p_total = p[p_match] - p_excluded = excluded.get(p_match, 0) - if v_total != p_total: - print(f" {v_label}: MISMATCH total verify {v_total} != pack {p_total}") - all_ok = False - elif p_ok == v_ok: - print( - f" {v_label}: verify {v_ok}/{v_total} == pack {p_ok}/{p_total} OK" - ) - else: - # Both ways are a disagreement. A pack exclusion never covers - # a file verify counts OK: an existence platform ships a file - # whose hash disagrees, and a hash platform's verify reports - # it untested, so the counts can only differ by a defect. - print( - f" {v_label}: MISMATCH pack {p_ok}/{p_total} OK " - f"({p_excluded} unsafe excluded) != verify {v_ok}/{v_total}" - ) - all_ok = False - elif released is not None and not (v_names & released): - print(f" {v_label}: {v_ok}/{v_total} (no release pack, served by the installer)") - else: - print(f" {v_label}: MISSING pack: verify judged {v_ok}/{v_total} " - "but the build wrote no pack for it") - all_ok = False - + records = read_records(destinations_file, counts_file) + all_ok = records is not None and compare_counts(*records, released) status = "OK" if all_ok else "FAILED" print(f"--- {step_title(STEP_LABELS['consistency'])}, counts: {status} ---") return all_ok def check_pack_destinations( - destinations_file: str, pack_output: str, platforms_dir: str = PLATFORMS_DIR, + destinations_file: str, counts_file: str, platforms_dir: str = PLATFORMS_DIR, ) -> bool: """Compare the paths verify credits with the members of each archive. @@ -112,22 +111,20 @@ def check_pack_destinations( set aside when its path and size are the cached file's and verify does not credit the path. """ - import json import zipfile print(f"\n--- {step_title(STEP_LABELS['consistency'])}, destinations ---") - try: - credited_by = json.loads(Path(destinations_file).read_text()) - except (OSError, ValueError) as exc: - print(f" no destinations from verify ({exc})") + records = read_records(destinations_file, counts_file) + if records is None: return False - paths = parse_pack_paths(pack_output) - if not paths: - print(" no archive named in the pack output") + credited_by, packs = records + if not packs: + print(" no archive in the pack counts") return False all_ok = True - for label, zip_path in sorted(paths.items()): - names = [n for n in credited_by if match_key(n) & match_key(label)] + for pack in sorted(packs, key=lambda p: p["label"]): + label = pack["label"] + names = [platform for platform in pack["platforms"] if platform in credited_by] if not names: print(f" {label}: no verify destinations") all_ok = False @@ -135,7 +132,7 @@ def check_pack_destinations( entry = credited_by[names[0]] credited = set(entry["pack_destinations"]) trees = compare.tree_members(entry["platform"], platforms_dir) - with zipfile.ZipFile(zip_path) as zf: + with zipfile.ZipFile(pack["archive"]) as zf: written = { info.filename for info in zf.infolist() if not info.is_dir() diff --git a/scripts/orchestrate/reports.py b/scripts/orchestrate/reports.py deleted file mode 100644 index ae91fd85e..000000000 --- a/scripts/orchestrate/reports.py +++ /dev/null @@ -1,143 +0,0 @@ -"""What verify and the pack build print, read back as counts, paths and platform identities.""" - -from __future__ import annotations - -import re -from collections.abc import Iterator - -from core.paths import PLATFORMS_DIR - -# "Label: X/Y OK ..." or "Label: X/Y present ...", the summary line verify -# prints for each group of identical platforms. -_VERIFY_SUMMARY = re.compile(r"^(.+?):\s+(\d+)/(\d+)\s+(OK|present)") -_PACK_HEADER = re.compile(r"Generating (?:shared )?pack for (.+)\.\.\.") - - -def _verify_groups(output: str) -> Iterator[tuple[list[str] | None, str, re.Match[str] | None]]: - """Each verify line with the platforms of the summary it falls under, - and its own summary match when it is one.""" - names: list[str] | None = None - for line in output.splitlines(): - m = _VERIFY_SUMMARY.match(line) - if m: - names = [name.strip() for name in m.group(1).split(" / ")] - yield names, line, m - - -def _pack_lines(output: str) -> Iterator[tuple[str, str]]: - """Each generate_pack line under a full pack's header, with its label. - - Labels carry execution metadata such as ``[source=full]``. Only the - full, unreduced pack is what verify describes: with --all-variants the - six variants shared one label and the last (platform, required) was - compared to the full report. - """ - label = "" - for line in output.splitlines(): - m = _PACK_HEADER.match(line) - if m: - label = _full_pack_label(m.group(1).strip()) - elif label: - yield label, line - - -def parse_verify_counts(output: str) -> dict[str, tuple[int, int]]: - """Per-platform OK/total from verify output.""" - return { - name: (int(m.group(2)), int(m.group(3))) - for names, _line, m in _verify_groups(output) if m and names - for name in names - } - - -def parse_verify_extras(output: str) -> dict[str, int]: - """Core files and game data verify says each pack carries, per platform. - - Read from the "Core files: N in pack" and "Game data: N in pack" lines - that follow a platform's summary line. - """ - extras: dict[str, int] = {} - for names, line, m in _verify_groups(output): - if m and names: - extras.update(dict.fromkeys(names, 0)) - continue - packed = re.match(r"^\s+(?:Core files|Game data): (\d+) in pack", line) - if packed and names: - for name in names: - extras[name] += int(packed.group(1)) - return extras - - -def parse_pack_extras(output: str) -> dict[str, int]: - """Files each full pack takes from the cores, per pack label.""" - extras: dict[str, int] = {} - for label, line in _pack_lines(output): - cores = re.search(r"\+ (\d+) from cores\)", line) - if "files packed" in line and cores: - extras[label] = int(cores.group(1)) - return extras - - -def _full_pack_label(label: str) -> str: - """The pack name, or "" for a reduced variant such as [source=platform].""" - meta = re.search(r"\s+\[([^\]]+)\]$", label) - if meta is None: - return label - return label[: meta.start()] if meta.group(1) == "source=full" else "" - - -def parse_pack_counts(output: str) -> dict[str, tuple[int, int]]: - """Per-pack OK/total from generate_pack output: {pack_label: (ok, total)}.""" - counts = {} - for label, line in _pack_lines(output): - # "622 files packed (359 baseline + 263 from cores), 358/359 files OK" - ok_m = re.search(r"(\d+)/(\d+) files OK", line) if "files packed" in line else None - if ok_m: - counts[label] = (int(ok_m.group(1)), int(ok_m.group(2))) - return counts - - -def parse_pack_exclusions(output: str) -> dict[str, int]: - """Intentional unsafe-omission counts from pack output, per pack label.""" - exclusions: dict[str, int] = {} - for label, line in _pack_lines(output): - if "files packed" in line: - excluded = re.search(r"(\d+) unsafe excluded", line) - exclusions[label] = int(excluded.group(1)) if excluded else 0 - return exclusions - - -def parse_pack_paths(output: str) -> dict[str, str]: - """The archive each full pack was written to, per pack label.""" - paths: dict[str, str] = {} - for label, line in _pack_lines(output): - written = re.match(r"^\s+(\S.*?\.zip): \d+ files packed", line) - if written: - paths[label] = written.group(1) - return paths - - -def match_key(label: str) -> set[str]: - """Comparable identity for a platform label. - - Display labels and registry ids differ in punctuation and spacing - (``MiSTer FPGA`` against ``misterfpga``), and grouped packs join their - members with either separator. - """ - return { - re.sub(r"[^a-z0-9]+", "", part.strip().lower()) - for part in label.replace("+", "/").split("/") - } - {""} - - -def release_pack_keys(platforms_dir: str = PLATFORMS_DIR) -> set[str]: - """Comparable identities of the platforms --all builds a pack for: their - registry ids and display names, normalized as match_key does.""" - from model.registry import list_release_pack_platforms - from model.platforms import load_platform_config - - keys: set[str] = set() - for name in list_release_pack_platforms(platforms_dir): - keys |= match_key(name) - keys |= match_key(str(load_platform_config(name, platforms_dir).get("platform", name))) - return keys diff --git a/scripts/packs/packcounts.py b/scripts/packs/packcounts.py new file mode 100644 index 000000000..a85dfa0e0 --- /dev/null +++ b/scripts/packs/packcounts.py @@ -0,0 +1,53 @@ +"""The counts each full platform pack hands the pipeline's consistency check.""" + +from __future__ import annotations + +import json +from dataclasses import asdict, dataclass +from pathlib import Path + + +@dataclass(frozen=True) +class PackCounts: + """What a built pack holds, by the builder's own count. + + ``ok`` and ``total`` are the platform's declared files judged in the + pack's verification mode, ``core_files`` what the pack takes from the + cores' profiles, and ``unsafe_excluded`` the files left out because the + frontend would reject their hash. + """ + + archive: str + ok: int + total: int + core_files: int + unsafe_excluded: int + + +def pack_counts(archive: str, file_status: dict[str, str], core_files: int) -> PackCounts: + """A pack's counts from the verdict of each declared file.""" + statuses = list(file_status.values()) + return PackCounts( + archive=archive, + ok=statuses.count("ok"), + total=len(statuses), + core_files=core_files, + unsafe_excluded=statuses.count("excluded"), + ) + + +def write_pack_counts(path: str, packs: list[tuple[str, list[str], PackCounts]]) -> None: + """Each pack's printed label, registry ids and counts, as a JSON list.""" + Path(path).write_text(json.dumps( + [{"label": label, "platforms": platforms, **asdict(counts)} + for label, platforms, counts in packs], + indent=1, sort_keys=True, + )) + + +def read_pack_counts(path: str) -> list[dict]: + """The packs a build recorded with write_pack_counts.""" + packs = json.loads(Path(path).read_text()) + if not isinstance(packs, list): + raise ValueError(f"{path} is not a list of packs") + return packs diff --git a/scripts/packs/packoptions.py b/scripts/packs/packoptions.py index 142a93b92..d65ce5a98 100644 --- a/scripts/packs/packoptions.py +++ b/scripts/packs/packoptions.py @@ -81,6 +81,21 @@ def _argument_conflicts(args: argparse.Namespace) -> list[tuple[bool, str]]: (one_per_slot and args.manifest, "--one-per-slot is incompatible with --manifest"), (one_per_slot and has_emulator, "--one-per-slot is incompatible with --emulator"), (one_per_slot and has_system, "--one-per-slot is incompatible with --system"), + *_counts_conflicts(args, has_platform or has_all, has_system or has_from_md5), + ] + + +def _counts_conflicts( + args: argparse.Namespace, platform_run: bool, narrowed: bool, +) -> list[tuple[bool, str]]: + """--counts describes the full platform packs: another mode refuses it.""" + counts = bool(getattr(args, "counts", None)) + return [ + (counts and not platform_run, "--counts requires --platform or --all"), + (counts and args.manifest, "--counts is incompatible with --manifest"), + (counts and args.split, "--counts is incompatible with --split"), + (counts and narrowed, + "--counts describes the full pack and is incompatible with --system and --from-md5"), ] @@ -204,6 +219,7 @@ def _given_flags(args: argparse.Namespace) -> set[str]: "--list-emulators": args.list_emulators, "--list-systems": args.list_systems, "--list-targets": args.list_targets, + "--counts": getattr(args, "counts", None), "--refresh-data": args.refresh_data, "--no-refresh-data": args.no_refresh_data, } diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index 543534218..40f9a859d 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -51,6 +51,7 @@ from packs.extras import ( undeclared_report, ) from packs.naming import file_name_part, pack_narrowings, platform_pack_name, platform_pack_stem +from packs.packcounts import PackCounts, pack_counts from packs.paths import flat_arcname, save_layout from packs.readme import build_agnostic_rename_readme, build_readme, save_place from resolve import packfiles as packresolve, regions as resolve_regions, slot as slot_mod @@ -101,11 +102,10 @@ def _report_pack_counts( verification_mode: str, tree_count: int = 0, ) -> None: - """Print the line the pipeline's consistency check reads. + """Print the pack's counts line. - The check compares these counts against what verify.py reports for - the same platform, so the wording is a contract: parse_pack_counts - in orchestrate/reports.py matches on it. + The pipeline's consistency check reads the same counts as data + (packs.packcounts), never this line. """ files_ok = sum(1 for s in file_status.values() if s == "ok") files_untested = sum(1 for s in file_status.values() if s == "untested") @@ -316,6 +316,7 @@ class PackOptions(PackNarrowing, _PartScope, total=False): record: PackRecord | None within: dict[str, str] | None uncached_out: set[str] | None + counts: list[PackCounts] | None @dataclass(frozen=True) @@ -342,6 +343,7 @@ class _PackSettings: record: PackRecord | None = None within: dict[str, str] | None = None uncached_out: set[str] | None = None + counts: list[PackCounts] | None = None @dataclass @@ -1093,6 +1095,8 @@ def generate_pack( its group, and a name built from every system of a hundred-system group is longer than a file name can be. + ``counts``, when given, receives the pack's PackCounts once it is built. + ``record`` builds the pack in memory (PackRecord): no archive is written, no external file fetched, and the paths are kept on it. @@ -1151,6 +1155,8 @@ def generate_pack( build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra) build.run() build.report() + if opts.counts is not None: + opts.counts.append(pack_counts(plan.zip_path, build.file_status, build.core_count)) return plan.zip_path diff --git a/scripts/packs/platformrun.py b/scripts/packs/platformrun.py index 8d170d44a..e19c52700 100644 --- a/scripts/packs/platformrun.py +++ b/scripts/packs/platformrun.py @@ -24,6 +24,7 @@ from packs.manifest import generate_manifest from packs.manifestrun import run_manifest_mode from packs.naming import pack_narrowings, platform_pack_name, platform_target from packs.outputdir import holds_other_kind, pack_output_lock +from packs.packcounts import PackCounts, write_pack_counts from packs.packcheck import run_verify_packs from packs.platformpack import generate_pack, generate_split_packs from packs.runscope import settle_scope @@ -60,19 +61,23 @@ def run_platform_packs( # The packs this run writes, the only ones it verifies and rewrites. built: set[str] = set() + # The full packs' counts, for --counts: the pipeline compares them with + # verify's. + recorded: list[tuple[str, list[str], PackCounts]] = [] + record_counts = getattr(args, "counts", None) + failed: list[str] = [] for source, required_only in run_variants(args): for group_platforms, representative in groups: aliases = [p for p in group_platforms if p != representative] - if aliases: - all_names = [ - load_platform_config(p, args.platforms_dir).get("platform", p) - for p in group_platforms - ] - label = " / ".join(all_names) - print(f"\nGenerating pack for {label} {pack_label(source, required_only)}...") - else: - print(f"\nGenerating pack for {representative} {pack_label(source, required_only)}...") + label = " / ".join( + load_platform_config(p, args.platforms_dir).get("platform", p) + for p in group_platforms + ) if aliases else representative + print(f"\nGenerating pack for {label} {pack_label(source, required_only)}...") + counts: list[PackCounts] | None = ( + [] if record_counts and (source, required_only) == ("full", False) else None + ) zip_path = None zip_paths: list = [] @@ -138,6 +143,7 @@ def run_platform_packs( pack_name=group_name, no_game_data=getattr(args, "no_game_data", False), uncached_out=getattr(args, "uncached_trees", None), + counts=counts, ) except (FileNotFoundError, OSError, yaml.YAMLError) as e: print(f" ERROR: {e}", file=sys.stderr) @@ -153,6 +159,7 @@ def run_platform_packs( os.path.relpath(path, args.output_dir) for path in ([zip_path] if zip_path else zip_paths) ) + recorded.extend((label, group_platforms, c) for c in counts or ()) if zip_path and not system_filter: # The install list of the same choices names each file's # systems: the pack records them, so a pack alone (a @@ -170,6 +177,8 @@ def run_platform_packs( uncached_out=getattr(args, "uncached_trees", None), ), target_list(board_list) if board_list.is_file() else None) + if record_counts: + write_pack_counts(record_counts, recorded) all_ok = finalize_platform_packs(args, db, data_registry, built, systems_for, system_filter) if failed: # Verification only sees the ZIPs that exist, so a pack that was never diff --git a/scripts/packs/report.py b/scripts/packs/report.py index d097d6fd2..0a843acb3 100644 --- a/scripts/packs/report.py +++ b/scripts/packs/report.py @@ -243,6 +243,23 @@ def split_undeclared(undeclared: list[dict]) -> tuple[list[dict], list[dict], li return game_data, placed, unplaced +def pack_shares(result: dict) -> tuple[int, int]: + """The core files and the game data a platform's pack carries, by the report. + + The builder's count, one file per pack path, when the platform pass + replayed it. Counting entries said 1130 for RetroArch, 48 more than the + pack holds: rom.key alone was claimed by three Amiga cores. + """ + packed = result.get("packed_extras") + if packed is not None: + return packed["bios"], packed["game_data"] + game_data, bios_files, _unplaced = split_undeclared(result.get("undeclared_files", [])) + return ( + sum(1 for u in bios_files if u["in_repo"]), + sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True)), + ) + + def core_required_missing(bios_files: list[dict]) -> list[dict]: """Core files a core cannot run without, absent from the collection. @@ -303,15 +320,8 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None: for u in bios_files if u["required"] and not u["in_repo"] and u.get("hle_fallback") ] - req_in_repo = [u for u in bios_files if u["required"] and u["in_repo"]] - opt_in_repo = [u for u in bios_files if not u["required"] and u["in_repo"]] opt_not_in_repo = [u for u in bios_files if not u["required"] and not u["in_repo"]] - # The builder's count, one file per pack path, when the platform pass - # replayed it. Counting entries said 1130 for RetroArch, 48 more than the - # pack holds: rom.key alone was claimed by three Amiga cores. - core_in_pack = ( - packed["bios"] if packed is not None else len(req_in_repo) + len(opt_in_repo) - ) + core_in_pack, gd_packed = pack_shares(result) core_missing_req = len(req_not_in_repo) + len(req_hle_not_in_repo) core_missing_opt = len(opt_not_in_repo) @@ -354,10 +364,6 @@ def _print_undeclared_section(result: dict, verbose: bool) -> None: if game_data or (packed and packed.get("game_data")): gd_missing = [u for u in game_data if not u["in_repo"]] - gd_packed = ( - packed["game_data"] if packed is not None - else sum(1 for u in game_data if u["in_repo"] and u.get("in_pack", True)) - ) gd_unplaced = [u for u in game_data if u["in_repo"] and not u.get("in_pack", True)] if gd_missing or gd_packed or gd_unplaced: listed = "" if verbose or not gd_missing else " (--verbose lists them)" diff --git a/scripts/packs/variants.py b/scripts/packs/variants.py index 8cb73c221..9fea10cc3 100644 --- a/scripts/packs/variants.py +++ b/scripts/packs/variants.py @@ -22,7 +22,7 @@ def run_variants(args: argparse.Namespace) -> tuple[tuple[str, bool], ...]: def pack_label(source: str, required_only: bool) -> str: - """The variant tag orchestrate.reports.parse_pack_counts reads after a pack name.""" + """The variant tag printed after a pack name.""" return f"[source={source}, required]" if required_only else f"[source={source}]" diff --git a/scripts/packs/verifyoutput.py b/scripts/packs/verifyoutput.py index bd122eb63..a7c020c90 100644 --- a/scripts/packs/verifyoutput.py +++ b/scripts/packs/verifyoutput.py @@ -5,7 +5,8 @@ from __future__ import annotations import json from pathlib import Path -from packs.verdicts import Status +from packs.report import pack_shares +from packs.verdicts import Severity, Status def json_details(details: list[dict], verbose: bool) -> list[dict]: @@ -25,11 +26,23 @@ def write_pack_destinations( groups: list[tuple[list[str], str]], group_results: list[tuple[dict, list[str]]], ) -> None: - """The paths each pack holds according to the report, per platform, as JSON.""" + """What each platform's pack holds according to the report, as JSON. + + Keyed by registry id: the name verify prints, its OK and total counts, + the core files and game data the pack takes from the cores, and the + paths it credits. The pipeline's consistency check reads them here + rather than from the printed report. + """ destinations = {} for (result, names), (group, _rep) in zip(group_results, groups): + core_files, game_data = pack_shares(result) for name, key in zip(names, group): - destinations[name] = { - "platform": key, "pack_destinations": result["pack_destinations"], + destinations[key] = { + "platform": key, + "label": name, + "ok": result["severity_counts"][Severity.OK], + "total": result["total_files"], + "core_files": core_files + game_data, + "pack_destinations": result["pack_destinations"], } Path(path).write_text(json.dumps(destinations, indent=1, sort_keys=True)) diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 79dce7b99..093829dfa 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -150,13 +150,13 @@ def main() -> None: all_ok = database_steps(args, results) all_ok = refresh_steps(args, results) and all_ok all_ok = truth_steps(args, results) and all_ok - ok, verify_output, destinations_file = verify_steps(args, results, held) + ok, destinations_file = verify_steps(args, results, held) all_ok = all_ok and ok - ok, pack_output = pack_steps(args, results) + ok, pack_counts_file = pack_steps(args, results) all_ok = all_ok and ok all_ok = index_steps(results) and all_ok all_ok = check_steps( - args, results, pack_output=pack_output, verify_output=verify_output, + args, results, pack_counts_file=pack_counts_file, destinations_file=destinations_file, ) and all_ok all_ok = docs_steps(args, results) and all_ok diff --git a/scripts/verify.py b/scripts/verify.py index cea9f72a1..e6707b48d 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -89,8 +89,8 @@ def build_parser() -> argparse.ArgumentParser: ) parser.add_argument( "--destinations", metavar="FILE", - help="With --platform or --all, also write the paths each pack holds " - "according to this report to FILE (JSON), for comparison with the archive", + help="With --platform or --all, also write the counts and paths each pack " + "holds according to this report to FILE (JSON), for comparison with the archive", ) parser.add_argument( "--strict", diff --git a/tests/sources.py b/tests/sources.py index 2d6172d0d..ee4e37532 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -21,7 +21,7 @@ COMMANDS = { "packs/manifestentry.py", "packs/manifestcores.py", "packs/standalone.py", "packs/manifest.py", "packs/finalize.py", "packs/outputdir.py", "packs/variants.py", "packs/manifestrun.py", "packs/packcheck.py", "packs/runscope.py", "packs/platformrun.py", - "packs/packoptions.py", "packs/packmodes.py", + "packs/packoptions.py", "packs/packmodes.py", "packs/packcounts.py", ), "verify.py": ( "packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py", @@ -113,7 +113,7 @@ COMMANDS = { "orchestrate/labels.py", "orchestrate/results.py", "orchestrate/runner.py", "orchestrate/guards.py", "orchestrate/locks.py", "orchestrate/prepare.py", "orchestrate/build.py", "orchestrate/checks.py", "orchestrate/docs.py", - "orchestrate/reports.py", "orchestrate/compare.py", "orchestrate/consistency.py", + "orchestrate/compare.py", "orchestrate/consistency.py", "orchestrate/emulatorpacks.py", "orchestrate/narrowed.py", "orchestrate/splitcheck.py", ), "validate_schemas.py": ( diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index e7c77afeb..9145c496e 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -32,7 +32,7 @@ except ImportError: import install from packs import verdicts from scripts import pipeline -from orchestrate import checks, consistency, reports, results, runner +from orchestrate import checks, consistency, results, runner from scripts.resolve import regionaudit, regions from scripts.resolve.localfile import resolve_local_file from scripts.core.ziptools import safe_extract_zip @@ -1196,130 +1196,91 @@ class PipelineRegressions(unittest.TestCase): self.assertNotIn("--all-variants", command()) self.assertEqual(command(target="switch")[-2:], ["--target", "switch"]) - def test_pack_parser_removes_source_metadata(self): - output = "\n".join( - [ - "Generating pack for RetroArch [source=full]...", - " 3 files packed (2 baseline + 1 from cores), 2/2 files OK", - ] - ) - self.assertEqual(reports.parse_pack_counts(output), {"RetroArch": (2, 2)}) + @staticmethod + def _verified(label: str, ok: int, total: int, core_files: int = 0) -> dict: + """One platform as verify.py --destinations records it.""" + key = label.lower().replace(" ", "") + return {key: {"platform": key, "label": label, "ok": ok, "total": total, + "core_files": core_files, "pack_destinations": []}} + + @staticmethod + def _packed(label: str, ok: int, total: int, core_files: int = 0, + unsafe_excluded: int = 0) -> dict: + """One full pack as generate_pack.py --counts records it.""" + return {"label": label, "platforms": [label.lower().replace(" ", "")], + "archive": "pack.zip", "ok": ok, "total": total, + "core_files": core_files, "unsafe_excluded": unsafe_excluded} def test_missing_pack_is_a_consistency_failure(self): - verify = "RetroArch: 2/2 OK" + verify = self._verified("RetroArch", 2, 2) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, "")) + self.assertFalse(consistency.compare_counts(verify, [])) - def test_display_name_matches_compact_registry_id(self): - verify = "MiSTer FPGA: 65/65 OK [md5]" - pack = "\n".join( - [ - "Generating pack for misterfpga [source=full]...", - " pack.zip: 65 files packed (65 baseline + 0 from cores), " - "65/65 files OK [md5]", - ] - ) + def test_display_name_and_registry_id_meet_by_id(self): + verify = self._verified("MiSTer FPGA", 65, 65) + pack = {**self._packed("misterfpga", 65, 65), "platforms": ["misterfpga"]} with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(consistency.check_consistency(verify, pack)) + self.assertTrue(consistency.compare_counts(verify, [pack])) def test_the_cores_share_is_compared_too(self): """RomM passed this step while verify counted 412 core files and game data in the pack and the builder placed 60.""" - verify = "\n".join([ - "RomM: 383/383 OK [md5]", - " Core files: 61 in pack, 0 required missing, 1 optional missing", - " Game data: 351 in pack, 0 missing", - ]) - pack = "\n".join([ - "Generating pack for RomM [source=full]...", - " pack.zip: 443 files packed (383 baseline + 60 from cores), " - "383/383 files OK [md5]", - ]) + verify = self._verified("RomM", 383, 383, core_files=412) + pack = self._packed("RomM", 383, 383, core_files=60) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, [pack])) + self.assertIn("RomM: MISMATCH core files verify 412 != pack 60", out.getvalue()) + agreed = self._verified("RomM", 383, 383, core_files=60) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, pack)) - agreed = verify.replace("61 in pack", "60 in pack").replace("351 in pack", "0 in pack") - self.assertTrue(consistency.check_consistency(agreed, pack)) + self.assertTrue(consistency.compare_counts(agreed, [pack])) def test_an_exclusion_never_covers_a_file_verify_counts_ok(self): """An existence platform packs a file whose hash disagrees and a hash platform's verify reports it untested: exclusions that make up the difference hid the very divergence this step exists to catch.""" - verify = "RetroArch: 3/3 present [existence]" - pack = "\n".join( - [ - "Generating pack for RetroArch [source=full]...", - " pack.zip: 2 files packed (2 baseline + 0 from cores), " - "2/3 files OK, 1 unsafe excluded [existence]", - ] - ) - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, pack)) - self.assertEqual(reports.parse_pack_exclusions(pack), {"RetroArch": 1}) - - def test_unaccounted_pack_omission_is_a_consistency_failure(self): - verify = "RetroArch: 3/3 present [existence]" - pack = "\n".join( - [ - "Generating pack for RetroArch [source=full]...", - " pack.zip: 1 files packed (1 baseline + 0 from cores), " - "1/3 files OK, 1 unsafe excluded, 1 missing [existence]", - ] - ) - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, pack)) + verify = self._verified("RetroArch", 3, 3) + pack = self._packed("RetroArch", 2, 3, unsafe_excluded=1) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, [pack])) + self.assertIn("(1 unsafe excluded)", out.getvalue()) def test_a_pack_more_optimistic_than_verify_is_a_failure(self): """The invariant held one way only: a pack counting more OK files than the report passed as 'pack resolves more'.""" - verify = "DupTest: 0/1 OK, 1 untested [md5]" - pack = "\n".join( - [ - "Generating pack for DupTest [source=full]...", - " x/DupTest_1_BIOS_Pack.zip: 1 files packed (1 baseline + 0 from cores), " - "1/1 files OK [md5]", - ] - ) + verify = self._verified("DupTest", 0, 1) + pack = self._packed("DupTest", 1, 1) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, pack)) + self.assertFalse(consistency.compare_counts(verify, [pack])) - def test_nothing_parsed_is_not_consistent(self): - """A changed output format must not pass with no platform compared.""" + def test_nothing_read_is_not_consistent(self): + """A build that recorded nothing must not pass with no platform compared.""" with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency("RetroArch = 2/2 OK", "")) - self.assertFalse(consistency.check_consistency("", "")) + self.assertFalse(consistency.compare_counts(self._verified("RetroArch", 2, 2), [])) + self.assertFalse(consistency.compare_counts({}, [])) + + def test_an_unwritten_record_file_is_a_failure(self): + """A step that crashed leaves its file empty: the check fails, it + does not compare nothing and pass.""" + with tempfile.TemporaryDirectory() as root: + empty = os.path.join(root, "empty.json") + Path(empty).write_text("") + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.check_consistency(empty, empty)) + self.assertFalse(consistency.check_pack_destinations(empty, empty)) + self.assertIn("unreadable counts", out.getvalue()) def test_pack_without_verify_result_is_a_failure(self): - verify = "RetroArch: 2/2 OK" - pack = "\n".join( - [ - "Generating pack for RetroArch [source=full]...", - " a.zip: 2 files packed (2 baseline + 0 from cores), 2/2 files OK", - "Generating pack for Batocera [source=full]...", - " b.zip: 2 files packed (2 baseline + 0 from cores), 2/2 files OK", - ] - ) - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.check_consistency(verify, pack)) + verify = self._verified("RetroArch", 2, 2) + packs = [self._packed("RetroArch", 2, 2), self._packed("Batocera", 2, 2)] + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, packs)) + self.assertIn("Batocera: pack with no verify result", out.getvalue()) - def test_only_the_full_variant_feeds_the_comparison(self): - """--all-variants printed six packs under one label, and the last won.""" - output = "\n".join([ - "Generating pack for RetroArch [source=full]...", - " a.zip: 5 files packed (5 baseline + 0 from cores), 535/535 files OK", - "Generating pack for RetroArch [source=platform, required]...", - " b.zip: 5 files packed (5 baseline + 0 from cores), 530/530 files OK", - ]) - self.assertEqual(reports.parse_pack_counts(output), {"RetroArch": (535, 535)}) - - def test_exclusions_read_only_the_full_variant(self): - """--all-variants printed six packs under one label, and the last won.""" - output = "\n".join([ - "Generating pack for Batocera [source=full]...", - " a.zip: 5 files packed (5 baseline + 0 from cores), 5/5 files OK, 3 unsafe excluded", - "Generating pack for Batocera [source=truth, required]...", - " b.zip: 2 files packed (0 baseline + 2 from cores), 2/2 files OK", - ]) - self.assertEqual(reports.parse_pack_exclusions(output), {"Batocera": 3}) + def test_only_the_full_variant_is_recorded(self): + """--all-variants built six packs under one label, and the last won.""" + source = script_source("generate_pack.py") + self.assertIn('[] if record_counts and (source, required_only) == ("full", False) else None', + source) def test_slot_step_reaches_the_summary(self): source = script_source("pipeline.py") diff --git a/tests/test_e2e.py b/tests/test_e2e.py index eeb0ee142..e764a73db 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -2335,6 +2335,49 @@ class TestE2E(unittest.TestCase): # Verify _Required tag in filename self.assertIn("_Required_", os.path.basename(zip_path)) + def test_130a_consistency_reads_what_the_builder_and_verify_write(self): + """Step 5 compares the records the two tools write, not their wording. + + The builder's counts and verify's go through the files the pipeline + reads, so a reworded line can no longer switch a comparison off. + """ + from orchestrate.consistency import check_consistency + from packs.packcounts import PackCounts, write_pack_counts + from packs.platformpack import generate_pack + from packs.verifyoutput import write_pack_destinations + + profiles = load_emulator_profiles(self.emulators_dir) + output_dir = os.path.join(self.root, "counted") + packs: list[tuple[str, list[str], PackCounts]] = [] + groups, group_results = [], [] + for platform in ("test_existence", "test_md5"): + sink: list[PackCounts] = [] + with contextlib.redirect_stdout(io.StringIO()): + generate_pack( + platform, self.platforms_dir, self.db, self.bios_dir, output_dir, + emulators_dir=self.emulators_dir, emu_profiles=profiles, counts=sink, + ) + self.assertEqual(len(sink), 1) + packs.append((platform, [platform], sink[0])) + config = load_platform_config(platform, self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir, emu_profiles=profiles) + groups.append(([platform], platform)) + group_results.append((result, [config.get("platform", platform)])) + destinations = os.path.join(self.root, "destinations.json") + counts = os.path.join(self.root, "counts.json") + write_pack_destinations(destinations, groups, group_results) + write_pack_counts(counts, packs) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertTrue(check_consistency(destinations, counts), out.getvalue()) + self.assertEqual(out.getvalue().count("== pack"), 2, out.getvalue()) + + skewed = [(label, ids, PackCounts(**{**c.__dict__, "core_files": c.core_files + 1})) + for label, ids, c in packs] + write_pack_counts(counts, skewed) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(check_consistency(destinations, counts)) + self.assertIn("MISMATCH core files", out.getvalue()) + def test_130b_existence_pack_reports_hash_mismatch(self): """Existence mode packs a mismatched file but prints the proof.""" import contextlib @@ -6301,6 +6344,18 @@ struct BurnDriver BurnDrvneogeo = { "refuse"), (["--list-systems"], ["--no-game-data"], "refuse"), (["--list"], ["--no-game-data"], "refuse"), + # --counts records the full platform packs the pipeline compares + # with verify: a mode that builds none refuses it. + (["--emulator", "handy"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--manifest"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--split"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--system", "sony-playstation"], + ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--counts", "counts.json"], + "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--counts", "counts.json"], + "refuse"), + (["--list"], ["--counts", "counts.json"], "refuse"), ] for mode, flag, expected in matrix: with self.subTest(mode=mode, flag=flag): diff --git a/tests/test_pack_destinations.py b/tests/test_pack_destinations.py index 56f2c9f26..2ff972b4d 100644 --- a/tests/test_pack_destinations.py +++ b/tests/test_pack_destinations.py @@ -251,18 +251,23 @@ class ThePipelineComparesPaths(unittest.TestCase): with zipfile.ZipFile(zip_path, "w") as zf: for name in ("a.bin", "b.bin", "README.txt", "INSTRUCTIONS_x.bin.txt"): zf.writestr(name, name) - output = f"Generating pack for plat [source=full]...\n {zip_path}: 2 files packed\n" + counts = root / "counts.json" + counts.write_text(json.dumps([{ + "label": "plat", "platforms": ["plat"], "archive": str(zip_path), + "ok": 2, "total": 2, "core_files": 0, "unsafe_excluded": 0, + }])) for credited, expected in ((["a.bin", "b.bin"], True), (["a.bin", "c.bin"], False)): with self.subTest(credited=credited): destinations = root / "d.json" destinations.write_text(json.dumps( - {"Plat": {"platform": "plat", "pack_destinations": credited}} + {"plat": {"platform": "plat", "label": "Plat", "ok": 2, "total": 2, + "core_files": 0, "pack_destinations": credited}} )) previous = os.getcwd() os.chdir(REPO_ROOT) try: with mock_tree_members(), contextlib.redirect_stdout(io.StringIO()) as out: - ok = check_pack_destinations(str(destinations), output) + ok = check_pack_destinations(str(destinations), str(counts)) finally: os.chdir(previous) self.assertIs(ok, expected, out.getvalue()) @@ -272,9 +277,12 @@ class ThePipelineComparesPaths(unittest.TestCase): def test_the_run_compares_every_emulator_pack(self): source = script_source("pipeline.py") - self.assertIn("ok = check_pack_destinations(destinations_file, pack_output) and ok", source) + self.assertIn( + "ok = check_pack_destinations(destinations_file, pack_counts_file) and ok", source + ) self.assertIn("ok = check_emulator_packs(full=args.full_narrowings) and ok", source) self.assertIn('"--destinations", destinations_file', source) + self.assertIn('"--counts",\n counts_file,', source) @contextlib.contextmanager diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index b5bb3c2e9..5743b4fdc 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -172,32 +172,33 @@ class TheBuildReadsTheField(unittest.TestCase): class APlatformWithoutAPackFailsNoCheck(unittest.TestCase): - VERIFY = ( - "RetroArch: 10/10 OK [existence]\n" - "KNULLI: 5/5 OK [md5]\n" - ) - PACK = ( - "Generating pack for RetroArch...\n" - " dist/RetroArch_BIOS_Pack.zip: 10 files packed, 10/10 files OK [existence]\n" - ) + VERIFY = { + "retroarch": {"platform": "retroarch", "label": "RetroArch", "ok": 10, "total": 10, + "core_files": 0, "pack_destinations": []}, + "knulli": {"platform": "knulli", "label": "KNULLI", "ok": 5, "total": 5, + "core_files": 0, "pack_destinations": []}, + } + PACKS = [{"label": "retroarch", "platforms": ["retroarch"], + "archive": "dist/RetroArch_BIOS_Pack.zip", "ok": 10, "total": 10, + "core_files": 0, "unsafe_excluded": 0}] def test_the_consistency_step_skips_a_setup_served_by_the_installer(self): - from orchestrate.consistency import check_consistency - from orchestrate.reports import release_pack_keys + from orchestrate.consistency import compare_counts with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertTrue(check_consistency( - self.VERIFY, self.PACK, release_pack_keys(PLATFORMS))) + self.assertTrue(compare_counts( + self.VERIFY, self.PACKS, set(list_release_pack_platforms(PLATFORMS)))) self.assertIn("KNULLI: 5/5 (no release pack, served by the installer)", out.getvalue()) def test_a_released_platform_without_its_pack_still_fails(self): - from orchestrate.consistency import check_consistency - from orchestrate.reports import release_pack_keys + from orchestrate.consistency import compare_counts - verify = self.VERIFY + "Batocera: 3/3 OK [md5]\n" + verify = {**self.VERIFY, "batocera": { + "platform": "batocera", "label": "Batocera", "ok": 3, "total": 3, + "core_files": 0, "pack_destinations": []}} with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(check_consistency( - verify, self.PACK, release_pack_keys(PLATFORMS))) + self.assertFalse(compare_counts( + verify, self.PACKS, set(list_release_pack_platforms(PLATFORMS)))) # The failing line says it fails: "(no separate pack)" read like # the installer-only note above it. self.assertIn("Batocera: MISSING pack: verify judged 3/3 but the build wrote no pack for it", @@ -205,7 +206,7 @@ class APlatformWithoutAPackFailsNoCheck(unittest.TestCase): def test_the_pipeline_passes_the_release_platforms(self): source = script_source("pipeline.py") - self.assertIn("release_pack_keys()", source) + self.assertIn("set(list_release_pack_platforms(PLATFORMS_DIR))", source) def test_verify_packs_sweeps_the_release_packs_only(self): import subprocess diff --git a/tests/test_verify_release_asset.py b/tests/test_verify_release_asset.py index bd9bf37ff..23912e04d 100644 --- a/tests/test_verify_release_asset.py +++ b/tests/test_verify_release_asset.py @@ -247,7 +247,7 @@ class OfflinePipelineVerifiesOffline(unittest.TestCase): def test_verify_step_gets_offline(self): source = script_source("pipeline.py") - block = source[source.index("verify_cmd = ["):source.index("ok, verify_output = runner.run(")] + block = source[source.index("verify_cmd = ["):source.index("ok, _ = runner.run(verify_cmd")] self.assertIn('verify_cmd.append("--offline")', block) diff --git a/wiki/tools.md b/wiki/tools.md index 076e6430d..397a71837 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -96,9 +96,10 @@ alone, run `python scripts/check_buildbot_system.py`. - **A step that did not run says SKIPPED**, never OK. - **verify.py and generate_pack.py read the same functions.** A count or a path that differs between the report and the pack is a defect, which is - what step 5 checks: the counts, the paths each archive holds against the - ones verify credits (`--destinations`), every emulator pack, each - profile in each build, built in memory against `verify --emulator`, and + what step 5 checks: the counts each tool records (`--destinations` and + `--counts`, never their printed lines), the paths each archive holds + against the ones verify credits, every emulator pack, each profile in + each build, built in memory against `verify --emulator`, and every system pack that gathers several profiles against `verify --system`. Each of them is also built with `--required-only` and with the regions its files declare (first, middle and last, all of them with @@ -165,7 +166,7 @@ python scripts/verify.py --platform retroarch --target switch # filter by hardw python scripts/verify.py --platform recalbox --region us # regional priority list python scripts/verify.py --platform emuelec --no-game-data # the firmware-only pack, game data named python scripts/verify.py --emulator mame --required-only # the pack built with --required-only -python scripts/verify.py --all --destinations tmp/paths.json # also write the paths each pack holds +python scripts/verify.py --all --destinations tmp/paths.json # also write the counts and paths each pack holds python scripts/verify.py --all --offline # a release asset the cache lacks counts missing, as in an offline build (any mode, --emulator included) python scripts/verify.py --list-platforms # list all platforms python scripts/verify.py --list-emulators # list all emulators @@ -247,6 +248,7 @@ python scripts/generate_pack.py --list-emulators python scripts/generate_pack.py --list-systems python scripts/generate_pack.py --platform retroarch --list-targets python scripts/generate_pack.py --all --verify-packs --output-dir dist/ # extract + hash +python scripts/generate_pack.py --all --counts tmp/counts.json # also write each full pack's counts # Data refresh python scripts/generate_pack.py --all --refresh-data # force re-download data dirs