diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index cbfb6ba81..1d4a9a553 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -69,6 +69,7 @@ on: - "scripts/model/systemnames.py" - "scripts/model/systems.py" - "scripts/model/targets.py" + - "scripts/orchestrate/labels.py" - "scripts/packs/__init__.py" - "scripts/packs/archive.py" - "scripts/packs/coverage.py" diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index eb13e0299..adb274722 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -521,7 +521,7 @@ ALL_VARIANTS: tuple[tuple[str, bool], ...] = ( def _pack_label(source: str, required_only: bool) -> str: - """The variant tag pipeline.parse_pack_counts reads after a pack name.""" + """The variant tag orchestrate.reports.parse_pack_counts reads after a pack name.""" return f"[source={source}, required]" if required_only else f"[source={source}]" diff --git a/scripts/orchestrate/__init__.py b/scripts/orchestrate/__init__.py index ed042ff80..ebef03505 100644 --- a/scripts/orchestrate/__init__.py +++ b/scripts/orchestrate/__init__.py @@ -1 +1 @@ -"""The steps of the full pipeline run and their order.""" +"""The pipeline: its steps in run order, their outcomes, and the comparisons of step 5.""" diff --git a/scripts/orchestrate/build.py b/scripts/orchestrate/build.py new file mode 100644 index 000000000..c38c28f0e --- /dev/null +++ b/scripts/orchestrate/build.py @@ -0,0 +1,224 @@ +"""Steps 3 to 4e: verify and its arbitrations, the packs and manifests, the install indexes.""" + +from __future__ import annotations + +import argparse +import atexit +import contextlib +import os +import sys +import tempfile +from pathlib import Path + +from core.artifacts import ArtifactLockBusy, artifact_lock +from core.paths import PLATFORMS_DIR, REPO_ROOT +from model.registry import load_data_dir_registry +from orchestrate import runner +from orchestrate.labels import STEP_LABELS, skip_notice +from orchestrate.results import SKIPPED +from packs.datadirs import hold_data_dirs + + +def verify_steps( + args: argparse.Namespace, results: dict, held: contextlib.ExitStack +) -> tuple[bool, str, 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. + """ + all_ok = True + # Every step from here reads the data directory trees: verify, the packs, + # the manifests and the integrity check. Held shared until the run ends, + # a refresh from another session waits instead of swapping a tree + # between the packs and the manifests, which would then describe two + # revisions of it. Taken after step 2, whose own refresh needs them + # 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) + verify_cmd = [ + sys.executable, "scripts/verify.py", "--all", "--strict", + "--destinations", destinations_file, + ] + if args.target: + verify_cmd.extend(["--target", args.target]) + if args.offline: + # 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"]) + results["verify"] = ok + all_ok = all_ok and ok + + # Step 3a: One content answering to two identities. Walks the tree rather + # than the index, which keeps a single path per content and therefore + # cannot see a file copied under another machine's name. + ok, _ = runner.run( + [sys.executable, "scripts/identity.py", "--strict"], + STEP_LABELS["identity"], + ) + results["identity"] = ok + all_ok = all_ok and ok + + # Step 3b: Destinations both layers claim, and how each was settled. The + # ones the pack settles by itself must stay at zero cost. The rest name an + # upstream declaration no build can repair, so this reports and never gates. + # A crash is not a report: without --strict slots.py exits 0 on every + # conflict, so a non-zero code means it never finished reading. + # The same cores verify judged: without the target the arbitration of a + # targeted run judged cores the target does not ship. + slots_cmd = [sys.executable, "scripts/slots.py"] + if args.target: + slots_cmd.extend(["--target", args.target]) + ok, _ = runner.run(slots_cmd, "3b slot arbitration") + results["slots"] = ok + all_ok &= ok + return all_ok, verify_output, destinations_file + + +def purge_stale_packs(output_dir: str) -> None: + """Remove the packs of earlier builds from the output directory.""" + # Purge stale packs: leftover ZIPs from previous builds would be + # picked up by pack verification and shipped in releases. + out_dir = Path(output_dir) + if not out_dir.is_dir(): + return + try: + with artifact_lock(str(out_dir)): + stale = [ + p for p in out_dir.iterdir() + if p.is_file() and ( + p.suffix == ".zip" + or ".zip." in p.name + or p.name == "SHA256SUMS.txt" + ) + ] + for p in stale: + p.unlink() + if stale: + print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/") + except ArtifactLockBusy as exc: + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + + +def pack_command(args: argparse.Namespace) -> list[str]: + """The step 4 command: every platform's pack.""" + pack_cmd = [ + sys.executable, + "scripts/generate_pack.py", + "--all", + "--output-dir", + args.output_dir, + ] + if args.offline: + pack_cmd.append("--offline") + else: + # Step 2 refreshed the trees once: refreshing again here let the + # pack and the manifest describe two revisions of a moving tree. + pack_cmd.append("--no-refresh-data") + if args.target: + pack_cmd.extend(["--target", args.target]) + if args.source != "full": + pack_cmd.extend(["--source", args.source]) + if args.all_variants: + pack_cmd.append("--all-variants") + return pack_cmd + + +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. + """ + all_ok = True + # Step 4: Generate packs + pack_output = "" + if not args.skip_packs: + purge_stale_packs(args.output_dir) + ok, pack_output = runner.run(pack_command(args), STEP_LABELS["generate_packs"]) + results["generate_packs"] = ok + all_ok = all_ok and ok + else: + skip_notice("generate_packs", "--skip-packs") + results["generate_packs"] = SKIPPED + + # Step 4b: Generate install manifests + if not args.skip_packs: + manifest_cmd = [ + sys.executable, + "scripts/generate_pack.py", + "--all", + "--manifest", + "--output-dir", + "install", + ] + if args.offline: + manifest_cmd.append("--offline") + else: + # Step 2 refreshed the trees once: refreshing again here let the + # pack and the manifest describe two revisions of a moving tree. + manifest_cmd.append("--no-refresh-data") + # No --target here: install/ holds the published lists, and every + # reader (site picker, release check, record) takes each file there + # as a whole platform. The per-target core lists are step 4c. + ok, _ = runner.run(manifest_cmd, STEP_LABELS["generate_manifests"]) + results["generate_manifests"] = ok + all_ok = all_ok and ok + else: + skip_notice("generate_manifests", "--skip-packs") + results["generate_manifests"] = SKIPPED + + # Step 4c: Generate target manifests + if not args.skip_packs: + target_cmd = [ + sys.executable, + "scripts/generate_pack.py", + "--manifest-targets", + "--output-dir", + "install/targets", + ] + ok, _ = runner.run(target_cmd, STEP_LABELS["generate_target_manifests"]) + results["generate_target_manifests"] = ok + all_ok = all_ok and ok + else: + skip_notice("generate_target_manifests", "--skip-packs") + results["generate_target_manifests"] = SKIPPED + return all_ok, pack_output + + +def index_steps(results: dict) -> bool: + """Steps 4d and 4e: bundled-only copies, the games index.""" + all_ok = True + # Step 4d: A collected copy that only an emulator's own install provides. + # Packs leave such files out, so a copy nothing else asks for is weight + # the collection carries for nobody. Read after the manifests, which say + # what an installation ships. + ok, _ = runner.run( + [sys.executable, "scripts/bundled_only.py", "--strict"], + STEP_LABELS["bundled_only"], + ) + results["bundled_only"] = ok + all_ok &= ok + + # Step 4e: What the installer reads for the games on a card: rom folders, + # game catalogs, header and region rules, arcade parents, and the + # fallback sets, which read the install lists. Runs under --skip-packs + # too, on the committed lists, so a rescrape of the rom folders or a DAT + # import reaches install/games/ in the same run. + ok, _ = runner.run( + [sys.executable, "scripts/generate_games_index.py", "--quiet"], + STEP_LABELS["games_index"], + ) + results["games_index"] = ok + all_ok &= ok + return all_ok diff --git a/scripts/orchestrate/checks.py b/scripts/orchestrate/checks.py new file mode 100644 index 000000000..eecb977e4 --- /dev/null +++ b/scripts/orchestrate/checks.py @@ -0,0 +1,85 @@ +"""Steps 5 and 6: verify against the packs it describes, then the packs' integrity.""" + +from __future__ import annotations + +import argparse +import sys + +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 + + +def integrity_command(args: argparse.Namespace) -> list[str]: + """Step 6: check the packs step 4 built, under the same expectation.""" + cmd = [ + sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", + "--output-dir", args.output_dir, + ] + # Without the target a targeted run reported every system the target + # removed as missing from a pack that was exactly right. Without + # --all-variants the five narrowed packs were never opened, and an empty + # _Platform pack passed. + if args.target: + cmd.extend(["--target", args.target]) + if args.all_variants: + cmd.append("--all-variants") + return cmd + + +def check_steps( + args: argparse.Namespace, + results: dict, + *, + pack_output: str, + verify_output: str, + destinations_file: str, +) -> bool: + """Steps 5 and 6: verify against the packs, then the packs' integrity.""" + all_ok = True + # Step 5: Consistency check. verify describes the full pack, and a run that + # 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: + skip_notice("consistency", "no full pack built") + results["consistency"] = SKIPPED + elif pack_output and verify_output: + ok = check_consistency( + verify_output, pack_output, + release_pack_keys(), + ) + # Counts can agree while the paths differ, both ways at once. + ok = check_pack_destinations(destinations_file, pack_output) 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 + print( + f"--- {step_title(STEP_LABELS['consistency'])}, counts and paths: " + f"{'OK' if ok else 'FAILED'} ---" + ) + results["consistency"] = ok + all_ok = all_ok and ok + else: + skip_notice("consistency") + results["consistency"] = SKIPPED + + # Step 6: Pack integrity (extract + hash verification) + if not args.skip_packs and not full_pack_built: + # The check reads the full pack's name, while a reduced pack holds fewer + # files than the platform declares by design. + skip_notice("pack_integrity", "no full pack built") + results["pack_integrity"] = SKIPPED + elif not args.skip_packs: + ok, _ = runner.run(integrity_command(args), STEP_LABELS["pack_integrity"]) + results["pack_integrity"] = ok + all_ok = all_ok and ok + else: + skip_notice("pack_integrity", "--skip-packs") + results["pack_integrity"] = SKIPPED + return all_ok diff --git a/scripts/orchestrate/compare.py b/scripts/orchestrate/compare.py new file mode 100644 index 000000000..3a13e2021 --- /dev/null +++ b/scripts/orchestrate/compare.py @@ -0,0 +1,74 @@ +"""What the step 5 comparisons share: the inputs they read, the members set aside, the difference lines.""" + +from __future__ import annotations + +import contextlib +import io +import os +import re + +from core.paths import EMULATORS_DIR +from model.registry import load_data_dir_registry +from packs.paths import MEDIA_MARKER + +# Members the builder writes for the reader or the device rather than for a +# core: the documents, and the empty marker an Android pack carries. +PACK_NOTES = re.compile( + r"(^README\.txt$|^manifest\.json$|(^|/)(INSTRUCTIONS|RENAMED)_[^/]*\.txt$" + rf"|(^|/){re.escape(MEDIA_MARKER)}$)" +) + + +def tree_members( + platform: str, platforms_dir: str, emulators_dir: str = EMULATORS_DIR, +) -> dict[str, int]: + """Archive path -> size of every file the platform's data trees can add.""" + from packs import datatrees + from model.profiles import load_emulator_profiles + from model.platforms import load_platform_config + from packs.archive import Placed + from packs.paths import flat_arcname + + config = load_platform_config(platform, platforms_dir) + base_dest = config.get("base_destination", "") + registry = load_data_dir_registry(platforms_dir) + core_trees = datatrees.core_data_trees( + config, load_emulator_profiles(emulators_dir), platform, registry, + ) + members: dict[str, int] = {} + with contextlib.redirect_stdout(io.StringIO()): + for src, full in datatrees.data_directory_members( + config.get("systems", {}), registry, + platform, base_dest, Placed(False), + core_trees=core_trees, + ): + members[flat_arcname(full, base_dest, True)] = os.path.getsize(src) + return members + + +def set_difference_lines(label: str, credited: set[str], written: set[str]) -> list[str]: + """The paths one side has and the other lacks, ten of each at most.""" + lines = [] + for side, paths in (("verify only", credited - written), ("pack only", written - credited)): + if paths: + shown = ", ".join(sorted(paths)[:10]) + more = f" (+{len(paths) - 10})" if len(paths) > 10 else "" + lines.append(f" {label}: {side} {len(paths)}: {shown}{more}") + return lines + + +def comparison_inputs( + db_path: str, emulators_dir: str, platforms_dir: str, +) -> tuple[dict, dict, dict, dict, list[tuple[list[str], str]]]: + """What the in-memory pack comparisons read: the database, its ZIP + index, the profiles, the data-directory registry and the platform groups.""" + from core.ziptools import build_zip_contents_index + from resolve.grouping import group_identical_platforms + from model.registry import list_registered_platforms + from model.database import load_database + from model.profiles import load_emulator_profiles + + db = load_database(db_path) + groups = group_identical_platforms(list_registered_platforms(platforms_dir), platforms_dir) + return (db, build_zip_contents_index(db), load_emulator_profiles(emulators_dir), + load_data_dir_registry(platforms_dir), groups) diff --git a/scripts/orchestrate/consistency.py b/scripts/orchestrate/consistency.py new file mode 100644 index 000000000..4dc6626ce --- /dev/null +++ b/scripts/orchestrate/consistency.py @@ -0,0 +1,153 @@ +"""Step 5 on the full packs: verify's counts and paths against what the build wrote.""" + +from __future__ import annotations + +from pathlib import Path + +from core.paths import PLATFORMS_DIR +from orchestrate import compare +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, +) + + +def check_consistency( + verify_output: str, pack_output: 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) + + 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 + + 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, +) -> bool: + """Compare the paths verify credits with the members of each archive. + + Equal counts hid a file credited on one side and another written on the + other. The trees and the notes are the archive's own: a tree member is + 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})") + return False + paths = parse_pack_paths(pack_output) + if not paths: + print(" no archive named in the pack output") + 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)] + if not names: + print(f" {label}: no verify destinations") + all_ok = False + continue + 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: + written = { + info.filename for info in zf.infolist() + if not info.is_dir() + and not compare.PACK_NOTES.search(info.filename) + and not ( + trees.get(info.filename) == info.file_size + and info.filename not in credited + ) + } + lines = compare.set_difference_lines(label, credited, written) + if lines: + print("\n".join(lines)) + all_ok = False + else: + print(f" {label}: {len(credited)} paths, the same on both sides") + return all_ok diff --git a/scripts/orchestrate/docs.py b/scripts/orchestrate/docs.py new file mode 100644 index 000000000..807ac2f47 --- /dev/null +++ b/scripts/orchestrate/docs.py @@ -0,0 +1,73 @@ +"""Steps 7 to 8b: README and generated pages, the site pages, the rendered site.""" + +from __future__ import annotations + +import argparse +import shutil +import sys +from pathlib import Path + +from orchestrate import runner +from orchestrate.labels import STEP_LABELS, skip_notice +from orchestrate.results import SKIPPED + + +def docs_steps(args: argparse.Namespace, results: dict) -> bool: + """Steps 7 to 8b: README and pages, site pages, the rendered site.""" + all_ok = True + # Step 7: Generate README + if not args.skip_docs: + ok, _ = runner.run( + [ + sys.executable, + "scripts/generate_readme.py", + "--db", + "database.json", + "--platforms-dir", + "platforms", + ], + STEP_LABELS["generate_readme"], + ) + # The run samples of wiki/installer.md, printed by install.py from + # the manifests step 4b just wrote. + doc_ok, _ = runner.run([sys.executable, "scripts/generate_installer_doc.py"], + "7 generate installer page") + # The verify excerpt of wiki/reading-reports.md, from this run's data. + excerpt_ok, _ = runner.run([sys.executable, "scripts/generate_report_excerpt.py"], + "7 generate report excerpt") + ok = ok and doc_ok and excerpt_ok + results["generate_readme"] = ok + all_ok = all_ok and ok + else: + skip_notice("generate_readme", "--skip-docs") + results["generate_readme"] = SKIPPED + + # Step 8: Generate site pages + if not args.skip_docs: + ok, _ = runner.run( + [sys.executable, "scripts/generate_site.py"], + STEP_LABELS["generate_site"], + ) + results["generate_site"] = ok + all_ok = all_ok and ok + else: + skip_notice("generate_site", "--skip-docs") + results["generate_site"] = SKIPPED + + # Step 8b: the render the site deploy runs. Generating the pages without + # rendering them let 20 pages with duplicate ids through to CI. + if args.skip_docs: + skip_notice("render_site", "--skip-docs") + results["render_site"] = SKIPPED + elif shutil.which("npm") is None or not Path("website/node_modules").is_dir(): + skip_notice("render_site", "Node not set up: npm ci --prefix website") + results["render_site"] = SKIPPED + else: + # Starlight's link check runs inside the build and fails it. + ok, _ = runner.run(["npm", "run", "build", "--prefix", "website"], STEP_LABELS["render_site"]) + if ok: + ok, _ = runner.run([sys.executable, "scripts/validate_site.py", "--site-dir", "website/dist"], + "8b validate site") + results["render_site"] = ok + all_ok = all_ok and ok + return all_ok diff --git a/scripts/orchestrate/emulatorpacks.py b/scripts/orchestrate/emulatorpacks.py new file mode 100644 index 000000000..1f8f3e84c --- /dev/null +++ b/scripts/orchestrate/emulatorpacks.py @@ -0,0 +1,134 @@ +"""Step 5 on the emulator and system packs, built in memory and compared with verify.""" + +from __future__ import annotations + +import contextlib +import io + +from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR +from model.profiles import reads_own_files +from orchestrate.compare import set_difference_lines +from orchestrate.labels import STEP_LABELS, step_title +from orchestrate.narrowed import matrix_coverage + +# The narrowings an emulator or system pack takes, compared by +# check_emulator_packs. A test holds this to the builder's parameters. +EMULATOR_NARROWINGS_COMPARED = frozenset({"standalone", "regions", "required_only"}) + + +def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict]]: + """(label, builder arguments) of each narrowed emulator pack compared. + + --required-only always, and each region the profiles' files declare, + sampled as check_narrowed_packs samples them unless *full*. A profile + without a regional file has nothing --region could withdraw. + """ + from model import region + + regions = sorted({ + r for profile in profiles for fe in profile.get("files") or [] + for r in region.normalize_declared(fe.get("region")) + }) + variants: list[tuple[str, dict]] = [("", {}), (" --required-only", {"required_only": True})] + variants += [ + (f" --region {regions[i]}", {"regions": [regions[i]]}) + for i in matrix_coverage(full, len(regions)) + ] + return variants + + +def check_emulator_packs( + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, full: bool = False, +) -> bool: + """Build every emulator and system pack in memory and compare it with verify. + + Each profile in each build it has (libretro, standalone), full and under + each narrowing of emulator_variants: the paths the pack fills with the + profile's files against the ones verify credits. The region and + required-only rules are written twice, once per side, and only this + comparison holds them together. No archive is written and no file read. + """ + from packs import archive + from packs import emulatorpack + from resolve import packfiles as packresolve + from packs import emulatorcheck + from model.profiles import ( + ProfileSelectionError, + load_emulator_profiles, + profiles_for_systems, + select_emulator_profiles, + ) + from model.systems import norm_system_id + from core.ziptools import build_zip_contents_index + from model.database import load_database + + print(f"\n--- {step_title(STEP_LABELS['consistency'])}, emulator packs ---") + db = load_database(db_path) + zip_contents = build_zip_contents_index(db) + profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) + + def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool: + record = archive.PackRecord() + # The pack is built offline: verify counts a release asset the cache + # lacks the same way, missing, as the narrowed-pack step does. + with packresolve.offline(), contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + emulatorpack.generate_emulator_pack( + names, emulators_dir, db, "bios", "", standalone, + zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir, + record=record, **narrowing, + ) + report = emulatorcheck.verify_emulator( + names, emulators_dir, db, standalone, platforms_dir=platforms_dir, + **narrowing, + ) + lines = set_difference_lines( + label, set(report["pack_destinations"]), set(record.files) + ) + if lines: + print("\n".join(lines)) + return not lines + + all_ok = True + compared = 0 + for name in sorted(profiles): + if profiles[name].get("type") == "alias": + continue # selects the profile it names, compared under that name + for standalone in (False, True): + try: + select_emulator_profiles([name], profiles, standalone) + except ProfileSelectionError: + continue + for tag, narrowing in emulator_variants([profiles[name]], full): + compared += 1 + label = f"{name}{' --standalone' if standalone else ''}{tag}" + all_ok = compare([name], standalone, label, **narrowing) and all_ok + print(f" {compared} emulator packs compared, {'all equal' if all_ok else 'differences above'}") + # A system pack builds every profile of the system together: a placement + # rule that only goes wrong when two profiles share a path (the bluemsx + # tree beside msx-emu's files) never meets in a one-profile pack. + systems = sorted({ + norm_system_id(str(sid)) + for profile in profiles.values() + if reads_own_files(profile) + for sid in profile.get("systems") or [] + }) + systems_ok = True + compared = 0 + for sid in systems: + for standalone in (False, True): + matching = profiles_for_systems(profiles, [sid], standalone) + if len(matching) < 2: + continue + for tag, narrowing in emulator_variants( + [profiles[n] for n in matching if n in profiles], full + ): + compared += 1 + label = f"--system {sid}{' --standalone' if standalone else ''}{tag}" + systems_ok = compare( + matching, standalone, label, system_ids=[sid], **narrowing + ) and systems_ok + print(f" {compared} system packs compared, " + f"{'all equal' if systems_ok else 'differences above'}") + return all_ok and systems_ok diff --git a/scripts/orchestrate/guards.py b/scripts/orchestrate/guards.py new file mode 100644 index 000000000..3b5242f7f --- /dev/null +++ b/scripts/orchestrate/guards.py @@ -0,0 +1,84 @@ +"""The refusals the run makes before its first step: flags it would drop, offline inputs it lacks.""" + +from __future__ import annotations + +import argparse +import os +from pathlib import Path + +from core.paths import PLATFORMS_DIR +from model.registry import load_data_dir_registry + + +def refuse_unapplied_flags( + parser: argparse.ArgumentParser, args: argparse.Namespace +) -> None: + """A flag the run would drop is refused before any step. + + --all-variants builds every source itself, so a --source beside it is + dropped; --skip-packs builds none, so both are, and step 5 does not run + for --full-narrowings to widen, nor does it without a full pack. + """ + # --source defaults to None so a typed `--source full` is seen: compared + # with its default value, it went through beside the modes that refuse it. + source_given = args.source is not None + if args.all_variants and source_given: + parser.error("--source is incompatible with --all-variants") + if args.skip_packs: + for flag, on in (("--source", source_given), + ("--all-variants", args.all_variants), + ("--full-narrowings", args.full_narrowings)): + if on: + parser.error(f"{flag} is incompatible with --skip-packs") + # Step 5 compares the full pack, and --source platform or truth builds + # none: the comparison is skipped and the flag had no effect. + if args.full_narrowings and source_given and args.source != "full": + parser.error(f"--full-narrowings is incompatible with --source {args.source}") + if args.source is None: + args.source = "full" + + +def refuse_offline_without_caches( + parser: argparse.ArgumentParser, args: argparse.Namespace, platforms_dir: str = PLATFORMS_DIR, +) -> None: + """An offline run that builds packs needs the data directories cached. + + On a fresh clone none is: --offline skips the refresh, and the run went + through the database, verify and every pack before failing at the end + of the build. Only an empty cache is refused here: with some cached, the + packs decide which ones they need and the build names the rest. + """ + if not args.offline or args.skip_packs: + return + registry = load_data_dir_registry(platforms_dir) + if registry and not any(os.path.isdir(e.get("local_cache") or "") for e in registry.values()): + parser.error( + "no data directory is cached and --offline skips their refresh: run " + "python scripts/refresh_data_dirs.py once, or drop --offline" + ) + + +def refuse_offline_export_without_originals( + parser: argparse.ArgumentParser, args: argparse.Namespace, + cache: str = ".cache/upstream-native", +) -> None: + """An offline run with --with-export needs each patched file cached. + + Seven formats carry code, so step 2e patches the platform's own file, + which --offline does not fetch. On a fresh clone the database, verify + and the truth model were built before step 2e failed on every one. + """ + if not (args.offline and args.with_export): + return + from exporter import discover_exporters + + lacking = sorted( + name for name, exporter in discover_exporters().items() + if exporter.needs_original() and not any(Path(cache, name).glob("*")) + ) + if lacking: + parser.error( + f"--with-export patches each platform's own file, and {cache}/ holds none " + f"for {', '.join(lacking)}: run python scripts/export_native.py --all " + "--refresh-cache once, or drop --offline" + ) diff --git a/scripts/orchestrate/labels.py b/scripts/orchestrate/labels.py new file mode 100644 index 000000000..5f04cc6c1 --- /dev/null +++ b/scripts/orchestrate/labels.py @@ -0,0 +1,60 @@ +"""The pipeline's steps in run order, and the titles the run prints for them.""" + +from __future__ import annotations + +# Every step in run order, by its results key. The position and the total +# printed during the run come from this list: hand-written "N/8" labels +# counted 8 steps in a run of 24, and the eighth came before 8b. The summary +# prints the same labels the run printed, so a FAILED row is found in the +# log by its number. +STEP_LABELS: dict[str, str] = { + "validate_schemas": "0 validate schemas", + "generate_db": "1 generate database", + "provenance": "1b provenance report", + "romset_recipes": "1c romset recipes", + "refresh_data": "2 refresh data directories", + "mame_hashes": "2a refresh MAME hashes", + "fbneo_hashes": "2a2 refresh FBNeo hashes", + "check_buildbot": "2b check buildbot system", + "check_release_assets": "2b2 check release assets", + "generate_truth": "2c generate truth", + "diff_truth": "2d diff truth", + "export_native": "2e export native", + "verify": "3 verify all platforms", + "identity": "3a file identity", + "slots": "3b slot arbitration", + "generate_packs": "4 generate packs", + "generate_manifests": "4b generate install manifests", + "generate_target_manifests": "4c generate target manifests", + "bundled_only": "4d copies only an emulator install provides", + "games_index": "4e games index", + "consistency": "5 consistency check", + "pack_integrity": "6 pack integrity", + "generate_readme": "7 generate readme", + "generate_site": "8 generate site", + "render_site": "8b render site", +} +_KEY_BY_LABEL = {label: key for key, label in STEP_LABELS.items()} + + +def step_number(key: str) -> str: + """The number a step's progress lines carry ("2b2", "4d").""" + return STEP_LABELS[key].split(" ", 1)[0] + + +def step_title(label: str) -> str: + """What the run prints for a label: its name and its place in the run. + + A second command of one step ("2c generate truth (export model)") is + printed as written. + """ + key = _KEY_BY_LABEL.get(label) + if key is None: + return label + return f"{label} [{list(STEP_LABELS).index(key) + 1}/{len(STEP_LABELS)}]" + + +def skip_notice(key: str, reason: str = "") -> None: + """The line a step that does not run prints in place of its output.""" + because = f" ({reason})" if reason else "" + print(f"\n--- {step_title(STEP_LABELS[key])}: SKIPPED{because} ---") diff --git a/scripts/orchestrate/locks.py b/scripts/orchestrate/locks.py new file mode 100644 index 000000000..722583644 --- /dev/null +++ b/scripts/orchestrate/locks.py @@ -0,0 +1,43 @@ +"""The locks a run holds from its first step to its exit.""" + +from __future__ import annotations + +import argparse +import contextlib +import sys + +from core.artifacts import ( + ArtifactLockBusy, + hold_artifact_lock, + hold_repository_outputs, + publish_hold, +) +from core.paths import REPO_ROOT + + +def hold_outputs(args: argparse.Namespace) -> contextlib.ExitStack: + """Take every lock the run holds until it exits, or exit when one is busy.""" + # A second run on the same output directory is refused before any work: + # the database rebuild alone takes minutes, and the reader holding the + # directory would otherwise see the answer only after all of it. The + # hold lasts until this process exits: taken step by step, it let another + # run purge the packs between the build and the integrity check, which + # then reported every platform SKIP and passed. + # database.json, install/, README.md, CONTRIBUTING.md and website/ sit at + # fixed paths (artifacts.REPOSITORY_OUTPUTS), so + # every run holds them too: a run on a scratch --output-dir otherwise + # rewrote them beside the run on dist/. + held = contextlib.ExitStack() + try: + root = str(REPO_ROOT) + held.enter_context(hold_repository_outputs(root)) + # Its steps write database.json, install/ and README.md themselves, + # and take the same lock to do so. + held.enter_context(publish_hold(root)) + if not args.skip_packs: + held.enter_context(hold_artifact_lock(args.output_dir)) + except ArtifactLockBusy as exc: + held.close() + print(f"ERROR: {exc}", file=sys.stderr) + sys.exit(1) + return held diff --git a/scripts/orchestrate/narrowed.py b/scripts/orchestrate/narrowed.py new file mode 100644 index 000000000..8cf9d79f2 --- /dev/null +++ b/scripts/orchestrate/narrowed.py @@ -0,0 +1,154 @@ +"""Step 5 on the narrowed platform packs, built in memory and compared with verify.""" + +from __future__ import annotations + +import contextlib +import io + +from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR +from orchestrate.compare import PACK_NOTES, comparison_inputs, set_difference_lines +from orchestrate.labels import STEP_LABELS, step_title + +# How each pack_narrowings() dimension of a platform pack is compared by +# check_narrowed_packs, or why it is not. A test reads the builder's +# signature against these two tables, so a new narrowing fails it until it +# is compared or a reason is written here. Emulator packs have their own +# table, EMULATOR_NARROWINGS_COMPARED. +NARROWINGS_COMPARED = frozenset({"regions", "target_name", "required_only", "no_game_data"}) +NARROWINGS_NOT_COMPARED = { + "standalone": "an emulator pack mode, compared by check_emulator_packs", + "source": "verify has no platform-only or truth-only report to compare with", + "one_per_slot": "verify has no slot choice to compare with", +} + + +def matrix_coverage(full: bool, count: int) -> range | list[int]: + """Which of *count* variants of one dimension a run compares. + + The full matrix takes every one. The default takes the first, the last + and one in between, which reaches each code path the dimension takes + (an empty selection, a single system, a large one) without its cost. + """ + if full or count <= 3: + return range(count) + return sorted({0, count // 2, count - 1}) + + +def narrowed_variants( + platform: str, config: dict, profiles: dict, platforms_dir: str, full: bool, +) -> list[tuple[str, dict]]: + """(label, builder arguments) of each narrowed pack compared for a platform. + + Every region a file of the platform's cores declares, every hardware + target, every system, --no-game-data and --required-only. Without + *full*, regions, targets and systems are sampled (matrix_coverage). + """ + from resolve import regions as resolve_regions + from model.targets import list_available_targets + + regions = sorted({ + r for entry in resolve_regions.platform_region_index(config, profiles).values() + for r in entry["regions"] + }) + targets = [t["name"] for t in list_available_targets(platform, platforms_dir)] + systems = sorted(config.get("systems") or {}) + variants: list[tuple[str, dict]] = [ + ("--required-only", {"required_only": True}), + ("--no-game-data", {"no_game_data": True}), + ] + variants += [ + (f"--region {regions[i]}", {"regions": [regions[i]]}) + for i in matrix_coverage(full, len(regions)) + ] + variants += [ + (f"--target {targets[i]}", {"target_name": targets[i]}) + for i in matrix_coverage(full, len(targets)) + ] + variants += [ + (f"--system {systems[i]}", {"system_filter": [systems[i]]}) + for i in matrix_coverage(full, len(systems)) + ] + return variants + + +def check_narrowed_packs( + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, full: bool = False, +) -> bool: + """Build each narrowed platform pack in memory and compare it with verify. + + The paths the pack writes against the ones verify credits for the same + narrowing, as check_pack_destinations compares the full packs. Both sides + run offline: a release asset the cache lacks is missing on each. + + Coverage: --required-only and --no-game-data for every platform, and + --region, --target and --system. Measured on 2026-11-05, the full matrix + is 1,150 packs and took 25 minutes, one to two seconds a pack, most + of it platform-wide work (slot overrides, the gap report) that each build + redoes. A run therefore takes the first, middle and last region, target + and system of each platform, 155 packs in about 3 minutes: each value of + a dimension runs the same code, so three reach every path a narrowing + takes (the empty end, one system, a large one). *full* (--full-narrowings) + compares every value. NARROWINGS_NOT_COMPARED says why --source and + --one-per-slot are not compared. + """ + from packs import archive + from packs import platformpack + from resolve import packfiles as packresolve + from packs import coverage + from model.platforms import load_platform_config + from model.targets import load_target_config + + print(f"\n--- {step_title(STEP_LABELS['consistency'])}, narrowed packs ---") + db, zip_contents, profiles, registry, groups = comparison_inputs( + db_path, emulators_dir, platforms_dir + ) + all_ok = True + compared = 0 + with packresolve.offline(): + for _members, platform in groups: + config = load_platform_config(platform, platforms_dir) + for label, narrowing in narrowed_variants( + platform, config, profiles, platforms_dir, full, + ): + target = narrowing.get("target_name") + target_cores = ( + load_target_config(platform, target, platforms_dir) if target else None + ) + record = archive.PackRecord() + with contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + built = platformpack.generate_pack( + platform, platforms_dir, db, "bios", "", + emulators_dir=emulators_dir, zip_contents=zip_contents, + data_registry=registry, emu_profiles=profiles, + target_cores=target_cores, offline=True, record=record, + **narrowing, + ) + report = coverage.verify_platform( + load_platform_config(platform, platforms_dir), db, + emulators_dir, profiles, target_cores=target_cores, + data_dir_registry=registry, + **{k: v for k, v in narrowing.items() if k != "target_name"}, + ) if built else None + compared += 1 + name = f"{platform} {label}" + if report is None: + # The builder declines a system no core of the platform runs. + print(f" {name}: the builder wrote no pack") + all_ok = False + continue + credited = set(report["pack_destinations"]) + trees = set(record.trees) - credited + written = { + m for m in record.members + if not PACK_NOTES.search(m) and m not in trees + } + lines = set_difference_lines(name, credited, written) + if lines: + print("\n".join(lines)) + all_ok = False + scope = "full matrix" if full else "sampled" + print(f" {compared} narrowed platform packs compared ({scope}), " + f"{'all equal' if all_ok else 'differences above'}") + return all_ok diff --git a/scripts/orchestrate/prepare.py b/scripts/orchestrate/prepare.py new file mode 100644 index 000000000..0ce95bde9 --- /dev/null +++ b/scripts/orchestrate/prepare.py @@ -0,0 +1,218 @@ +"""Steps 0 to 2e: schemas, database, catalogs and recipes, upstream refreshes, truth and export.""" + +from __future__ import annotations + +import argparse +import importlib.util +import sys +from pathlib import Path + +from orchestrate import runner +from orchestrate.labels import STEP_LABELS, skip_notice +from orchestrate.results import SKIPPED + + +def database_steps(results: dict) -> bool: + """Steps 0 to 1c: schemas, database, dump catalogs, romset recipes.""" + all_ok = True + # Step 0: the schema check PR validation runs. Without it a profile with + # `cores: [81]` unquoted passed the whole pipeline and failed CI on push. + # jsonschema is tooling only, so its absence skips the step. + if importlib.util.find_spec("jsonschema") is None: + # The skip names the install and what still runs the check, or a + # contributor read SKIPPED, then COMPLETE, and met the failure on push. + skip_notice( + "validate_schemas", + "jsonschema not installed. PR validation runs this check: " + 'pip install "jsonschema[format-nongpl]"', + ) + results["validate_schemas"] = SKIPPED + else: + ok, _ = runner.run( + [sys.executable, "scripts/validate_schemas.py", "--source-only"], + STEP_LABELS["validate_schemas"], + ) + results["validate_schemas"] = ok + all_ok = all_ok and ok + + # Step 1: Generate database + ok, _ = runner.run( + [ + sys.executable, + "scripts/generate_db.py", + "--force", + "--bios-dir", + "bios", + "--output", + "database.json", + ], + STEP_LABELS["generate_db"], + ) + results["generate_db"] = ok + if not ok: + print("\nDatabase generation failed, aborting.") + sys.exit(1) + + # Step 1b: Dump-catalog coverage (offline, reads provenance/ snapshots), + # and which missing dumps the collection already produces: recorded in + # derivable.json, which the site reads instead of rereading bios/. + ok, _ = runner.run( + [sys.executable, "scripts/provenance_report.py", "--derive", + "--write-derivable", "derivable.json"], + STEP_LABELS["provenance"], + ) + results["provenance"] = ok + all_ok = all_ok and ok + + # Step 1c: Which emulator version each arcade archive corresponds to, and + # which pinned archive the collection could rebuild from ROMs it holds. + # Read-only: writing reconstructions is an explicit --write invocation. + ok, _ = runner.run( + [sys.executable, "scripts/romset_recipes.py"], + STEP_LABELS["romset_recipes"], + ) + # A recipe for every archive database.json lists (recipes/archives.json): + # only an archive whose sha1 moved is read again, so the step costs the + # archives added since the last run. + captured, _ = runner.run( + [sys.executable, "scripts/romset_recipes.py", "--capture"], + f"{STEP_LABELS['romset_recipes']} (archive recipes)", + ) + ok = ok and captured + results["romset_recipes"] = ok + all_ok = all_ok and ok + return all_ok + + +def refresh_steps(args: argparse.Namespace, results: dict) -> bool: + """Steps 2 to 2b2: data directories, hash scrapers, release assets.""" + all_ok = True + # Step 2: Refresh data directories + if not args.offline: + ok, _ = runner.run( + [sys.executable, "scripts/refresh_data_dirs.py"], + STEP_LABELS["refresh_data"], + ) + results["refresh_data"] = ok + all_ok = all_ok and ok + else: + skip_notice("refresh_data", "--offline") + results["refresh_data"] = SKIPPED + + # Step 2a: Refresh MAME BIOS hashes + if not args.offline: + ok, _ = runner.run( + [sys.executable, "-m", "scripts.scraper.mame_hash_scraper"], + STEP_LABELS["mame_hashes"], + ) + results["mame_hashes"] = ok + all_ok = all_ok and ok + else: + skip_notice("mame_hashes", "--offline") + results["mame_hashes"] = SKIPPED + + # Step 2a2: Refresh FBNeo BIOS hashes + if not args.offline: + ok, _ = runner.run( + [sys.executable, "-m", "scripts.scraper.fbneo_hash_scraper"], + STEP_LABELS["fbneo_hashes"], + ) + results["fbneo_hashes"] = ok + all_ok = all_ok and ok + else: + skip_notice("fbneo_hashes", "--offline") + results["fbneo_hashes"] = SKIPPED + + # Step 2b: Check buildbot system directory (non-blocking) + if args.check_buildbot and not args.offline: + ok, _ = runner.run( + [sys.executable, "scripts/check_buildbot_system.py"], + STEP_LABELS["check_buildbot"], + ) + results["check_buildbot"] = ok + else: + if args.check_buildbot: + skip_notice("check_buildbot", "--offline") + results["check_buildbot"] = SKIPPED + + # Step 2b2: The release must serve the bytes the manifests describe. The + # installer compares Content-Length with the manifest size, so an asset + # uploaded before its local file was rebuilt fails every install of it. + if not args.offline: + ok, _ = runner.run( + [sys.executable, "scripts/check_release_assets.py"], + STEP_LABELS["check_release_assets"], + ) + results["check_release_assets"] = ok + all_ok = all_ok and ok + else: + skip_notice("check_release_assets", "--offline") + results["check_release_assets"] = SKIPPED + return all_ok + + +def truth_steps(args: argparse.Namespace, results: dict) -> bool: + """Steps 2c to 2e: truth model, its diff, the native export.""" + all_ok = True + # Step 2c: Generate truth YAMLs + # A targeted run writes each platform's model under the target as that + # platform files it, and the diff is told the target and reads the same place. + truth_dir = Path(args.output_dir) / "truth" + + if args.with_truth or args.with_export: + truth_cmd = [ + sys.executable, + "scripts/generate_truth.py", + "--all", + "--output-dir", + str(Path(args.output_dir) / "truth"), + ] + if args.target: + truth_cmd.extend(["--target", args.target]) + ok, _ = runner.run(truth_cmd, STEP_LABELS["generate_truth"]) + # A native file is one per platform, never per target: the export + # corrects it against the full model, which a targeted run does not + # write. + if ok and args.with_export and args.target: + ok, _ = runner.run(truth_cmd[:-2], "2c generate truth (export model)") + results["generate_truth"] = ok + all_ok = all_ok and ok + else: + results["generate_truth"] = SKIPPED + + # Step 2d: Diff truth vs scraped + if args.with_truth or args.with_export: + diff_cmd = [sys.executable, "scripts/diff_truth.py", "--all"] + diff_cmd.extend(["--truth-dir", str(truth_dir)]) + if args.target: + diff_cmd.extend(["--target", args.target]) + ok, _ = runner.run(diff_cmd, STEP_LABELS["diff_truth"]) + results["diff_truth"] = ok + all_ok = all_ok and ok + else: + results["diff_truth"] = SKIPPED + + # Step 2e: Export native formats + if args.with_export: + export_cmd = [ + sys.executable, + "scripts/export_native.py", + "--all", + # exports/ is committed with the code, like README.md and + # install/: written under the pack directory it went stale on + # every green run. + "--truth-dir", + str(Path(args.output_dir) / "truth"), + ] + # Seven of the formats carry code, so the export patches the + # platform's own file rather than regenerating it. Offline that + # file has to be in the cache already. + if not args.offline: + export_cmd.append("--fetch") + ok, _ = runner.run(export_cmd, STEP_LABELS["export_native"]) + results["export_native"] = ok + all_ok = all_ok and ok + else: + results["export_native"] = SKIPPED + + return all_ok diff --git a/scripts/orchestrate/reports.py b/scripts/orchestrate/reports.py new file mode 100644 index 000000000..ae91fd85e --- /dev/null +++ b/scripts/orchestrate/reports.py @@ -0,0 +1,143 @@ +"""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/orchestrate/results.py b/scripts/orchestrate/results.py new file mode 100644 index 000000000..332bd101c --- /dev/null +++ b/scripts/orchestrate/results.py @@ -0,0 +1,72 @@ +"""The outcome and duration of each step, and the summary table the run ends on.""" + +from __future__ import annotations + +import time + +from orchestrate.labels import step_number + +# Steps that report without failing the run. +NON_BLOCKING = frozenset({"check_buildbot"}) + + +class StepResults(dict): + """The outcome of each step, and how long it took. + + A step's time runs from the previous step's outcome to its own, so the + in-process steps (consistency, the truth diff) are timed like the ones + run() launches. The summary prints it: finding the slow step in a + twenty-minute run meant reading the whole log. + """ + + def __init__(self, start: float) -> None: + super().__init__() + self.seconds: dict[str, float] = {} + self._mark = start + + def __setitem__(self, step: str, outcome: object) -> None: + now = time.monotonic() + self.seconds[step] = self.seconds.get(step, 0.0) + now - self._mark + self._mark = now + super().__setitem__(step, outcome) + + +class _Skipped: + """A step that did not run. Truthy, so it never fails the pipeline, and + distinct, so the summary does not report it as work that was done.""" + + def __bool__(self) -> bool: + return True + + def __repr__(self) -> str: + return "SKIPPED" + + +SKIPPED = _Skipped() + + +def print_summary(results: StepResults, total_start: float, all_ok: bool) -> None: + """The table of every step's outcome and duration, then the verdict.""" + total_elapsed = time.monotonic() - total_start + print(f"\n{'=' * 60}") + warned = [] + for step, outcome in results.items(): + # The number finds the step's lines in the log, the key is the + # name a caller reading the results knows it by. + number = step_number(step) + if outcome is SKIPPED: + print(f" {number:<4} {step:.<40} SKIPPED") + continue + label = "OK" if outcome else "FAILED" + if not outcome and step in NON_BLOCKING: + # Printed FAILED right above "Pipeline COMPLETE", it read as a + # contradiction: the step reports, it does not stop the run. + label = "WARN" + warned.append(step) + print(f" {number:<4} {step:.<40} {label:<7}{results.seconds[step]:>8.1f}s") + print(f" {'':<4} {'total':.<40} {'':<7}{total_elapsed:>8.1f}s") + print(f"{'=' * 60}") + print(f" Pipeline {'COMPLETE' if all_ok else 'FINISHED WITH ERRORS'}") + if warned: + print(f" {', '.join(warned)} reported a difference, which does not fail the run") + print(f"{'=' * 60}") diff --git a/scripts/orchestrate/runner.py b/scripts/orchestrate/runner.py new file mode 100644 index 000000000..9a2eb0711 --- /dev/null +++ b/scripts/orchestrate/runner.py @@ -0,0 +1,53 @@ +"""Each step's command, run from the repository root with its output echoed as it comes.""" + +from __future__ import annotations + +import os +import subprocess +import time +from pathlib import Path + +from core.paths import REPO_ROOT +from orchestrate.labels import step_title + + +def pack_output_dir(typed: str | None) -> str: + """The pack directory as an absolute path. + + Every step runs from the repository root, while the lock and the purge + of stale packs ran here, against the caller's directory: started from + scripts/, the run locked and purged scripts/dist/ and wrote its packs to + dist/. A directory the caller typed is read from where they typed it. + """ + if typed is None: + return str(REPO_ROOT / "dist") + return str(Path(typed).resolve()) + + +def run(cmd: list[str], label: str) -> tuple[bool, str]: + """Run a command, echoing its output as it comes. Returns (success, output). + + The output used to be captured and printed when the step ended, stderr + after stdout: a twenty-minute pack build showed nothing, and a warning + landed far from the line it was about. One stream, read line by line. + """ + title = step_title(label) + print(f"\n--- {title} ---", flush=True) + start = time.monotonic() + lines: list[str] = [] + with subprocess.Popen( + cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, + # Node's compile cache lands in /tmp, a 4 GB tmpfs here: the site + # build filled it to 3.4 GB across a day of pipeline runs. + cwd=str(REPO_ROOT), + env={**os.environ, "PYTHONUNBUFFERED": "1", "NODE_DISABLE_COMPILE_CACHE": "1"}, + ) as proc: + for line in proc.stdout or (): + lines.append(line) + print(line, end="", flush=True) + returncode = proc.wait() + elapsed = time.monotonic() - start + + ok = returncode == 0 + print(f"--- {title}: {'OK' if ok else 'FAILED'} ({elapsed:.1f}s) ---") + return ok, "".join(lines) diff --git a/scripts/orchestrate/splitcheck.py b/scripts/orchestrate/splitcheck.py new file mode 100644 index 000000000..af0170275 --- /dev/null +++ b/scripts/orchestrate/splitcheck.py @@ -0,0 +1,85 @@ +"""Step 5 on the --split parts: together they must be the full pack, path for path and byte for byte.""" + +from __future__ import annotations + +import contextlib +import io +from collections.abc import Callable +from typing import TYPE_CHECKING + +from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR +from orchestrate.compare import PACK_NOTES, comparison_inputs +from orchestrate.labels import STEP_LABELS, step_title + +if TYPE_CHECKING: + from packs.archive import PackRecord + + +def split_differences( + full: PackRecord, parts: dict[str, PackRecord], same_bytes: Callable[[str, str], bool], +) -> list[str]: + """Where the --split parts of a pack, together, are not the full pack. + + A path in a part and not in the full pack, a path of the full pack in no + part, and a path a part fills with other bytes than the full pack. + """ + full_members = {m for m in full.members if not PACK_NOTES.search(m)} + union = { + m for record in parts.values() for m in record.members + if not PACK_NOTES.search(m) + } + lines = [f"in a part, not in the full pack: {m}" for m in sorted(union - full_members)] + lines += [f"in the full pack, in no part: {m}" for m in sorted(full_members - union)] + lines += sorted({ + f"other bytes in {name}: {member}" + for name, record in parts.items() + for member, source in record.sources.items() + if member in full.sources and not same_bytes(source, full.sources[member]) + }) + return lines + + +def check_split_packs( + emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, + db_path: str = DB_FILE, +) -> bool: + """Build each platform's --split parts in memory and compare them with + the full pack: the parts must add up to it, path for path and byte for + byte. Each part is a pack of its own and used to settle its paths alone: + RetroDECK's parts carried bios/SGB1.sfc as a file and as a directory, + RetroBat's 21 openmsx/ twins of openMSX/ files. Offline, as every + comparison of this step. + """ + from packs import archive + from packs import platformpack + from resolve import packfiles as packresolve + + print(f"\n--- {step_title(STEP_LABELS['consistency'])}, split packs ---") + db, zip_contents, profiles, registry, groups = comparison_inputs( + db_path, emulators_dir, platforms_dir + ) + all_ok = True + with packresolve.offline(): + for _members, platform in groups: + args = dict( + emulators_dir=emulators_dir, zip_contents=zip_contents, + data_registry=registry, emu_profiles=profiles, offline=True, + ) + full = archive.PackRecord() + parts: dict[str, archive.PackRecord] = {} + with contextlib.redirect_stdout(io.StringIO()), \ + contextlib.redirect_stderr(io.StringIO()): + platformpack.generate_pack( + platform, platforms_dir, db, "bios", "", record=full, **args, + ) + platformpack.generate_split_packs( + platform, platforms_dir, db, "bios", "", records=parts, **args, + ) + lines = split_differences(full, parts, archive.same_bytes) + if lines: + all_ok = False + print(f" {platform} --split: {len(lines)} differences") + print("\n".join(f" {line}" for line in lines[:20])) + print(f" {len(groups)} split platform packs compared, " + f"{'all equal' if all_ok else 'differences above'}") + return all_ok diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index fcf3f7e5b..f4a0a2f73 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -100,7 +100,7 @@ def _report_pack_counts( The check compares these counts against what verify.py reports for the same platform, so the wording is a contract: parse_pack_counts - in pipeline.py matches on it. + in orchestrate/reports.py matches on it. """ 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") diff --git a/scripts/pipeline.py b/scripts/pipeline.py index a39970c8a..439b7af34 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -45,20 +45,9 @@ Usage: from __future__ import annotations import argparse -import atexit -import contextlib -import importlib.util -import io -import os -import re -import shutil -import subprocess import sys -import tempfile import time -from collections.abc import Callable, Iterator from pathlib import Path -from typing import TYPE_CHECKING # The build scripts need CPython 3.9, which builds the same database, # manifests and packs as 3.12. @@ -69,994 +58,22 @@ if sys.version_info < (3, 9): sys.exit(f"pipeline.py needs Python 3.9 or newer, this is {sys.version.split()[0]}") sys.path.insert(0, str(Path(__file__).parent)) -from core.paths import DB_FILE, EMULATORS_DIR, PLATFORMS_DIR -from core.artifacts import ( - ArtifactLockBusy, - artifact_lock, - hold_artifact_lock, - hold_repository_outputs, - publish_hold, -) from core.github import github_token -from model.registry import load_data_dir_registry -from model.profiles import reads_own_files -from packs.datadirs import hold_data_dirs -from packs.paths import MEDIA_MARKER - -if TYPE_CHECKING: - from packs.archive import PackRecord - - -class StepResults(dict): - """The outcome of each step, and how long it took. - - A step's time runs from the previous step's outcome to its own, so the - in-process steps (consistency, the truth diff) are timed like the ones - run() launches. The summary prints it: finding the slow step in a - twenty-minute run meant reading the whole log. - """ - - def __init__(self, start: float) -> None: - super().__init__() - self.seconds: dict[str, float] = {} - self._mark = start - - def __setitem__(self, step: str, outcome: object) -> None: - now = time.monotonic() - self.seconds[step] = self.seconds.get(step, 0.0) + now - self._mark - self._mark = now - super().__setitem__(step, outcome) - - - -# Steps that report without failing the run. -NON_BLOCKING = frozenset({"check_buildbot"}) - -# Every step in run order, by its results key. The position and the total -# printed during the run come from this list: hand-written "N/8" labels -# counted 8 steps in a run of 24, and the eighth came before 8b. The summary -# prints the same labels the run printed, so a FAILED row is found in the -# log by its number. -STEP_LABELS: dict[str, str] = { - "validate_schemas": "0 validate schemas", - "generate_db": "1 generate database", - "provenance": "1b provenance report", - "romset_recipes": "1c romset recipes", - "refresh_data": "2 refresh data directories", - "mame_hashes": "2a refresh MAME hashes", - "fbneo_hashes": "2a2 refresh FBNeo hashes", - "check_buildbot": "2b check buildbot system", - "check_release_assets": "2b2 check release assets", - "generate_truth": "2c generate truth", - "diff_truth": "2d diff truth", - "export_native": "2e export native", - "verify": "3 verify all platforms", - "identity": "3a file identity", - "slots": "3b slot arbitration", - "generate_packs": "4 generate packs", - "generate_manifests": "4b generate install manifests", - "generate_target_manifests": "4c generate target manifests", - "bundled_only": "4d copies only an emulator install provides", - "games_index": "4e games index", - "consistency": "5 consistency check", - "pack_integrity": "6 pack integrity", - "generate_readme": "7 generate readme", - "generate_site": "8 generate site", - "render_site": "8b render site", -} -_KEY_BY_LABEL = {label: key for key, label in STEP_LABELS.items()} - - -def step_number(key: str) -> str: - """The number a step's progress lines carry ("2b2", "4d").""" - return STEP_LABELS[key].split(" ", 1)[0] - - -def step_title(label: str) -> str: - """What the run prints for a label: its name and its place in the run. - - A second command of one step ("2c generate truth (export model)") is - printed as written. - """ - key = _KEY_BY_LABEL.get(label) - if key is None: - return label - return f"{label} [{list(STEP_LABELS).index(key) + 1}/{len(STEP_LABELS)}]" - - -def skip_notice(key: str, reason: str = "") -> None: - """The line a step that does not run prints in place of its output.""" - because = f" ({reason})" if reason else "" - print(f"\n--- {step_title(STEP_LABELS[key])}: SKIPPED{because} ---") - -def _output_dir(typed: str | None) -> str: - """The pack directory as an absolute path. - - Every step runs from the repository root, while the lock and the purge - of stale packs ran here, against the caller's directory: started from - scripts/, the run locked and purged scripts/dist/ and wrote its packs to - dist/. A directory the caller typed is read from where they typed it. - """ - if typed is None: - return str(Path(__file__).resolve().parent.parent / "dist") - return str(Path(typed).resolve()) - - -def run(cmd: list[str], label: str) -> tuple[bool, str]: - """Run a command, echoing its output as it comes. Returns (success, output). - - The output used to be captured and printed when the step ended, stderr - after stdout: a twenty-minute pack build showed nothing, and a warning - landed far from the line it was about. One stream, read line by line. - """ - title = step_title(label) - print(f"\n--- {title} ---", flush=True) - start = time.monotonic() - repo_root = str(Path(__file__).resolve().parent.parent) - lines: list[str] = [] - with subprocess.Popen( - cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, - # Node's compile cache lands in /tmp, a 4 GB tmpfs here: the site - # build filled it to 3.4 GB across a day of pipeline runs. - cwd=repo_root, - env={**os.environ, "PYTHONUNBUFFERED": "1", "NODE_DISABLE_COMPILE_CACHE": "1"}, - ) as proc: - for line in proc.stdout or (): - lines.append(line) - print(line, end="", flush=True) - returncode = proc.wait() - elapsed = time.monotonic() - start - - ok = returncode == 0 - print(f"--- {title}: {'OK' if ok else 'FAILED'} ({elapsed:.1f}s) ---") - return ok, "".join(lines) - - -# "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 _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 - - -def check_consistency( - verify_output: str, pack_output: 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) - - 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 - - status = "OK" if all_ok else "FAILED" - print(f"--- {step_title(STEP_LABELS['consistency'])}, counts: {status} ---") - return all_ok - - -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 - - -# Members the builder writes for the reader or the device rather than for a -# core: the documents, and the empty marker an Android pack carries. -_PACK_NOTES = re.compile( - r"(^README\.txt$|^manifest\.json$|(^|/)(INSTRUCTIONS|RENAMED)_[^/]*\.txt$" - rf"|(^|/){re.escape(MEDIA_MARKER)}$)" +from orchestrate.build import index_steps, pack_steps, verify_steps +from orchestrate.checks import check_steps +from orchestrate.docs import docs_steps +from orchestrate.guards import ( + refuse_offline_export_without_originals, + refuse_offline_without_caches, + refuse_unapplied_flags, ) +from orchestrate.locks import hold_outputs +from orchestrate.prepare import database_steps, refresh_steps, truth_steps +from orchestrate.results import StepResults, print_summary +from orchestrate.runner import pack_output_dir -def _tree_members( - platform: str, platforms_dir: str, emulators_dir: str = EMULATORS_DIR, -) -> dict[str, int]: - """Archive path -> size of every file the platform's data trees can add.""" - from packs import datatrees - from model.profiles import load_emulator_profiles - from model.platforms import load_platform_config - from packs.archive import Placed - from packs.paths import flat_arcname - - config = load_platform_config(platform, platforms_dir) - base_dest = config.get("base_destination", "") - registry = load_data_dir_registry(platforms_dir) - core_trees = datatrees.core_data_trees( - config, load_emulator_profiles(emulators_dir), platform, registry, - ) - members: dict[str, int] = {} - with contextlib.redirect_stdout(io.StringIO()): - for src, full in datatrees.data_directory_members( - config.get("systems", {}), registry, - platform, base_dest, Placed(False), - core_trees=core_trees, - ): - members[flat_arcname(full, base_dest, True)] = os.path.getsize(src) - return members - - -def _set_difference_lines(label: str, credited: set[str], written: set[str]) -> list[str]: - """The paths one side has and the other lacks, ten of each at most.""" - lines = [] - for side, paths in (("verify only", credited - written), ("pack only", written - credited)): - if paths: - shown = ", ".join(sorted(paths)[:10]) - more = f" (+{len(paths) - 10})" if len(paths) > 10 else "" - lines.append(f" {label}: {side} {len(paths)}: {shown}{more}") - return lines - - -def check_pack_destinations( - destinations_file: str, pack_output: str, platforms_dir: str = PLATFORMS_DIR, -) -> bool: - """Compare the paths verify credits with the members of each archive. - - Equal counts hid a file credited on one side and another written on the - other. The trees and the notes are the archive's own: a tree member is - 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})") - return False - paths = parse_pack_paths(pack_output) - if not paths: - print(" no archive named in the pack output") - 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)] - if not names: - print(f" {label}: no verify destinations") - all_ok = False - continue - entry = credited_by[names[0]] - credited = set(entry["pack_destinations"]) - trees = _tree_members(entry["platform"], platforms_dir) - with zipfile.ZipFile(zip_path) as zf: - written = { - info.filename for info in zf.infolist() - if not info.is_dir() - and not _PACK_NOTES.search(info.filename) - and not ( - trees.get(info.filename) == info.file_size - and info.filename not in credited - ) - } - lines = _set_difference_lines(label, credited, written) - if lines: - print("\n".join(lines)) - all_ok = False - else: - print(f" {label}: {len(credited)} paths, the same on both sides") - return all_ok - - -# The narrowings an emulator or system pack takes, compared by -# check_emulator_packs. A test holds this to the builder's parameters. -EMULATOR_NARROWINGS_COMPARED = frozenset({"standalone", "regions", "required_only"}) - - -def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict]]: - """(label, builder arguments) of each narrowed emulator pack compared. - - --required-only always, and each region the profiles' files declare, - sampled as check_narrowed_packs samples them unless *full*. A profile - without a regional file has nothing --region could withdraw. - """ - from model import region - - regions = sorted({ - r for profile in profiles for fe in profile.get("files") or [] - for r in region.normalize_declared(fe.get("region")) - }) - variants: list[tuple[str, dict]] = [("", {}), (" --required-only", {"required_only": True})] - variants += [ - (f" --region {regions[i]}", {"regions": [regions[i]]}) - for i in _matrix_coverage(full, len(regions)) - ] - return variants - - -def check_emulator_packs( - emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, - db_path: str = DB_FILE, full: bool = False, -) -> bool: - """Build every emulator and system pack in memory and compare it with verify. - - Each profile in each build it has (libretro, standalone), full and under - each narrowing of emulator_variants: the paths the pack fills with the - profile's files against the ones verify credits. The region and - required-only rules are written twice, once per side, and only this - comparison holds them together. No archive is written and no file read. - """ - from packs import archive - from packs import emulatorpack - from resolve import packfiles as packresolve - from packs import emulatorcheck - from model.profiles import ( - ProfileSelectionError, - load_emulator_profiles, - profiles_for_systems, - select_emulator_profiles, - ) - from model.systems import norm_system_id - from core.ziptools import build_zip_contents_index - from model.database import load_database - - print(f"\n--- {step_title(STEP_LABELS['consistency'])}, emulator packs ---") - db = load_database(db_path) - zip_contents = build_zip_contents_index(db) - profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) - - def compare(names: list[str], standalone: bool, label: str, **narrowing: object) -> bool: - record = archive.PackRecord() - # The pack is built offline: verify counts a release asset the cache - # lacks the same way, missing, as the narrowed-pack step does. - with packresolve.offline(), contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()): - emulatorpack.generate_emulator_pack( - names, emulators_dir, db, "bios", "", standalone, - zip_contents=zip_contents, offline=True, platforms_dir=platforms_dir, - record=record, **narrowing, - ) - report = emulatorcheck.verify_emulator( - names, emulators_dir, db, standalone, platforms_dir=platforms_dir, - **narrowing, - ) - lines = _set_difference_lines( - label, set(report["pack_destinations"]), set(record.files) - ) - if lines: - print("\n".join(lines)) - return not lines - - all_ok = True - compared = 0 - for name in sorted(profiles): - if profiles[name].get("type") == "alias": - continue # selects the profile it names, compared under that name - for standalone in (False, True): - try: - select_emulator_profiles([name], profiles, standalone) - except ProfileSelectionError: - continue - for tag, narrowing in emulator_variants([profiles[name]], full): - compared += 1 - label = f"{name}{' --standalone' if standalone else ''}{tag}" - all_ok = compare([name], standalone, label, **narrowing) and all_ok - print(f" {compared} emulator packs compared, {'all equal' if all_ok else 'differences above'}") - # A system pack builds every profile of the system together: a placement - # rule that only goes wrong when two profiles share a path (the bluemsx - # tree beside msx-emu's files) never meets in a one-profile pack. - systems = sorted({ - norm_system_id(str(sid)) - for profile in profiles.values() - if reads_own_files(profile) - for sid in profile.get("systems") or [] - }) - systems_ok = True - compared = 0 - for sid in systems: - for standalone in (False, True): - matching = profiles_for_systems(profiles, [sid], standalone) - if len(matching) < 2: - continue - for tag, narrowing in emulator_variants( - [profiles[n] for n in matching if n in profiles], full - ): - compared += 1 - label = f"--system {sid}{' --standalone' if standalone else ''}{tag}" - systems_ok = compare( - matching, standalone, label, system_ids=[sid], **narrowing - ) and systems_ok - print(f" {compared} system packs compared, " - f"{'all equal' if systems_ok else 'differences above'}") - return all_ok and systems_ok - - -# How each pack_narrowings() dimension of a platform pack is compared by -# check_narrowed_packs, or why it is not. A test reads the builder's -# signature against these two tables, so a new narrowing fails it until it -# is compared or a reason is written here. Emulator packs have their own -# table, EMULATOR_NARROWINGS_COMPARED. -NARROWINGS_COMPARED = frozenset({"regions", "target_name", "required_only", "no_game_data"}) -NARROWINGS_NOT_COMPARED = { - "standalone": "an emulator pack mode, compared by check_emulator_packs", - "source": "verify has no platform-only or truth-only report to compare with", - "one_per_slot": "verify has no slot choice to compare with", -} - - -def _matrix_coverage(full: bool, count: int) -> range | list[int]: - """Which of *count* variants of one dimension a run compares. - - The full matrix takes every one. The default takes the first, the last - and one in between, which reaches each code path the dimension takes - (an empty selection, a single system, a large one) without its cost. - """ - if full or count <= 3: - return range(count) - return sorted({0, count // 2, count - 1}) - - -def narrowed_variants( - platform: str, config: dict, profiles: dict, platforms_dir: str, full: bool, -) -> list[tuple[str, dict]]: - """(label, builder arguments) of each narrowed pack compared for a platform. - - Every region a file of the platform's cores declares, every hardware - target, every system, --no-game-data and --required-only. Without - *full*, regions, targets and systems are sampled (_matrix_coverage). - """ - from resolve import regions as resolve_regions - from model.targets import list_available_targets - - regions = sorted({ - r for entry in resolve_regions.platform_region_index(config, profiles).values() - for r in entry["regions"] - }) - targets = [t["name"] for t in list_available_targets(platform, platforms_dir)] - systems = sorted(config.get("systems") or {}) - variants: list[tuple[str, dict]] = [ - ("--required-only", {"required_only": True}), - ("--no-game-data", {"no_game_data": True}), - ] - variants += [ - (f"--region {regions[i]}", {"regions": [regions[i]]}) - for i in _matrix_coverage(full, len(regions)) - ] - variants += [ - (f"--target {targets[i]}", {"target_name": targets[i]}) - for i in _matrix_coverage(full, len(targets)) - ] - variants += [ - (f"--system {systems[i]}", {"system_filter": [systems[i]]}) - for i in _matrix_coverage(full, len(systems)) - ] - return variants - - -def _comparison_inputs( - db_path: str, emulators_dir: str, platforms_dir: str, -) -> tuple[dict, dict, dict, dict, list[tuple[list[str], str]]]: - """What the in-memory pack comparisons read: the database, its ZIP - index, the profiles, the data-directory registry and the platform groups.""" - from core.ziptools import build_zip_contents_index - from resolve.grouping import group_identical_platforms - from model.registry import list_registered_platforms - from model.database import load_database - from model.profiles import load_emulator_profiles - - db = load_database(db_path) - groups = group_identical_platforms(list_registered_platforms(platforms_dir), platforms_dir) - return (db, build_zip_contents_index(db), load_emulator_profiles(emulators_dir), - load_data_dir_registry(platforms_dir), groups) - - -def check_narrowed_packs( - emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, - db_path: str = DB_FILE, full: bool = False, -) -> bool: - """Build each narrowed platform pack in memory and compare it with verify. - - The paths the pack writes against the ones verify credits for the same - narrowing, as check_pack_destinations compares the full packs. Both sides - run offline: a release asset the cache lacks is missing on each. - - Coverage: --required-only and --no-game-data for every platform, and - --region, --target and --system. Measured on 2026-11-05, the full matrix - is 1,150 packs and took 25 minutes, one to two seconds a pack, most - of it platform-wide work (slot overrides, the gap report) that each build - redoes. A run therefore takes the first, middle and last region, target - and system of each platform, 155 packs in about 3 minutes: each value of - a dimension runs the same code, so three reach every path a narrowing - takes (the empty end, one system, a large one). *full* (--full-narrowings) - compares every value. NARROWINGS_NOT_COMPARED says why --source and - --one-per-slot are not compared. - """ - from packs import archive - from packs import platformpack - from resolve import packfiles as packresolve - from packs import coverage - from model.platforms import load_platform_config - from model.targets import load_target_config - - print(f"\n--- {step_title(STEP_LABELS['consistency'])}, narrowed packs ---") - db, zip_contents, profiles, registry, groups = _comparison_inputs( - db_path, emulators_dir, platforms_dir - ) - all_ok = True - compared = 0 - with packresolve.offline(): - for _members, platform in groups: - config = load_platform_config(platform, platforms_dir) - for label, narrowing in narrowed_variants( - platform, config, profiles, platforms_dir, full, - ): - target = narrowing.get("target_name") - target_cores = ( - load_target_config(platform, target, platforms_dir) if target else None - ) - record = archive.PackRecord() - with contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()): - built = platformpack.generate_pack( - platform, platforms_dir, db, "bios", "", - emulators_dir=emulators_dir, zip_contents=zip_contents, - data_registry=registry, emu_profiles=profiles, - target_cores=target_cores, offline=True, record=record, - **narrowing, - ) - report = coverage.verify_platform( - load_platform_config(platform, platforms_dir), db, - emulators_dir, profiles, target_cores=target_cores, - data_dir_registry=registry, - **{k: v for k, v in narrowing.items() if k != "target_name"}, - ) if built else None - compared += 1 - name = f"{platform} {label}" - if report is None: - # The builder declines a system no core of the platform runs. - print(f" {name}: the builder wrote no pack") - all_ok = False - continue - credited = set(report["pack_destinations"]) - trees = set(record.trees) - credited - written = { - m for m in record.members - if not _PACK_NOTES.search(m) and m not in trees - } - lines = _set_difference_lines(name, credited, written) - if lines: - print("\n".join(lines)) - all_ok = False - scope = "full matrix" if full else "sampled" - print(f" {compared} narrowed platform packs compared ({scope}), " - f"{'all equal' if all_ok else 'differences above'}") - return all_ok - - -def split_differences( - full: PackRecord, parts: dict[str, PackRecord], same_bytes: Callable[[str, str], bool], -) -> list[str]: - """Where the --split parts of a pack, together, are not the full pack. - - A path in a part and not in the full pack, a path of the full pack in no - part, and a path a part fills with other bytes than the full pack. - """ - full_members = {m for m in full.members if not _PACK_NOTES.search(m)} - union = { - m for record in parts.values() for m in record.members - if not _PACK_NOTES.search(m) - } - lines = [f"in a part, not in the full pack: {m}" for m in sorted(union - full_members)] - lines += [f"in the full pack, in no part: {m}" for m in sorted(full_members - union)] - lines += sorted({ - f"other bytes in {name}: {member}" - for name, record in parts.items() - for member, source in record.sources.items() - if member in full.sources and not same_bytes(source, full.sources[member]) - }) - return lines - - -def check_split_packs( - emulators_dir: str = EMULATORS_DIR, platforms_dir: str = PLATFORMS_DIR, - db_path: str = DB_FILE, -) -> bool: - """Build each platform's --split parts in memory and compare them with - the full pack: the parts must add up to it, path for path and byte for - byte. Each part is a pack of its own and used to settle its paths alone: - RetroDECK's parts carried bios/SGB1.sfc as a file and as a directory, - RetroBat's 21 openmsx/ twins of openMSX/ files. Offline, as every - comparison of this step. - """ - from packs import archive - from packs import platformpack - from resolve import packfiles as packresolve - - print(f"\n--- {step_title(STEP_LABELS['consistency'])}, split packs ---") - db, zip_contents, profiles, registry, groups = _comparison_inputs( - db_path, emulators_dir, platforms_dir - ) - all_ok = True - with packresolve.offline(): - for _members, platform in groups: - args = dict( - emulators_dir=emulators_dir, zip_contents=zip_contents, - data_registry=registry, emu_profiles=profiles, offline=True, - ) - full = archive.PackRecord() - parts: dict[str, archive.PackRecord] = {} - with contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()): - platformpack.generate_pack( - platform, platforms_dir, db, "bios", "", record=full, **args, - ) - platformpack.generate_split_packs( - platform, platforms_dir, db, "bios", "", records=parts, **args, - ) - lines = split_differences(full, parts, archive.same_bytes) - if lines: - all_ok = False - print(f" {platform} --split: {len(lines)} differences") - print("\n".join(f" {line}" for line in lines[:20])) - print(f" {len(groups)} split platform packs compared, " - f"{'all equal' if all_ok else 'differences above'}") - return all_ok - - -class _Skipped: - """A step that did not run. Truthy, so it never fails the pipeline, and - distinct, so the summary does not report it as work that was done.""" - - def __bool__(self) -> bool: - return True - - def __repr__(self) -> str: - return "SKIPPED" - - -SKIPPED = _Skipped() - - -def integrity_command(args: argparse.Namespace) -> list[str]: - """Step 6: check the packs step 4 built, under the same expectation.""" - cmd = [ - sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", - "--output-dir", args.output_dir, - ] - # Without the target a targeted run reported every system the target - # removed as missing from a pack that was exactly right. Without - # --all-variants the five narrowed packs were never opened, and an empty - # _Platform pack passed. - if args.target: - cmd.extend(["--target", args.target]) - if args.all_variants: - cmd.append("--all-variants") - return cmd - - -def _refuse_unapplied_flags( - parser: argparse.ArgumentParser, args: argparse.Namespace -) -> None: - """A flag the run would drop is refused before any step. - - --all-variants builds every source itself, so a --source beside it is - dropped; --skip-packs builds none, so both are, and step 5 does not run - for --full-narrowings to widen, nor does it without a full pack. - """ - # --source defaults to None so a typed `--source full` is seen: compared - # with its default value, it went through beside the modes that refuse it. - source_given = args.source is not None - if args.all_variants and source_given: - parser.error("--source is incompatible with --all-variants") - if args.skip_packs: - for flag, on in (("--source", source_given), - ("--all-variants", args.all_variants), - ("--full-narrowings", args.full_narrowings)): - if on: - parser.error(f"{flag} is incompatible with --skip-packs") - # Step 5 compares the full pack, and --source platform or truth builds - # none: the comparison is skipped and the flag had no effect. - if args.full_narrowings and source_given and args.source != "full": - parser.error(f"--full-narrowings is incompatible with --source {args.source}") - if args.source is None: - args.source = "full" - - -def _refuse_offline_without_caches( - parser: argparse.ArgumentParser, args: argparse.Namespace, platforms_dir: str = PLATFORMS_DIR, -) -> None: - """An offline run that builds packs needs the data directories cached. - - On a fresh clone none is: --offline skips the refresh, and the run went - through the database, verify and every pack before failing at the end - of the build. Only an empty cache is refused here: with some cached, the - packs decide which ones they need and the build names the rest. - """ - if not args.offline or args.skip_packs: - return - registry = load_data_dir_registry(platforms_dir) - if registry and not any(os.path.isdir(e.get("local_cache") or "") for e in registry.values()): - parser.error( - "no data directory is cached and --offline skips their refresh: run " - "python scripts/refresh_data_dirs.py once, or drop --offline" - ) - - -def _refuse_offline_export_without_originals( - parser: argparse.ArgumentParser, args: argparse.Namespace, - cache: str = ".cache/upstream-native", -) -> None: - """An offline run with --with-export needs each patched file cached. - - Seven formats carry code, so step 2e patches the platform's own file, - which --offline does not fetch. On a fresh clone the database, verify - and the truth model were built before step 2e failed on every one. - """ - if not (args.offline and args.with_export): - return - from exporter import discover_exporters - - lacking = sorted( - name for name, exporter in discover_exporters().items() - if exporter.needs_original() and not any(Path(cache, name).glob("*")) - ) - if lacking: - parser.error( - f"--with-export patches each platform's own file, and {cache}/ holds none " - f"for {', '.join(lacking)}: run python scripts/export_native.py --all " - "--refresh-cache once, or drop --offline" - ) - - -def _truth_steps(args: argparse.Namespace, results: dict) -> bool: - """Steps 2c to 2e: truth model, its diff, the native export.""" - all_ok = True - # Step 2c: Generate truth YAMLs - # A targeted run writes each platform's model under the target as that - # platform files it, and the diff is told the target and reads the same place. - truth_dir = Path(args.output_dir) / "truth" - - if args.with_truth or args.with_export: - truth_cmd = [ - sys.executable, - "scripts/generate_truth.py", - "--all", - "--output-dir", - str(Path(args.output_dir) / "truth"), - ] - if args.target: - truth_cmd.extend(["--target", args.target]) - ok, _ = run(truth_cmd, STEP_LABELS["generate_truth"]) - # A native file is one per platform, never per target: the export - # corrects it against the full model, which a targeted run does not - # write. - if ok and args.with_export and args.target: - ok, _ = run(truth_cmd[:-2], "2c generate truth (export model)") - results["generate_truth"] = ok - all_ok = all_ok and ok - else: - results["generate_truth"] = SKIPPED - - # Step 2d: Diff truth vs scraped - if args.with_truth or args.with_export: - diff_cmd = [sys.executable, "scripts/diff_truth.py", "--all"] - diff_cmd.extend(["--truth-dir", str(truth_dir)]) - if args.target: - diff_cmd.extend(["--target", args.target]) - ok, _ = run(diff_cmd, STEP_LABELS["diff_truth"]) - results["diff_truth"] = ok - all_ok = all_ok and ok - else: - results["diff_truth"] = SKIPPED - - # Step 2e: Export native formats - if args.with_export: - export_cmd = [ - sys.executable, - "scripts/export_native.py", - "--all", - # exports/ is committed with the code, like README.md and - # install/: written under the pack directory it went stale on - # every green run. - "--truth-dir", - str(Path(args.output_dir) / "truth"), - ] - # Seven of the formats carry code, so the export patches the - # platform's own file rather than regenerating it. Offline that - # file has to be in the cache already. - if not args.offline: - export_cmd.append("--fetch") - ok, _ = run(export_cmd, STEP_LABELS["export_native"]) - results["export_native"] = ok - all_ok = all_ok and ok - else: - results["export_native"] = SKIPPED - - return all_ok - - -def _parser() -> argparse.ArgumentParser: +def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description="Run the full retrobios pipeline") parser.add_argument( "--skip-packs", @@ -1113,555 +130,42 @@ def _parser() -> argparse.ArgumentParser: return parser -def _database_steps(results: dict) -> bool: - """Steps 0 to 1c: schemas, database, dump catalogs, romset recipes.""" - all_ok = True - # Step 0: the schema check PR validation runs. Without it a profile with - # `cores: [81]` unquoted passed the whole pipeline and failed CI on push. - # jsonschema is tooling only, so its absence skips the step. - if importlib.util.find_spec("jsonschema") is None: - # The skip names the install and what still runs the check, or a - # contributor read SKIPPED, then COMPLETE, and met the failure on push. - skip_notice( - "validate_schemas", - "jsonschema not installed. PR validation runs this check: " - 'pip install "jsonschema[format-nongpl]"', - ) - results["validate_schemas"] = SKIPPED - else: - ok, _ = run( - [sys.executable, "scripts/validate_schemas.py", "--source-only"], - STEP_LABELS["validate_schemas"], - ) - results["validate_schemas"] = ok - all_ok = all_ok and ok - - # Step 1: Generate database - ok, _ = run( - [ - sys.executable, - "scripts/generate_db.py", - "--force", - "--bios-dir", - "bios", - "--output", - "database.json", - ], - STEP_LABELS["generate_db"], - ) - results["generate_db"] = ok - if not ok: - print("\nDatabase generation failed, aborting.") - sys.exit(1) - - # Step 1b: Dump-catalog coverage (offline, reads provenance/ snapshots), - # and which missing dumps the collection already produces: recorded in - # derivable.json, which the site reads instead of rereading bios/. - ok, _ = run( - [sys.executable, "scripts/provenance_report.py", "--derive", - "--write-derivable", "derivable.json"], - STEP_LABELS["provenance"], - ) - results["provenance"] = ok - all_ok = all_ok and ok - - # Step 1c: Which emulator version each arcade archive corresponds to, and - # which pinned archive the collection could rebuild from ROMs it holds. - # Read-only: writing reconstructions is an explicit --write invocation. - ok, _ = run( - [sys.executable, "scripts/romset_recipes.py"], - STEP_LABELS["romset_recipes"], - ) - # A recipe for every archive database.json lists (recipes/archives.json): - # only an archive whose sha1 moved is read again, so the step costs the - # archives added since the last run. - captured, _ = run( - [sys.executable, "scripts/romset_recipes.py", "--capture"], - f"{STEP_LABELS['romset_recipes']} (archive recipes)", - ) - ok = ok and captured - results["romset_recipes"] = ok - all_ok = all_ok and ok - return all_ok - - -def _refresh_steps(args: argparse.Namespace, results: dict) -> bool: - """Steps 2 to 2b2: data directories, hash scrapers, release assets.""" - all_ok = True - # Step 2: Refresh data directories - if not args.offline: - ok, _ = run( - [sys.executable, "scripts/refresh_data_dirs.py"], - STEP_LABELS["refresh_data"], - ) - results["refresh_data"] = ok - all_ok = all_ok and ok - else: - skip_notice("refresh_data", "--offline") - results["refresh_data"] = SKIPPED - - # Step 2a: Refresh MAME BIOS hashes - if not args.offline: - ok, _ = run( - [sys.executable, "-m", "scripts.scraper.mame_hash_scraper"], - STEP_LABELS["mame_hashes"], - ) - results["mame_hashes"] = ok - all_ok = all_ok and ok - else: - skip_notice("mame_hashes", "--offline") - results["mame_hashes"] = SKIPPED - - # Step 2a2: Refresh FBNeo BIOS hashes - if not args.offline: - ok, _ = run( - [sys.executable, "-m", "scripts.scraper.fbneo_hash_scraper"], - STEP_LABELS["fbneo_hashes"], - ) - results["fbneo_hashes"] = ok - all_ok = all_ok and ok - else: - skip_notice("fbneo_hashes", "--offline") - results["fbneo_hashes"] = SKIPPED - - # Step 2b: Check buildbot system directory (non-blocking) - if args.check_buildbot and not args.offline: - ok, _ = run( - [sys.executable, "scripts/check_buildbot_system.py"], - STEP_LABELS["check_buildbot"], - ) - results["check_buildbot"] = ok - else: - if args.check_buildbot: - skip_notice("check_buildbot", "--offline") - results["check_buildbot"] = SKIPPED - - # Step 2b2: The release must serve the bytes the manifests describe. The - # installer compares Content-Length with the manifest size, so an asset - # uploaded before its local file was rebuilt fails every install of it. - if not args.offline: - ok, _ = run( - [sys.executable, "scripts/check_release_assets.py"], - STEP_LABELS["check_release_assets"], - ) - results["check_release_assets"] = ok - all_ok = all_ok and ok - else: - skip_notice("check_release_assets", "--offline") - results["check_release_assets"] = SKIPPED - return all_ok - - -def _verify_steps( - args: argparse.Namespace, results: dict, held: contextlib.ExitStack -) -> tuple[bool, str, 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. - """ - all_ok = True - # Every step from here reads the data directory trees: verify, the packs, - # the manifests and the integrity check. Held shared until the run ends, - # a refresh from another session waits instead of swapping a tree - # between the packs and the manifests, which would then describe two - # revisions of it. Taken after step 2, whose own refresh needs them - # 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 = Path(__file__).resolve().parent.parent / "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) - verify_cmd = [ - sys.executable, "scripts/verify.py", "--all", "--strict", - "--destinations", destinations_file, - ] - if args.target: - verify_cmd.extend(["--target", args.target]) - if args.offline: - # The packs of step 4 fetch no release asset: a missing one is - # missing on both sides. - verify_cmd.append("--offline") - ok, verify_output = run(verify_cmd, STEP_LABELS["verify"]) - results["verify"] = ok - all_ok = all_ok and ok - - # Step 3a: One content answering to two identities. Walks the tree rather - # than the index, which keeps a single path per content and therefore - # cannot see a file copied under another machine's name. - ok, _ = run( - [sys.executable, "scripts/identity.py", "--strict"], - STEP_LABELS["identity"], - ) - results["identity"] = ok - all_ok = all_ok and ok - - # Step 3b: Destinations both layers claim, and how each was settled. The - # ones the pack settles by itself must stay at zero cost. The rest name an - # upstream declaration no build can repair, so this reports and never gates. - # A crash is not a report: without --strict slots.py exits 0 on every - # conflict, so a non-zero code means it never finished reading. - # The same cores verify judged: without the target the arbitration of a - # targeted run judged cores the target does not ship. - slots_cmd = [sys.executable, "scripts/slots.py"] - if args.target: - slots_cmd.extend(["--target", args.target]) - ok, _ = run(slots_cmd, "3b slot arbitration") - results["slots"] = ok - all_ok &= ok - return all_ok, verify_output, destinations_file - - -def _purge_stale_packs(output_dir: str) -> None: - """Remove the packs of earlier builds from the output directory.""" - # Purge stale packs: leftover ZIPs from previous builds would be - # picked up by pack verification and shipped in releases. - out_dir = Path(output_dir) - if not out_dir.is_dir(): - return - try: - with artifact_lock(str(out_dir)): - stale = [ - p for p in out_dir.iterdir() - if p.is_file() and ( - p.suffix == ".zip" - or ".zip." in p.name - or p.name == "SHA256SUMS.txt" - ) - ] - for p in stale: - p.unlink() - if stale: - print(f"Purged {len(stale)} stale pack file(s) from {out_dir}/") - except ArtifactLockBusy as exc: - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - - -def _pack_command(args: argparse.Namespace) -> list[str]: - """The step 4 command: every platform's pack.""" - pack_cmd = [ - sys.executable, - "scripts/generate_pack.py", - "--all", - "--output-dir", - args.output_dir, - ] - if args.offline: - pack_cmd.append("--offline") - else: - # Step 2 refreshed the trees once: refreshing again here let the - # pack and the manifest describe two revisions of a moving tree. - pack_cmd.append("--no-refresh-data") - if args.target: - pack_cmd.extend(["--target", args.target]) - if args.source != "full": - pack_cmd.extend(["--source", args.source]) - if args.all_variants: - pack_cmd.append("--all-variants") - return pack_cmd - - -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. - """ - all_ok = True - # Step 4: Generate packs - pack_output = "" - if not args.skip_packs: - _purge_stale_packs(args.output_dir) - ok, pack_output = run(_pack_command(args), STEP_LABELS["generate_packs"]) - results["generate_packs"] = ok - all_ok = all_ok and ok - else: - skip_notice("generate_packs", "--skip-packs") - results["generate_packs"] = SKIPPED - - # Step 4b: Generate install manifests - if not args.skip_packs: - manifest_cmd = [ - sys.executable, - "scripts/generate_pack.py", - "--all", - "--manifest", - "--output-dir", - "install", - ] - if args.offline: - manifest_cmd.append("--offline") - else: - # Step 2 refreshed the trees once: refreshing again here let the - # pack and the manifest describe two revisions of a moving tree. - manifest_cmd.append("--no-refresh-data") - # No --target here: install/ holds the published lists, and every - # reader (site picker, release check, record) takes each file there - # as a whole platform. The per-target core lists are step 4c. - ok, _ = run(manifest_cmd, STEP_LABELS["generate_manifests"]) - results["generate_manifests"] = ok - all_ok = all_ok and ok - else: - skip_notice("generate_manifests", "--skip-packs") - results["generate_manifests"] = SKIPPED - - # Step 4c: Generate target manifests - if not args.skip_packs: - target_cmd = [ - sys.executable, - "scripts/generate_pack.py", - "--manifest-targets", - "--output-dir", - "install/targets", - ] - ok, _ = run(target_cmd, STEP_LABELS["generate_target_manifests"]) - results["generate_target_manifests"] = ok - all_ok = all_ok and ok - else: - skip_notice("generate_target_manifests", "--skip-packs") - results["generate_target_manifests"] = SKIPPED - return all_ok, pack_output - - -def _index_steps(results: dict) -> bool: - """Steps 4d and 4e: bundled-only copies, the games index.""" - all_ok = True - # Step 4d: A collected copy that only an emulator's own install provides. - # Packs leave such files out, so a copy nothing else asks for is weight - # the collection carries for nobody. Read after the manifests, which say - # what an installation ships. - ok, _ = run( - [sys.executable, "scripts/bundled_only.py", "--strict"], - STEP_LABELS["bundled_only"], - ) - results["bundled_only"] = ok - all_ok &= ok - - # Step 4e: What the installer reads for the games on a card: rom folders, - # game catalogs, header and region rules, arcade parents, and the - # fallback sets, which read the install lists. Runs under --skip-packs - # too, on the committed lists, so a rescrape of the rom folders or a DAT - # import reaches install/games/ in the same run. - ok, _ = run( - [sys.executable, "scripts/generate_games_index.py", "--quiet"], - STEP_LABELS["games_index"], - ) - results["games_index"] = ok - all_ok &= ok - return all_ok - - -def _check_steps( - args: argparse.Namespace, - results: dict, - *, - pack_output: str, - verify_output: str, - destinations_file: str, -) -> bool: - """Steps 5 and 6: verify against the packs, then the packs' integrity.""" - all_ok = True - # Step 5: Consistency check. verify describes the full pack, and a run that - # 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: - skip_notice("consistency", "no full pack built") - results["consistency"] = SKIPPED - elif pack_output and verify_output: - ok = check_consistency( - verify_output, pack_output, - release_pack_keys(), - ) - # Counts can agree while the paths differ, both ways at once. - ok = check_pack_destinations(destinations_file, pack_output) 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 - print( - f"--- {step_title(STEP_LABELS['consistency'])}, counts and paths: " - f"{'OK' if ok else 'FAILED'} ---" - ) - results["consistency"] = ok - all_ok = all_ok and ok - else: - skip_notice("consistency") - results["consistency"] = SKIPPED - - # Step 6: Pack integrity (extract + hash verification) - if not args.skip_packs and not full_pack_built: - # The check reads the full pack's name, while a reduced pack holds fewer - # files than the platform declares by design. - skip_notice("pack_integrity", "no full pack built") - results["pack_integrity"] = SKIPPED - elif not args.skip_packs: - ok, _ = run(integrity_command(args), STEP_LABELS["pack_integrity"]) - results["pack_integrity"] = ok - all_ok = all_ok and ok - else: - skip_notice("pack_integrity", "--skip-packs") - results["pack_integrity"] = SKIPPED - return all_ok - - -def _docs_steps(args: argparse.Namespace, results: dict) -> bool: - """Steps 7 to 8b: README and pages, site pages, the rendered site.""" - all_ok = True - # Step 7: Generate README - if not args.skip_docs: - ok, _ = run( - [ - sys.executable, - "scripts/generate_readme.py", - "--db", - "database.json", - "--platforms-dir", - "platforms", - ], - STEP_LABELS["generate_readme"], - ) - # The run samples of wiki/installer.md, printed by install.py from - # the manifests step 4b just wrote. - doc_ok, _ = run([sys.executable, "scripts/generate_installer_doc.py"], - "7 generate installer page") - # The verify excerpt of wiki/reading-reports.md, from this run's data. - excerpt_ok, _ = run([sys.executable, "scripts/generate_report_excerpt.py"], - "7 generate report excerpt") - ok = ok and doc_ok and excerpt_ok - results["generate_readme"] = ok - all_ok = all_ok and ok - else: - skip_notice("generate_readme", "--skip-docs") - results["generate_readme"] = SKIPPED - - # Step 8: Generate site pages - if not args.skip_docs: - ok, _ = run( - [sys.executable, "scripts/generate_site.py"], - STEP_LABELS["generate_site"], - ) - results["generate_site"] = ok - all_ok = all_ok and ok - else: - skip_notice("generate_site", "--skip-docs") - results["generate_site"] = SKIPPED - - # Step 8b: the render the site deploy runs. Generating the pages without - # rendering them let 20 pages with duplicate ids through to CI. - if args.skip_docs: - skip_notice("render_site", "--skip-docs") - results["render_site"] = SKIPPED - elif shutil.which("npm") is None or not Path("website/node_modules").is_dir(): - skip_notice("render_site", "Node not set up: npm ci --prefix website") - results["render_site"] = SKIPPED - else: - # Starlight's link check runs inside the build and fails it. - ok, _ = run(["npm", "run", "build", "--prefix", "website"], STEP_LABELS["render_site"]) - if ok: - ok, _ = run([sys.executable, "scripts/validate_site.py", "--site-dir", "website/dist"], - "8b validate site") - results["render_site"] = ok - all_ok = all_ok and ok - return all_ok - - -def _print_summary(results: StepResults, total_start: float, all_ok: bool) -> None: - """The table of every step's outcome and duration, then the verdict.""" - total_elapsed = time.monotonic() - total_start - print(f"\n{'=' * 60}") - warned = [] - for step, outcome in results.items(): - # The number finds the step's lines in the log, the key is the - # name a caller reading the results knows it by. - number = step_number(step) - if outcome is SKIPPED: - print(f" {number:<4} {step:.<40} SKIPPED") - continue - label = "OK" if outcome else "FAILED" - if not outcome and step in NON_BLOCKING: - # Printed FAILED right above "Pipeline COMPLETE", it read as a - # contradiction: the step reports, it does not stop the run. - label = "WARN" - warned.append(step) - print(f" {number:<4} {step:.<40} {label:<7}{results.seconds[step]:>8.1f}s") - print(f" {'':<4} {'total':.<40} {'':<7}{total_elapsed:>8.1f}s") - print(f"{'=' * 60}") - print(f" Pipeline {'COMPLETE' if all_ok else 'FINISHED WITH ERRORS'}") - if warned: - print(f" {', '.join(warned)} reported a difference, which does not fail the run") - print(f"{'=' * 60}") - - def main() -> None: - parser = _parser() + parser = build_parser() args = parser.parse_args() - _refuse_unapplied_flags(parser, args) - _refuse_offline_without_caches(parser, args) - _refuse_offline_export_without_originals(parser, args) + refuse_unapplied_flags(parser, args) + refuse_offline_without_caches(parser, args) + refuse_offline_export_without_originals(parser, args) if not args.offline: # Read once and put in the environment every step inherits: the # scrapers and refresh_data_dirs went anonymous unless the user had # exported GITHUB_TOKEN by hand, though gh was logged in. github_token() - args.output_dir = _output_dir(args.output_dir) - held = _hold_outputs(args) + args.output_dir = pack_output_dir(args.output_dir) + held = hold_outputs(args) total_start = time.monotonic() results = StepResults(total_start) - all_ok = _database_steps(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) + all_ok = database_steps(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) all_ok = all_ok and ok - ok, pack_output = _pack_steps(args, results) + ok, pack_output = pack_steps(args, results) all_ok = all_ok and ok - all_ok = _index_steps(results) and all_ok - all_ok = _check_steps( + all_ok = index_steps(results) and all_ok + all_ok = check_steps( args, results, pack_output=pack_output, verify_output=verify_output, destinations_file=destinations_file, ) and all_ok - all_ok = _docs_steps(args, results) and all_ok + all_ok = docs_steps(args, results) and all_ok - _print_summary(results, total_start, all_ok) + print_summary(results, total_start, all_ok) held.close() sys.exit(0 if all_ok else 1) -def _hold_outputs(args: argparse.Namespace) -> contextlib.ExitStack: - """Take every lock the run holds until it exits, or exit when one is busy.""" - # A second run on the same output directory is refused before any work: - # the database rebuild alone takes minutes, and the reader holding the - # directory would otherwise see the answer only after all of it. The - # hold lasts until this process exits: taken step by step, it let another - # run purge the packs between the build and the integrity check, which - # then reported every platform SKIP and passed. - # database.json, install/, README.md, CONTRIBUTING.md and website/ sit at - # fixed paths (artifacts.REPOSITORY_OUTPUTS), so - # every run holds them too: a run on a scratch --output-dir otherwise - # rewrote them beside the run on dist/. - held = contextlib.ExitStack() - try: - root = str(Path(__file__).resolve().parent.parent) - held.enter_context(hold_repository_outputs(root)) - # Its steps write database.json, install/ and README.md themselves, - # and take the same lock to do so. - held.enter_context(publish_hold(root)) - if not args.skip_packs: - held.enter_context(hold_artifact_lock(args.output_dir)) - except ArtifactLockBusy as exc: - held.close() - print(f"ERROR: {exc}", file=sys.stderr) - sys.exit(1) - return held - - if __name__ == "__main__": from core.cli import run_cli diff --git a/scripts/sitegen/diagrams.py b/scripts/sitegen/diagrams.py index df8a4a866..56931f923 100644 --- a/scripts/sitegen/diagrams.py +++ b/scripts/sitegen/diagrams.py @@ -595,8 +595,8 @@ def _minui_narrow() -> tuple[float, float, list[str]]: def _pipeline_boxes() -> list[Box]: - """The steps pipeline.py runs, read from its STEP_LABELS literal.""" - tree = ast.parse((REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8")) + """The steps pipeline.py runs, read from the STEP_LABELS literal of its step list.""" + tree = ast.parse((REPO_ROOT / "scripts" / "orchestrate" / "labels.py").read_text(encoding="utf-8")) for node in ast.walk(tree): if isinstance(node, ast.Assign): target: ast.expr = node.targets[0] @@ -609,7 +609,7 @@ def _pipeline_boxes() -> list[Box]: labels = ast.literal_eval(value) break else: - raise RuntimeError("STEP_LABELS not found in scripts/pipeline.py") + raise RuntimeError("STEP_LABELS not found in scripts/orchestrate/labels.py") boxes = [] for label in labels.values(): number, title = label.split(" ", 1) @@ -709,7 +709,7 @@ def _figures() -> dict[str, Figure]: "Pipeline steps", "The pipeline runs its steps in order: " + ", ".join(f"{b.number} {b.title}" for b in _pipeline_boxes()) + ".", - "Read from the step list in scripts/pipeline.py, numbered as the run prints them.", + "Read from the step list in scripts/orchestrate/labels.py, numbered as the run prints them.", lambda: grid(_pipeline_boxes(), 4, WIDE), lambda: grid(_pipeline_boxes(), 2, NARROW), ), diff --git a/tests/sources.py b/tests/sources.py index 48cf31c7a..5fed8a9da 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -116,6 +116,12 @@ COMMANDS = { "freshness/catalogs.py", "freshness/ci.py", "freshness/pinbuilds.py", "freshness/profiles.py", "freshness/report.py", ), + "pipeline.py": ( + "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/emulatorpacks.py", "orchestrate/narrowed.py", "orchestrate/splitcheck.py", } diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index 3adb3273a..48c0bcdb2 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -26,6 +26,7 @@ from core.artifacts import ( publish_hold, ) from tests.scratchtree import scratch_checkout +from tests.sources import script_source from core import artifacts from unittest import mock @@ -359,7 +360,7 @@ class HeldLockTest(unittest.TestCase): self.assertEqual(self._child_locks(dict(os.environ)).returncode, 0) def test_the_pipeline_holds_its_output_for_the_run(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn("hold_artifact_lock(args.output_dir)", source) @@ -369,7 +370,7 @@ class PipelineHoldsTheDataTrees(unittest.TestCase): and the manifests, which then described two revisions of it.""" def test_the_trees_are_held_after_the_refresh_and_before_verify(self): - source = (Path(__file__).resolve().parents[1] / "scripts" / "pipeline.py").read_text() + source = script_source("pipeline.py") refresh = source.index('"scripts/refresh_data_dirs.py"') hold = source.index("hold_data_dirs(held,") verify = source.index('"scripts/verify.py", "--all"') diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 1ba3ac55b..a01e85c30 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -32,6 +32,7 @@ except ImportError: import install from packs import verdicts from scripts import pipeline +from orchestrate import checks, consistency, reports, results, runner from scripts.resolve import regionaudit, regions from scripts.resolve.localfile import resolve_local_file from scripts.core.ziptools import safe_extract_zip @@ -1188,7 +1189,7 @@ class PipelineRegressions(unittest.TestCase): def command(**flags) -> list[str]: base = {"output_dir": "dist", "target": None, "all_variants": False} - return pipeline.integrity_command(argparse.Namespace(**{**base, **flags})) + return checks.integrity_command(argparse.Namespace(**{**base, **flags})) self.assertIn("--all-variants", command(all_variants=True)) self.assertNotIn("--all-variants", command()) @@ -1201,12 +1202,12 @@ class PipelineRegressions(unittest.TestCase): " 3 files packed (2 baseline + 1 from cores), 2/2 files OK", ] ) - self.assertEqual(pipeline.parse_pack_counts(output), {"RetroArch": (2, 2)}) + self.assertEqual(reports.parse_pack_counts(output), {"RetroArch": (2, 2)}) def test_missing_pack_is_a_consistency_failure(self): verify = "RetroArch: 2/2 OK" with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, "")) + self.assertFalse(consistency.check_consistency(verify, "")) def test_display_name_matches_compact_registry_id(self): verify = "MiSTer FPGA: 65/65 OK [md5]" @@ -1218,7 +1219,7 @@ class PipelineRegressions(unittest.TestCase): ] ) with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(pipeline.check_consistency(verify, pack)) + self.assertTrue(consistency.check_consistency(verify, pack)) def test_the_cores_share_is_compared_too(self): """RomM passed this step while verify counted 412 core files and game @@ -1234,9 +1235,9 @@ class PipelineRegressions(unittest.TestCase): "383/383 files OK [md5]", ]) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, pack)) + 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(pipeline.check_consistency(agreed, pack)) + self.assertTrue(consistency.check_consistency(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 @@ -1251,8 +1252,8 @@ class PipelineRegressions(unittest.TestCase): ] ) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, pack)) - self.assertEqual(pipeline.parse_pack_exclusions(pack), {"RetroArch": 1}) + 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]" @@ -1264,7 +1265,7 @@ class PipelineRegressions(unittest.TestCase): ] ) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, pack)) + self.assertFalse(consistency.check_consistency(verify, pack)) def test_a_pack_more_optimistic_than_verify_is_a_failure(self): """The invariant held one way only: a pack counting more OK files @@ -1278,13 +1279,13 @@ class PipelineRegressions(unittest.TestCase): ] ) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, pack)) + self.assertFalse(consistency.check_consistency(verify, pack)) def test_nothing_parsed_is_not_consistent(self): """A changed output format must not pass with no platform compared.""" with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency("RetroArch = 2/2 OK", "")) - self.assertFalse(pipeline.check_consistency("", "")) + self.assertFalse(consistency.check_consistency("RetroArch = 2/2 OK", "")) + self.assertFalse(consistency.check_consistency("", "")) def test_pack_without_verify_result_is_a_failure(self): verify = "RetroArch: 2/2 OK" @@ -1297,7 +1298,7 @@ class PipelineRegressions(unittest.TestCase): ] ) with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(pipeline.check_consistency(verify, pack)) + self.assertFalse(consistency.check_consistency(verify, pack)) def test_only_the_full_variant_feeds_the_comparison(self): """--all-variants printed six packs under one label, and the last won.""" @@ -1307,7 +1308,7 @@ class PipelineRegressions(unittest.TestCase): "Generating pack for RetroArch [source=platform, required]...", " b.zip: 5 files packed (5 baseline + 0 from cores), 530/530 files OK", ]) - self.assertEqual(pipeline.parse_pack_counts(output), {"RetroArch": (535, 535)}) + 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.""" @@ -1317,10 +1318,10 @@ class PipelineRegressions(unittest.TestCase): "Generating pack for Batocera [source=truth, required]...", " b.zip: 2 files packed (0 baseline + 2 from cores), 2/2 files OK", ]) - self.assertEqual(pipeline.parse_pack_exclusions(output), {"Batocera": 3}) + self.assertEqual(reports.parse_pack_exclusions(output), {"Batocera": 3}) def test_slot_step_reaches_the_summary(self): - source = Path(pipeline.__file__).read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn('results["slots"] = ok', source) def test_every_refresh_failure_reaches_pipeline_exit_status(self): @@ -1336,7 +1337,7 @@ class PipelineRegressions(unittest.TestCase): argv = ["pipeline.py", "--skip-packs", "--skip-docs"] with ( mock.patch.object(sys, "argv", argv), - mock.patch.object(pipeline, "run", side_effect=fake_run), + mock.patch.object(runner, "run", side_effect=fake_run), contextlib.redirect_stdout(io.StringIO()), self.assertRaises(SystemExit) as raised, ): @@ -1357,8 +1358,8 @@ class PipelineRegressions(unittest.TestCase): # The originals the offline export patches are not cached in a # checkout: the run would be refused before any step. with mock.patch.object(sys, "argv", argv), mock.patch.object( - pipeline, "run", side_effect=fake_run - ), mock.patch.object(pipeline, "_refuse_offline_export_without_originals"), \ + runner, "run", side_effect=fake_run + ), mock.patch.object(pipeline, "refuse_offline_export_without_originals"), \ contextlib.redirect_stdout(io.StringIO()), contextlib.suppress(SystemExit): pipeline.main() truth_runs = [c for c in commands if "scripts/generate_truth.py" in c] @@ -2845,7 +2846,7 @@ class ReleaseAssetsMatchTheCollection(unittest.TestCase): return True, "" argv = ["pipeline.py", "--skip-packs", "--skip-docs", *flags] - with mock.patch.object(pipeline, "run", record), \ + with mock.patch.object(runner, "run", record), \ mock.patch.object(sys, "argv", argv), \ contextlib.redirect_stdout(io.StringIO()) as out, \ self.assertRaises(SystemExit) as done: @@ -2882,7 +2883,7 @@ class OneRefreshPerOnlineRun(unittest.TestCase): # A scratch output directory: step 4 purges the ZIPs of the one it # is given, and this run must never touch dist/. with tempfile.TemporaryDirectory() as out, \ - mock.patch.object(pipeline, "run", record), \ + mock.patch.object(runner, "run", record), \ mock.patch.object( sys, "argv", ["pipeline.py", "--skip-docs", "--output-dir", out] ), \ @@ -3086,14 +3087,12 @@ class PipelineReportsWhatItDid(unittest.TestCase): """ def test_a_skipped_step_is_not_reported_as_done(self): - import pipeline - - self.assertTrue(bool(pipeline.SKIPPED), "a skip must not fail the run") - self.assertEqual(repr(pipeline.SKIPPED), "SKIPPED") - self.assertIsNot(pipeline.SKIPPED, True) + self.assertTrue(bool(results.SKIPPED), "a skip must not fail the run") + self.assertEqual(repr(results.SKIPPED), "SKIPPED") + self.assertIsNot(results.SKIPPED, True) def test_every_skip_branch_uses_the_sentinel(self): - source = (ROOT / "scripts" / "pipeline.py").read_text() + source = script_source("pipeline.py") stale = re.findall(r'results\["(\w+)"\] = True', source) self.assertEqual(stale, [], f"steps still claiming OK when skipped: {stale}") @@ -4047,7 +4046,7 @@ class PipelineStepsSpeakAsTheyGo(unittest.TestCase): "print('two', file=sys.stderr, flush=True); print('three')") echoed = io.StringIO() with contextlib.redirect_stdout(echoed): - ok, output = pipeline.run([sys.executable, "-c", script], "probe") + ok, output = runner.run([sys.executable, "-c", script], "probe") self.assertTrue(ok) self.assertEqual(output, "one\ntwo\nthree\n") text = echoed.getvalue() @@ -4841,7 +4840,7 @@ class ThePipelineTableNamesEveryStep(unittest.TestCase): def test_every_labelled_step_is_documented(self): labels = set(re.findall( - r'"(\d[a-z]?\d?)(?:/8)? [a-z]', (ROOT / "scripts" / "pipeline.py").read_text() + r'"(\d[a-z]?\d?)(?:/8)? [a-z]', script_source("pipeline.py") )) doc = (ROOT / "wiki" / "tools.md").read_text() documented = set(re.findall(r"^\| (\d[a-z]?\d?)(?:/8)? \|", doc, re.MULTILINE)) @@ -5379,9 +5378,9 @@ class PipelineDocstringNamesThePrintedSteps(unittest.TestCase): source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") doc = ast.get_docstring(ast.parse(source)) listed = set(re.findall(r"^ (\d[a-z0-9]*)\s{2,}", doc, re.M)) - import pipeline + from orchestrate.labels import STEP_LABELS, step_number - printed = {pipeline.step_number(key) for key in pipeline.STEP_LABELS} + printed = {step_number(key) for key in STEP_LABELS} self.assertEqual(listed, printed) @@ -6377,14 +6376,14 @@ class ThePipelineSummaryTimesEachStep(unittest.TestCase): from unittest import mock clock = iter([10.0, 12.5, 12.5, 20.0]) - with mock.patch.object(pipeline.time, "monotonic", lambda: next(clock)): - results = pipeline.StepResults(pipeline.time.monotonic()) - results["generate_db"] = True - results["refresh_data"] = pipeline.SKIPPED - results["verify"] = True - self.assertEqual(results.seconds, {"generate_db": 2.5, "refresh_data": 0.0, "verify": 7.5}) - self.assertEqual(dict(results), {"generate_db": True, "refresh_data": pipeline.SKIPPED, - "verify": True}) + with mock.patch.object(results.time, "monotonic", lambda: next(clock)): + outcomes = results.StepResults(results.time.monotonic()) + outcomes["generate_db"] = True + outcomes["refresh_data"] = results.SKIPPED + outcomes["verify"] = True + self.assertEqual(outcomes.seconds, {"generate_db": 2.5, "refresh_data": 0.0, "verify": 7.5}) + self.assertEqual(dict(outcomes), {"generate_db": True, "refresh_data": results.SKIPPED, + "verify": True}) class StrictFailsOnMissingOnly(unittest.TestCase): @@ -7044,9 +7043,7 @@ class AStepThatCannotFailTheRunIsNotShownFailed(unittest.TestCase): column by fourteen characters.""" def test_every_step_outside_all_ok_is_declared_non_blocking(self): - import pipeline - - lines = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8").splitlines() + lines = script_source("pipeline.py").splitlines() loose = set() for number, line in enumerate(lines): found = re.search(r'results\["(\w+)"\] = ok$', line.strip()) @@ -7055,14 +7052,14 @@ class AStepThatCannotFailTheRunIsNotShownFailed(unittest.TestCase): after = " ".join(lines[number + 1:number + 4]) if "all_ok" not in after and "sys.exit" not in after: loose.add(found.group(1)) - self.assertEqual(loose, set(pipeline.NON_BLOCKING)) + self.assertEqual(loose, set(results.NON_BLOCKING)) def test_the_total_sits_under_the_durations(self): step = f" {'x':.<40} {'OK':<7}{1.0:>8.1f}s" total = f" {'total':.<40} {'':<7}{12.5:>8.1f}s" self.assertEqual(len(step), len(total)) self.assertIn("{'':<7}{total_elapsed:>8.1f}s", - (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8")) + script_source("pipeline.py")) class AHashConflictIsReportedOnce(unittest.TestCase): @@ -7093,7 +7090,7 @@ class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase): workflow = (ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") command = re.search(r"python (scripts/validate_schemas\.py[^\n]*)", workflow).group(1) script, *flags = command.split() - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn(f'"{script}"', source) for flag in flags: self.assertIn(f'"{flag}"', source) @@ -7102,7 +7099,7 @@ class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase): """The pipeline generated pages without rendering them: 20 pages with duplicate ids passed it and failed the deploy.""" workflow = (ROOT / ".github" / "workflows" / "deploy-site.yml").read_text(encoding="utf-8") - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn("npm run build --prefix website", workflow) self.assertIn('["npm", "run", "build", "--prefix", "website"]', source) self.assertIn("scripts/validate_site.py", workflow) @@ -7455,14 +7452,14 @@ class PipelineOutputDirIsTheOneItWrites(unittest.TestCase): previous = os.getcwd() self.addCleanup(os.chdir, previous) os.chdir(ROOT / "scripts") - self.assertEqual(pipeline._output_dir(None), str(ROOT / "dist")) - self.assertEqual(pipeline._output_dir("out"), str(ROOT / "scripts" / "out")) + self.assertEqual(runner.pack_output_dir(None), str(ROOT / "dist")) + self.assertEqual(runner.pack_output_dir("out"), str(ROOT / "scripts" / "out")) def test_main_resolves_it_before_the_lock(self): - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") body = source[source.index("def main("):] self.assertLess( - body.index("args.output_dir = _output_dir(args.output_dir)"), + body.index("args.output_dir = pack_output_dir(args.output_dir)"), body.index("hold_artifact_lock(args.output_dir)"), ) @@ -7515,11 +7512,11 @@ class SkipPacksHelpSaysWhatRuns(unittest.TestCase): self.assertNotIn("docs/", text) def test_every_step_it_names_is_one_it_skips(self): - import pipeline + from orchestrate.labels import step_number - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") keys = re.findall(r'skip_notice\("(\w+)", "--skip-packs"\)', source) - skipped = {pipeline.step_number(key) for key in keys} + skipped = {step_number(key) for key in keys} self.assertEqual(skipped, {"4", "4b", "4c", "6"}) @@ -7767,7 +7764,7 @@ class PipelineChildrenSkipNodeCompileCache(unittest.TestCase): every child the pipeline starts carries NODE_DISABLE_COMPILE_CACHE.""" def test_the_run_helper_sets_it(self): - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn('"NODE_DISABLE_COMPILE_CACHE": "1"', source) diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index ebcc7594d..8778565af 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -303,7 +303,7 @@ class ReleaseCommitCarriesTheManifests(unittest.TestCase): release pipeline regenerates: v2026.10.10 added three by hand.""" def test_the_commit_step_adds_what_the_pipeline_rewrites(self): - pipeline = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + pipeline = script_source("pipeline.py") self.assertIn('"--manifest"', pipeline) block = _section(_page("release-process.md"), "Cutting a release") add = next(line for line in block.splitlines() if line.startswith("git add ")) @@ -1174,7 +1174,7 @@ class ListsFollowTheCode(unittest.TestCase): self.assertEqual({row[0].strip("`") for row in _table_rows(section)}, used) def test_pipeline_steps(self): - from pipeline import STEP_LABELS + from orchestrate.labels import STEP_LABELS section = _section(_page("adding-a-platform.md"), "Step 8: Validate the full pipeline") listed = re.findall(r"^- (\d\w*) ", section, re.M) @@ -1380,9 +1380,9 @@ class PipelineStepsMatchTheRun(unittest.TestCase): @staticmethod def labels() -> list[str]: - import pipeline + from orchestrate.labels import STEP_LABELS, step_number - return [pipeline.step_number(key) for key in pipeline.STEP_LABELS] + return [step_number(key) for key in STEP_LABELS] @staticmethod def cited(text: str) -> list[str]: diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 809dec4d8..da80fb234 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -1418,10 +1418,10 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - import pipeline + from orchestrate import compare from model.profiles import load_emulator_profiles - cls.pipeline = pipeline + cls.compare = compare cls.db = json.loads(db_path.read_text(encoding="utf-8")) cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) @@ -1460,11 +1460,11 @@ class ANativeNameSelectsOneSetEverywhere(unittest.TestCase): ) self.assertEqual(report["systems"], [system_id]) credited = set(report["pack_destinations"]) - trees = self.pipeline._tree_members(platform, str(REPO_ROOT / "platforms")) + trees = self.compare.tree_members(platform, str(REPO_ROOT / "platforms")) members = self._packed(platform, chosen) written = { name for name, size in members.items() - if not self.pipeline._PACK_NOTES.search(name) + if not self.compare.PACK_NOTES.search(name) and not (trees.get(name) == size and name not in credited) } self.assertTrue(written) diff --git a/tests/test_layers.py b/tests/test_layers.py index 4235d24f2..d6bac726c 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -51,6 +51,9 @@ SIBLING_IMPORTS: dict[str, frozenset[str]] = { # native export, the data directory refresh, the installer pins, the # site's source trees and profile_sync's report. "freshness": frozenset({"scraper", "exporter", "packs", "installer_build", "sitegen", "profiling"}), + # Step 5 builds the packs in memory, and the offline export refusal asks + # the exporters which ones patch a cached original. + "orchestrate": frozenset({"packs", "exporter"}), } # Top-level files that stay whole at their path although packages import them: diff --git a/tests/test_pack_destinations.py b/tests/test_pack_destinations.py index ddd3bd4f1..a493b534b 100644 --- a/tests/test_pack_destinations.py +++ b/tests/test_pack_destinations.py @@ -24,6 +24,8 @@ from pathlib import Path import yaml +from tests.sources import script_source + REPO_ROOT = Path(__file__).resolve().parents[1] @@ -173,12 +175,12 @@ class EveryNarrowingIsCompared(unittest.TestCase): def test_each_dimension_of_the_name_builder_is_accounted_for(self): import inspect - import pipeline + from orchestrate import narrowed from packs.naming import pack_narrowings dimensions = set(inspect.signature(pack_narrowings).parameters) - compared = set(pipeline.NARROWINGS_COMPARED) - exempt = set(pipeline.NARROWINGS_NOT_COMPARED) + compared = set(narrowed.NARROWINGS_COMPARED) + exempt = set(narrowed.NARROWINGS_NOT_COMPARED) self.assertFalse(compared & exempt) self.assertEqual(dimensions, compared | exempt, "compare the new narrowing in check_narrowed_packs, " @@ -190,25 +192,25 @@ class EveryNarrowingIsCompared(unittest.TestCase): it describes the platform packs only.""" import inspect - import pipeline + from orchestrate import emulatorpacks from packs.naming import pack_narrowings from packs.emulatorpack import generate_emulator_pack taken = (set(inspect.signature(pack_narrowings).parameters) & set(inspect.signature(generate_emulator_pack).parameters)) - self.assertEqual(taken, set(pipeline.EMULATOR_NARROWINGS_COMPARED)) + self.assertEqual(taken, set(emulatorpacks.EMULATOR_NARROWINGS_COMPARED)) profile = {"files": [{"name": "a.bin", "region": "japan"}, {"name": "b.bin", "region": ["north-america", "europe"]}]} - used = {key for _label, narrowing in pipeline.emulator_variants([profile], False) + used = {key for _label, narrowing in emulatorpacks.emulator_variants([profile], False) for key in narrowing} # standalone is the loop around the variants, both builds of each profile. - self.assertEqual(used, pipeline.EMULATOR_NARROWINGS_COMPARED - {"standalone"}) - regions = [n["regions"] for _l, n in pipeline.emulator_variants([profile], True) + self.assertEqual(used, emulatorpacks.EMULATOR_NARROWINGS_COMPARED - {"standalone"}) + regions = [n["regions"] for _l, n in emulatorpacks.emulator_variants([profile], True) if "regions" in n] self.assertEqual(len(regions), 3) def test_the_variants_reach_every_compared_dimension(self): - import pipeline + from orchestrate import narrowed from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -217,23 +219,23 @@ class EveryNarrowingIsCompared(unittest.TestCase): profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) for full in (False, True): with self.subTest(full=full): - variants = pipeline.narrowed_variants( + variants = narrowed.narrowed_variants( "retroarch", config, profiles, platforms, full, ) used = {key for _label, narrowing in variants for key in narrowing} - self.assertEqual(used, pipeline.NARROWINGS_COMPARED | {"system_filter"}) + self.assertEqual(used, narrowed.NARROWINGS_COMPARED | {"system_filter"}) systems = [n for _l, n in variants if "system_filter" in n] self.assertEqual(len(systems), len(config["systems"])) def test_the_sample_takes_both_ends_and_the_middle(self): - import pipeline + from orchestrate.narrowed import matrix_coverage - self.assertEqual(list(pipeline._matrix_coverage(False, 2)), [0, 1]) - self.assertEqual(pipeline._matrix_coverage(False, 11), [0, 5, 10]) - self.assertEqual(list(pipeline._matrix_coverage(True, 11)), list(range(11))) + self.assertEqual(list(matrix_coverage(False, 2)), [0, 1]) + self.assertEqual(matrix_coverage(False, 11), [0, 5, 10]) + self.assertEqual(list(matrix_coverage(True, 11)), list(range(11))) def test_the_run_compares_them(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn("ok = check_narrowed_packs(", source) @@ -241,7 +243,7 @@ class ThePipelineComparesPaths(unittest.TestCase): """Equal counts, other paths: the comparison fails and names both sides.""" def test_a_swap_at_equal_counts_fails(self): - import pipeline + from orchestrate.consistency import check_pack_destinations root = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, root, True) @@ -260,7 +262,7 @@ class ThePipelineComparesPaths(unittest.TestCase): os.chdir(REPO_ROOT) try: with mock_tree_members(), contextlib.redirect_stdout(io.StringIO()) as out: - ok = pipeline.check_pack_destinations(str(destinations), output) + ok = check_pack_destinations(str(destinations), output) finally: os.chdir(previous) self.assertIs(ok, expected, out.getvalue()) @@ -269,7 +271,7 @@ class ThePipelineComparesPaths(unittest.TestCase): self.assertIn("pack only 1: b.bin", out.getvalue()) def test_the_run_compares_every_emulator_pack(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn("ok = check_pack_destinations(destinations_file, pack_output) and ok", source) self.assertIn("ok = check_emulator_packs(full=args.full_narrowings) and ok", source) self.assertIn('"--destinations", destinations_file', source) @@ -277,14 +279,14 @@ class ThePipelineComparesPaths(unittest.TestCase): @contextlib.contextmanager def mock_tree_members(): - import pipeline + from orchestrate import compare - original = pipeline._tree_members - pipeline._tree_members = lambda *_args: {} + original = compare.tree_members + compare.tree_members = lambda *_args: {} try: yield finally: - pipeline._tree_members = original + compare.tree_members = original class EveryEmulatorPackMatchesItsReport(unittest.TestCase): @@ -293,13 +295,13 @@ class EveryEmulatorPackMatchesItsReport(unittest.TestCase): def test_the_paths_agree(self): if not (REPO_ROOT / "database.json").is_file(): self.skipTest("database.json is not built") - import pipeline + from orchestrate.emulatorpacks import check_emulator_packs previous = os.getcwd() os.chdir(REPO_ROOT) try: with contextlib.redirect_stdout(io.StringIO()) as out: - ok = pipeline.check_emulator_packs() + ok = check_emulator_packs() finally: os.chdir(previous) self.assertTrue(ok, out.getvalue()) diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index 17458b82b..694b0e5bc 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -180,27 +180,29 @@ class APlatformWithoutAPackFailsNoCheck(unittest.TestCase): ) def test_the_consistency_step_skips_a_setup_served_by_the_installer(self): - import pipeline + from orchestrate.consistency import check_consistency + from orchestrate.reports import release_pack_keys with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertTrue(pipeline.check_consistency( - self.VERIFY, self.PACK, pipeline.release_pack_keys(PLATFORMS))) + self.assertTrue(check_consistency( + self.VERIFY, self.PACK, release_pack_keys(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): - import pipeline + from orchestrate.consistency import check_consistency + from orchestrate.reports import release_pack_keys verify = self.VERIFY + "Batocera: 3/3 OK [md5]\n" with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(pipeline.check_consistency( - verify, self.PACK, pipeline.release_pack_keys(PLATFORMS))) + self.assertFalse(check_consistency( + verify, self.PACK, release_pack_keys(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", out.getvalue()) def test_the_pipeline_passes_the_release_platforms(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertIn("release_pack_keys()", source) def test_verify_packs_sweeps_the_release_packs_only(self): diff --git a/tests/test_site_images.py b/tests/test_site_images.py index a64e6b755..dfb3b8d41 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -124,7 +124,7 @@ class DiagramsMatchTheData(unittest.TestCase): self.assertTrue(diagrams.minui_files().get(tag)) def test_the_pipeline_drawing_is_the_step_list(self): - from pipeline import STEP_LABELS + from orchestrate.labels import STEP_LABELS numbers = [box.number for box in diagrams._pipeline_boxes()] self.assertEqual(numbers, [label.split(" ", 1)[0] for label in STEP_LABELS.values()]) diff --git a/tests/test_slots.py b/tests/test_slots.py index bdf3dd88b..1145041f0 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -17,6 +17,7 @@ from packs import slots as packs_slots from resolve import collisions as resolve_collisions from packs.slots import Claim, Conflict, arbitrate from slots import format_decision +from tests.sources import script_source def _db(entries: dict[str, dict]) -> dict: @@ -942,7 +943,7 @@ class SlotsJudgeWhatVerifyJudged(unittest.TestCase): the target does not ship.""" def test_the_pipeline_passes_the_target(self): - source = (Path(__file__).resolve().parents[1] / "scripts" / "pipeline.py").read_text() + source = script_source("pipeline.py") step = source[source.index('slots_cmd = [sys.executable, "scripts/slots.py"]'):] step = step[:step.index("3b slot arbitration")] self.assertIn('slots_cmd.extend(["--target", args.target])', step) diff --git a/tests/test_split_extras.py b/tests/test_split_extras.py index e477a6eb1..27d77d3e4 100644 --- a/tests/test_split_extras.py +++ b/tests/test_split_extras.py @@ -23,6 +23,7 @@ from model.profiles import load_emulator_profiles from packs.archive import PackRecord from packs.platformpack import generate_pack from packs.platformpack import generate_split_packs +from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parent.parent @@ -206,9 +207,9 @@ class PipelineComparesTheSplitParts(unittest.TestCase): RetroBat's 21 openmsx/openMSX twins passed every check.""" def setUp(self): - import pipeline + from orchestrate import splitcheck - self.pipeline = pipeline + self.splitcheck = splitcheck def _record(self, sources: dict[str, str]) -> PackRecord: record = PackRecord() @@ -219,7 +220,7 @@ class PipelineComparesTheSplitParts(unittest.TestCase): def test_equal_parts_report_nothing(self): full = self._record({"a.bin": "x", "b.bin": "y"}) parts = {"A": self._record({"a.bin": "x"}), "B": self._record({"b.bin": "y"})} - self.assertEqual(self.pipeline.split_differences(full, parts, str.__eq__), []) + self.assertEqual(self.splitcheck.split_differences(full, parts, str.__eq__), []) def test_each_difference_is_named(self): full = self._record({"SGB1.sfc": "x", "kept.bin": "k", "lost.bin": "l"}) @@ -228,7 +229,7 @@ class PipelineComparesTheSplitParts(unittest.TestCase): "Other": self._record({"SGB1.sfc/program.rom": "p"}), } self.assertEqual( - self.pipeline.split_differences(full, parts, str.__eq__), + self.splitcheck.split_differences(full, parts, str.__eq__), [ "in a part, not in the full pack: SGB1.sfc/program.rom", "in the full pack, in no part: lost.bin", @@ -237,7 +238,7 @@ class PipelineComparesTheSplitParts(unittest.TestCase): ) def test_step_five_runs_the_comparison(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text() + source = script_source("pipeline.py") step = source[source.index("# Step 5: Consistency check"):source.index("# Step 6:")] self.assertIn("check_split_packs(", step) diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index a8c425845..033d1ffb0 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -29,7 +29,7 @@ from packs import archive from packs import emulatorpack from packs import md5pack from tests.scratchtree import scratch_checkout, snapshot -from tests.sources import declared_options +from tests.sources import declared_options, script_source REPO_ROOT = Path(__file__).resolve().parent.parent @@ -539,7 +539,7 @@ class StrictVerifyFailsOnACriticalMiss(unittest.TestCase): self.assertIn("1 required file(s) missing", strict.stderr) def test_the_pipeline_asks_for_it(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text() + source = script_source("pipeline.py") self.assertIn('"scripts/verify.py", "--all", "--strict"', source) diff --git a/tests/test_target_names.py b/tests/test_target_names.py index 9a1631583..3740ff1ff 100644 --- a/tests/test_target_names.py +++ b/tests/test_target_names.py @@ -161,7 +161,7 @@ class OneTruthModelPerTarget(unittest.TestCase): with self.subTest(module=module): self.assertIn("truth_target_dir(", source) self.assertNotIn('re.sub(\n r"[^a-z0-9]+"', source) - pipeline = (REPO_ROOT / "scripts" / "pipeline.py").read_text() + pipeline = script_source("pipeline.py") self.assertIn('diff_cmd.extend(["--target", args.target])', pipeline) @@ -224,7 +224,7 @@ class PublishedListsAreNotNarrowed(unittest.TestCase): file list with the Switch one and check_release asked for it as an asset.""" def test_pipeline_writes_install_unfiltered(self): - pipeline = (REPO_ROOT / "scripts" / "pipeline.py").read_text() + pipeline = script_source("pipeline.py") self.assertNotIn('manifest_cmd.extend(["--target"', pipeline) def test_every_install_list_is_a_whole_platform(self): diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 664c25f31..13856878c 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -22,11 +22,13 @@ from model.registry import list_registered_platforms from model.targets import load_target_config, build_target_cores_cache import diff_truth import pipeline +from orchestrate import guards, labels, prepare, runner from resolve import truth import verify from packs import coverage from packs import report as packs_report from packs import verdicts +from tests.sources import script_source REPO_ROOT = Path(__file__).resolve().parents[1] @@ -377,15 +379,15 @@ class AnOfflineRunWithNoCacheStopsFirst(unittest.TestCase): f"data_directories:\n a:\n local_cache: {cache}\n" ) parser = mock.Mock() - pipeline._refuse_offline_without_caches(parser, self._args(), tmp) + guards.refuse_offline_without_caches(parser, self._args(), tmp) self.assertIn("refresh_data_dirs.py", parser.error.call_args.args[0]) for args in (self._args(offline=False), self._args(skip_packs=True)): parser = mock.Mock() - pipeline._refuse_offline_without_caches(parser, args, tmp) + guards.refuse_offline_without_caches(parser, args, tmp) parser.error.assert_not_called() cache.mkdir() parser = mock.Mock() - pipeline._refuse_offline_without_caches(parser, self._args(), tmp) + guards.refuse_offline_without_caches(parser, self._args(), tmp) parser.error.assert_not_called() @@ -407,19 +409,19 @@ class AnOfflineExportWithNoOriginalsStopsFirst(unittest.TestCase): self.assertIn("batocera", patched) with tempfile.TemporaryDirectory() as tmp: parser = mock.Mock() - pipeline._refuse_offline_export_without_originals(parser, self._args(), tmp) + guards.refuse_offline_export_without_originals(parser, self._args(), tmp) message = parser.error.call_args.args[0] self.assertIn("export_native.py --all --refresh-cache", message) self.assertIn("batocera", message) for args in (self._args(offline=False), self._args(with_export=False)): parser = mock.Mock() - pipeline._refuse_offline_export_without_originals(parser, args, tmp) + guards.refuse_offline_export_without_originals(parser, args, tmp) parser.error.assert_not_called() for name in patched: (Path(tmp) / name).mkdir() (Path(tmp) / name / "original").write_text("x") parser = mock.Mock() - pipeline._refuse_offline_export_without_originals(parser, self._args(), tmp) + guards.refuse_offline_export_without_originals(parser, self._args(), tmp) parser.error.assert_not_called() def test_the_tools_page_says_so(self): @@ -443,7 +445,7 @@ class ThePipelineFlagTableSaysEveryRefusal(unittest.TestCase): for flag, value in flags.items(): setattr(args, flag.lstrip("-").replace("-", "_"), value) parser = mock.Mock() - pipeline._refuse_unapplied_flags(parser, args) + guards.refuse_unapplied_flags(parser, args) return parser.error.called def test_each_refused_pair_is_in_the_row_of_a_flag(self): @@ -696,7 +698,7 @@ class ThePipelineRefreshesTheCommittedExport(unittest.TestCase): def test_the_export_step_writes_the_default_directory(self): import ast - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") for node in ast.walk(ast.parse(source)): if (isinstance(node, ast.Assign) and any(getattr(t, "id", "") == "export_cmd" for t in node.targets)): @@ -714,16 +716,16 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): def test_every_recorded_step_has_a_label(self): import re - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") keys = set(re.findall(r'results\["(\w+)"\] =', source)) - self.assertEqual(keys - set(pipeline.STEP_LABELS), set()) + self.assertEqual(keys - set(labels.STEP_LABELS), set()) def test_a_label_written_out_is_one_of_the_list(self): import re - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") written = re.findall(r'run\([^()]*?, "([^"]+)"\)', source) - numbers = {label.split(" ", 1)[0] for label in pipeline.STEP_LABELS.values()} + numbers = {label.split(" ", 1)[0] for label in labels.STEP_LABELS.values()} for label in written: with self.subTest(label=label): # A step's own label, or a second command of a listed step. @@ -734,25 +736,25 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): computed "5 consistency check [20/24]".""" import re - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + source = script_source("pipeline.py") self.assertEqual(re.findall(r'"[^"\n]*---[^"\n]*\b\d+[a-z]?/\d+\b[^"\n]*"', source), []) def test_progress_comes_from_the_list(self): - total = len(pipeline.STEP_LABELS) - title = pipeline.step_title(pipeline.STEP_LABELS["render_site"]) + total = len(labels.STEP_LABELS) + title = labels.step_title(labels.STEP_LABELS["render_site"]) self.assertEqual(title, f"8b render site [{total}/{total}]") - self.assertNotIn("/8", pipeline.step_title(pipeline.STEP_LABELS["verify"])) + self.assertNotIn("/8", labels.step_title(labels.STEP_LABELS["verify"])) def test_a_skipped_schema_check_says_how_to_run_it(self): """Step 0 said only "jsonschema not installed", then the run read COMPLETE and the schema failed in PR validation.""" argv = ["pipeline.py", "--offline", "--skip-packs", "--skip-docs"] out = io.StringIO() - real_find_spec = pipeline.importlib.util.find_spec + real_find_spec = prepare.importlib.util.find_spec with mock.patch.object(sys, "argv", argv), mock.patch.object( - pipeline, "run", return_value=(True, "") + runner, "run", return_value=(True, "") ), mock.patch.object( - pipeline.importlib.util, "find_spec", + prepare.importlib.util, "find_spec", side_effect=lambda name, *a: None if name == "jsonschema" else real_find_spec(name, *a), ), contextlib.redirect_stdout(out), contextlib.suppress(SystemExit): @@ -769,7 +771,7 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): "--skip-docs"] out = io.StringIO() with mock.patch.object(sys, "argv", argv), mock.patch.object( - pipeline, "run", return_value=(True, "RetroArch: 1/1 OK\n") + runner, "run", return_value=(True, "RetroArch: 1/1 OK\n") ), contextlib.redirect_stdout(out), contextlib.suppress(SystemExit): pipeline.main() summary = out.getvalue().split("=" * 60)[1] @@ -777,7 +779,7 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): # The number the run printed for the step leads its summary row. self.assertIn("4d bundled_only", summary) self.assertTrue( - pipeline.step_title(pipeline.STEP_LABELS["bundled_only"]).startswith("4d ") + labels.step_title(labels.STEP_LABELS["bundled_only"]).startswith("4d ") ) diff --git a/tests/test_verify_release_asset.py b/tests/test_verify_release_asset.py index 1b9ac1217..687d4a27c 100644 --- a/tests/test_verify_release_asset.py +++ b/tests/test_verify_release_asset.py @@ -24,6 +24,7 @@ from unittest import mock import yaml from model.platforms import _platform_config_cache +from tests.sources import script_source from model.profiles import emulator_profiles_cache import generate_db from packs import archive @@ -245,8 +246,8 @@ class OfflinePipelineVerifiesOffline(unittest.TestCase): step has to count them the same way, or step 5 compares two answers.""" def test_verify_step_gets_offline(self): - source = (REPO_ROOT / "scripts" / "pipeline.py").read_text() - block = source[source.index("verify_cmd = ["):source.index("ok, verify_output = run(")] + source = script_source("pipeline.py") + block = source[source.index("verify_cmd = ["):source.index("ok, verify_output = runner.run(")] self.assertIn('verify_cmd.append("--offline")', block) diff --git a/wiki/adding-a-platform.md b/wiki/adding-a-platform.md index 0d966aab5..6ae4f6ab8 100644 --- a/wiki/adding-a-platform.md +++ b/wiki/adding-a-platform.md @@ -770,7 +770,7 @@ python scripts/pipeline.py --offline ``` This executes in sequence, numbered as the run prints them (`STEP_LABELS` in -`scripts/pipeline.py`): +`scripts/orchestrate/labels.py`): - 0 `validate_schemas.py --source-only`, the schema check PR validation runs - 1 `generate_db.py`, rebuild `database.json` from `bios/` diff --git a/wiki/architecture.md b/wiki/architecture.md index a1921f06b..be973af82 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -53,6 +53,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c schemas/ the data contracts behind validate_schemas.py: schemas and semantic invariants unattended/ the job registry, worktree, CI breaker and units behind autorun.py freshness/ each transcribed layer against its upstream, one module per area (check_freshness.py), and the refresh of each stale row (refresh_stale.py) + orchestrate/ the pipeline's steps in order and the comparisons of step 5 (pipeline.py) install/ JSON install manifests per platform targets/ JSON target manifests per platform (cores per architecture) install.py the installer, with install.sh and install.ps1 to start it,