refactor: move the recipe runs into romrecipes

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 14:59:03 +01:00
1 parent 2428d92e6a
commit 0b91bc9e37
7 files changed
+300 -189

No files matched your search

+41
View File
@@ -3,6 +3,8 @@
from __future__ import annotations
import os
from collections import defaultdict
from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
@@ -165,3 +167,42 @@ def select(ledger: dict[str, dict], wanted: str, root: Path = REPO_ROOT) -> list
if key in ledger:
return [ledger[key]]
return [record for path, record in sorted(ledger.items()) if Path(path).name == wanted]
def build_targets(ledger: dict[str, dict], wanted: str | None) -> list[dict]:
"""Every record in path order when *wanted* is None, else those it names."""
if wanted is None:
return [ledger[path] for path in sorted(ledger)]
return select(ledger, wanted)
def build_records(
records: list[dict],
atoms: AtomIndex,
output_dir: Path,
root: Path,
discard: bool = False,
) -> Iterator[BuildResult]:
"""Build each record in turn; with *discard* a verified build is deleted once seen."""
for record in records:
result = build_archive(record, atoms, output_dir, root)
yield result
if discard and result.status in ("exact", "canonical"):
Path(result.output).unlink()
@dataclass
class BuildTally:
"""A build run counted by status, with the archives that read their own members."""
counts: dict[str, int] = field(default_factory=lambda: defaultdict(int))
own: list[tuple[str, int]] = field(default_factory=list)
def add(self, result: BuildResult) -> None:
self.counts[result.status] += 1
if result.own_members:
self.own.append((result.path, result.own_members))
@property
def own_members(self) -> int:
return sum(n for _p, n in self.own)
+36 -1
View File
@@ -7,12 +7,13 @@ import zipfile
from collections import defaultdict
from collections.abc import Callable, Iterable
from concurrent.futures import ProcessPoolExecutor
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO
from core.hashing import parse_hash_list
from core.torrentzip import has_torrentzip_comment, write_torrentzip, zlib_ng_version
from romrecipes.ledger import database_archives
from romrecipes.ledger import database_archives, load_ledger, write_ledger
from romrecipes.members import member_sha1, member_opener
from romrecipes.pins import container_entries
from romrecipes.romsets import collect_recipes, load_dat_recipes
@@ -209,3 +210,37 @@ class ZlibNgError(RuntimeError):
"stock zlib's level-9 output, so an exact rebuild cannot be proven "
"or claimed here. Run under a Python linked against stock zlib."
)
@dataclass
class CaptureRun:
"""The records a capture wrote, the archives it could not read, and whether the file changed."""
records: dict[str, dict]
failed: dict[str, str]
changed: bool
def counts(self) -> dict[str, int]:
"""Records by rebuild class, those agreeing with another recipe, those pinned as bytes."""
by_class: dict[str, int] = defaultdict(int)
for record in self.records.values():
by_class[record["rebuild"]] += 1
return {
"exact": by_class["exact"],
"canonical": by_class["canonical"],
"agreed": sum(1 for record in self.records.values() if len(record["sources"]) > 1),
"pinned": sum(1 for record in self.records.values() if record.get("bytes_pinned")),
}
def capture_ledger(
archives: Path, db: dict, emulators_dir: str, dat_recipes: str, platforms_dir: str,
) -> CaptureRun:
"""Capture every archive of *db* against the ledger at *archives* and write it back."""
records, failed = capture(
db,
load_ledger(archives),
recipe_index(emulators_dir, dat_recipes),
container_pins(platforms_dir, emulators_dir),
)
return CaptureRun(records, failed, write_ledger(records, archives))
+64
View File
@@ -0,0 +1,64 @@
"""The recipe survey: recipes and ROM atoms counted, archives identified, missing pins attempted."""
from __future__ import annotations
from pathlib import Path
from model.profiles import load_emulator_profiles
from romrecipes.identify import identify_report, missing_report, write_reconstructions
from romrecipes.pool import DIGEST_CACHE, AtomPool
from romrecipes.romsets import collect_recipes, load_dat_recipes, merge_recipes
def survey_modes(identify: bool, missing: bool, write: bool) -> tuple[bool, bool]:
"""Which reports run: both by default, and the missing pins whenever *write*.
The reconstructions --write saves are those of the missing pins: with
--identify alone beside it, nothing ran them, nothing was written, and
the run exited 0.
"""
if write:
missing = True
if not identify and not missing:
identify = missing = True
return identify, missing
def survey(
bios_dir: Path,
emulators_dir: str,
dat_recipes_path: str,
platforms_dir: str,
db: dict,
*,
identify: bool,
missing: bool,
write: bool,
) -> dict:
"""Recipe and atom counts, then the identification and missing-pin reports asked for."""
profiles = load_emulator_profiles(emulators_dir, skip_aliases=False)
profile_recipes = collect_recipes(profiles)
dat_recipes = load_dat_recipes(dat_recipes_path)
recipes = merge_recipes(profile_recipes, dat_recipes)
pool = AtomPool(bios_dir, DIGEST_CACHE, db)
result: dict = {
"recipes": sum(len(v) for v in recipes.values()),
"profile_recipes": sum(len(v) for v in profile_recipes.values()),
"dat_recipes": sum(len(v) for v in dat_recipes.values()),
"archives_with_recipes": len(recipes),
"atoms": len(pool),
}
if pool.unreadable:
result["unreadable_archives"] = pool.unreadable
if identify:
result["identify"] = identify_report(recipes, pool, db)
if missing:
result["missing"] = missing_report(recipes, pool, db, platforms_dir)
if write:
result["written"] = write_reconstructions(
result["missing"]["constructible"], recipes, pool, bios_dir, db,
)
pool.save_digests()
return result
+119
View File
@@ -0,0 +1,119 @@
"""Terminal text of the recipe survey, the archive capture and the archive builds."""
from __future__ import annotations
import sys
from collections import defaultdict
from romrecipes.build import BuildResult, BuildTally
from romrecipes.capture import CaptureRun
def print_survey(result: dict) -> None:
"""The survey counts, then each report it ran."""
print(
f"{result['archives_with_recipes']} archives described by "
f"{result['recipes']} recipes "
f"({result['profile_recipes']} from profiles, {result['dat_recipes']} from DATs), "
f"{result['atoms']} ROM atoms available"
)
if not result["dat_recipes"]:
print(
" No DAT recipe: import one with "
"`python -m scripts.scraper.romset_dat_importer --source mame --fetch mame0289`"
)
for problem in result.get("unreadable_archives", []):
print(f" UNREADABLE: {problem}")
if "identify" in result:
print_identification(result["identify"])
if "missing" in result:
print_missing(result["missing"])
for path in result.get("written", []):
print(f" WROTE: {path}")
def print_identification(ident: dict) -> None:
"""Which recipe reproduces each local archive, counted by recipe."""
print(
f"\nIdentification: {len(ident['identified'])} archives reproduced "
f"by a recipe, {len(ident['unidentified'])} unidentified"
)
print(
" The label is the oldest version producing these bytes: a recipe "
"unchanged since 0.177 is counted there, not at its own version."
)
by_recipe: dict[str, int] = defaultdict(int)
for record in ident["identified"]:
by_recipe[record["recipe"]] += 1
for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])):
print(f" {label}: {count}")
for record in ident["unidentified"][:10]:
print(f" UNIDENTIFIED: {record['path']}")
def print_missing(gap: dict) -> None:
"""The pinned archives the collection lacks, each one named."""
print(
f"\nPinned archives not held: "
f"{len(gap['constructible'])} buildable, "
f"{len(gap['unreproducible'])} not reproducible, "
f"{len(gap['no_recipe'])} without a recipe"
)
for record in gap["constructible"]:
print(
f" BUILDABLE: {record['archive']} md5={record['md5'][:8]} "
f"via {record['recipe']} ({record['size']} bytes)"
)
# The acquisition targets: an archive pinned under several md5s is
# one line, the platforms' own bundles rather than romsets.
by_archive: dict[str, list[str]] = defaultdict(list)
for record in gap["unreproducible"]:
by_archive[record["archive"]].append(record["md5"][:8])
for archive, md5s in sorted(by_archive.items(), key=lambda kv: (-len(kv[1]), kv[0])):
print(f" NOT REPRODUCIBLE: {archive} ({len(md5s)} pinned: {', '.join(sorted(md5s))})")
for record in gap["no_recipe"]:
print(f" NO RECIPE: {record['archive']} md5={record['md5'][:8]}")
def print_capture(run: CaptureRun, archives: str) -> None:
"""The archives a capture could not read, its counts and whether it wrote."""
for path, reason in sorted(run.failed.items()):
print(f" UNREADABLE: {path}: {reason}", file=sys.stderr)
counts = run.counts()
print(
f"{len(run.records)} archive recipes: {counts['exact']} exact, "
f"{counts['canonical']} canonical; {counts['agreed']} agree with a profile or DAT "
f"recipe, {counts['pinned']} pinned as bytes"
)
print(f"{'Wrote' if run.changed else 'Unchanged'} {archives}")
def print_build_result(result: BuildResult) -> None:
"""One line per built archive, one per member an impossible build lacks."""
if result.status == "impossible":
for member in result.missing:
print(
f" IMPOSSIBLE: {result.path}: missing {member['name']} "
f"({member['sha1']})"
)
elif result.status == "failed":
print(f" FAILED: {result.path}: {result.detail}")
else:
note = f" ({result.detail})" if result.detail else ""
print(f" {result.status.upper()}: {result.path}{note}")
def print_build_totals(tally: BuildTally, total: int) -> None:
"""The build run counted by status, and the members held only in their own archive."""
counts = tally.counts
print(
f"\n{total} archives: {counts['exact']} rebuilt exact, "
f"{counts['canonical']} canonical, {counts['impossible']} impossible, "
f"{counts['failed']} failed"
)
print(
f" {len(tally.own)} of them read {tally.own_members} members from their "
"own archive, held nowhere else in the collection"
)
+33 -174
View File
@@ -40,12 +40,12 @@ Every archive the collection holds also has a recipe of its own in
canonical, or impossible with the member nothing holds.
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import defaultdict
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@@ -53,66 +53,24 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
from core.cli import add_repo_inputs, require_directory
from core.torrentzip import zlib_ng_version
from model.database import load_database
from model.profiles import load_emulator_profiles
from romrecipes.build import AtomIndex, build_archive, select
from romrecipes.capture import ZlibNgError, capture, container_pins, recipe_index
from romrecipes.identify import identify_report, missing_report, write_reconstructions
from romrecipes.ledger import ARCHIVES_FILE, load_ledger, write_ledger
from romrecipes.pool import AtomPool, DIGEST_CACHE
from romrecipes.romsets import collect_recipes, load_dat_recipes, merge_recipes
def print_missing(gap: dict) -> None:
"""The pinned archives the collection lacks, each one named."""
print(
f"\nPinned archives not held: "
f"{len(gap['constructible'])} buildable, "
f"{len(gap['unreproducible'])} not reproducible, "
f"{len(gap['no_recipe'])} without a recipe"
)
for record in gap["constructible"]:
print(
f" BUILDABLE: {record['archive']} md5={record['md5'][:8]} "
f"via {record['recipe']} ({record['size']} bytes)"
)
# The acquisition targets: an archive pinned under several md5s is
# one line, the platforms' own bundles rather than romsets.
by_archive: dict[str, list[str]] = defaultdict(list)
for record in gap["unreproducible"]:
by_archive[record["archive"]].append(record["md5"][:8])
for archive, md5s in sorted(by_archive.items(), key=lambda kv: (-len(kv[1]), kv[0])):
print(f" NOT REPRODUCIBLE: {archive} ({len(md5s)} pinned: {', '.join(sorted(md5s))})")
for record in gap["no_recipe"]:
print(f" NO RECIPE: {record['archive']} md5={record['md5'][:8]}")
from romrecipes.build import AtomIndex, BuildTally, build_records, build_targets
from romrecipes.capture import ZlibNgError, capture_ledger
from romrecipes.ledger import ARCHIVES_FILE, load_ledger
from romrecipes.survey import survey, survey_modes
from romrecipes.text import print_build_result, print_build_totals, print_capture, print_survey
def run_capture(args: argparse.Namespace, db: dict) -> int:
"""Write recipes/archives.json for every archive the database lists."""
try:
records, failed = capture(
db,
load_ledger(Path(args.archives)),
recipe_index(args.emulators_dir, args.dat_recipes),
container_pins(args.platforms_dir, args.emulators_dir),
run = capture_ledger(
Path(args.archives), db, args.emulators_dir, args.dat_recipes, args.platforms_dir,
)
except ZlibNgError as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 2
for path, reason in sorted(failed.items()):
print(f" UNREADABLE: {path}: {reason}", file=sys.stderr)
changed = write_ledger(records, Path(args.archives))
by_class: dict[str, int] = defaultdict(int)
for record in records.values():
by_class[record["rebuild"]] += 1
agreed = sum(1 for record in records.values() if len(record["sources"]) > 1)
pinned = sum(1 for record in records.values() if record.get("bytes_pinned"))
print(
f"{len(records)} archive recipes: {by_class['exact']} exact, "
f"{by_class['canonical']} canonical; {agreed} agree with a profile or DAT "
f"recipe, {pinned} pinned as bytes"
)
print(f"{'Wrote' if changed else 'Unchanged'} {args.archives}")
return 1 if failed else 0
print_capture(run, args.archives)
return 1 if run.failed else 0
def run_build(args: argparse.Namespace, db: dict) -> int:
@@ -121,13 +79,10 @@ def run_build(args: argparse.Namespace, db: dict) -> int:
print("ERROR: --build and --build-all need --output-dir", file=sys.stderr)
return 2
ledger = load_ledger(Path(args.archives))
if args.build_all:
records = [ledger[path] for path in sorted(ledger)]
else:
records = select(ledger, args.build)
if not records:
print(f"ERROR: no archive recipe named {args.build}", file=sys.stderr)
return 2
records = build_targets(ledger, None if args.build_all else args.build)
if not records and not args.build_all:
print(f"ERROR: no archive recipe named {args.build}", file=sys.stderr)
return 2
ng = zlib_ng_version()
if ng:
print(
@@ -136,74 +91,18 @@ def run_build(args: argparse.Namespace, db: dict) -> int:
)
root = Path(args.bios_dir).resolve().parent
atoms = AtomIndex.from_collection(ledger, db, root)
counts: dict[str, int] = defaultdict(int)
own: list[tuple[str, int]] = []
for record in records:
result = build_archive(record, atoms, Path(args.output_dir), root)
counts[result.status] += 1
if result.own_members:
own.append((result.path, result.own_members))
if result.status == "impossible":
for member in result.missing:
print(
f" IMPOSSIBLE: {result.path}: missing {member['name']} "
f"({member['sha1']})"
)
elif result.status == "failed":
print(f" FAILED: {result.path}: {result.detail}")
else:
note = f" ({result.detail})" if result.detail else ""
print(f" {result.status.upper()}: {result.path}{note}")
if args.discard:
Path(result.output).unlink()
print(
f"\n{len(records)} archives: {counts['exact']} rebuilt exact, "
f"{counts['canonical']} canonical, {counts['impossible']} impossible, "
f"{counts['failed']} failed"
)
print(
f" {len(own)} of them read {sum(n for _p, n in own)} members from their "
"own archive, held nowhere else in the collection"
)
if counts["failed"]:
tally = BuildTally()
for result in build_records(records, atoms, Path(args.output_dir), root, args.discard):
tally.add(result)
print_build_result(result)
print_build_totals(tally, len(records))
if tally.counts["failed"]:
print("ERROR: a build did not match its recipe and was not kept", file=sys.stderr)
return 1
return 1 if counts["impossible"] else 0
return 1 if tally.counts["impossible"] else 0
def _resolve_modes(args: argparse.Namespace) -> None:
"""Which reports run: both by default, and --missing whenever --write.
The reconstructions --write saves are those of the missing pins: with
--identify alone beside it, nothing ran them, nothing was written, and
the run exited 0.
"""
if args.write:
args.missing = True
if not args.identify and not args.missing:
args.identify = args.missing = True
def print_identification(ident: dict) -> None:
"""Which recipe reproduces each local archive, counted by recipe."""
print(
f"\nIdentification: {len(ident['identified'])} archives reproduced "
f"by a recipe, {len(ident['unidentified'])} unidentified"
)
print(
" The label is the oldest version producing these bytes: a recipe "
"unchanged since 0.177 is counted there, not at its own version."
)
by_recipe: dict[str, int] = defaultdict(int)
for record in ident["identified"]:
by_recipe[record["recipe"]] += 1
for label, count in sorted(by_recipe.items(), key=lambda kv: (-kv[1], kv[0])):
print(f" {label}: {count}")
for record in ident["unidentified"][:10]:
print(f" UNIDENTIFIED: {record['path']}")
def main() -> int:
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
allow_abbrev=False,
description=__doc__.replace("``", ""),
@@ -240,6 +139,11 @@ def main() -> int:
"--discard", action="store_true",
help="delete each build once verified: a full proof without the disk space",
)
return parser
def main() -> int:
parser = build_parser()
args = parser.parse_args()
require_directory(args.bios_dir)
if (args.output_dir or args.discard) and not (args.build or args.build_all):
@@ -252,60 +156,15 @@ def main() -> int:
return run_capture(args, db)
if args.build or args.build_all:
return run_build(args, db)
_resolve_modes(args)
profiles = load_emulator_profiles(args.emulators_dir, skip_aliases=False)
profile_recipes = collect_recipes(profiles)
dat_recipes = load_dat_recipes(args.dat_recipes)
recipes = merge_recipes(profile_recipes, dat_recipes)
pool = AtomPool(Path(args.bios_dir), DIGEST_CACHE, db)
result: dict = {
"recipes": sum(len(v) for v in recipes.values()),
"profile_recipes": sum(len(v) for v in profile_recipes.values()),
"dat_recipes": sum(len(v) for v in dat_recipes.values()),
"archives_with_recipes": len(recipes),
"atoms": len(pool),
}
if pool.unreadable:
result["unreadable_archives"] = pool.unreadable
if args.identify:
result["identify"] = identify_report(recipes, pool, db)
if args.missing:
result["missing"] = missing_report(recipes, pool, db, args.platforms_dir)
if args.write:
result["written"] = write_reconstructions(
result["missing"]["constructible"], recipes, pool,
Path(args.bios_dir), db,
)
pool.save_digests()
args.identify, args.missing = survey_modes(args.identify, args.missing, args.write)
result = survey(
Path(args.bios_dir), args.emulators_dir, args.dat_recipes, args.platforms_dir, db,
identify=args.identify, missing=args.missing, write=args.write,
)
if args.json:
print(json.dumps(result, indent=2, sort_keys=True))
return 0
print(
f"{result['archives_with_recipes']} archives described by "
f"{result['recipes']} recipes "
f"({result['profile_recipes']} from profiles, {result['dat_recipes']} from DATs), "
f"{result['atoms']} ROM atoms available"
)
if not result["dat_recipes"]:
print(
" No DAT recipe: import one with "
"`python -m scripts.scraper.romset_dat_importer --source mame --fetch mame0289`"
)
for problem in result.get("unreadable_archives", []):
print(f" UNREADABLE: {problem}")
if args.identify:
print_identification(result["identify"])
if args.missing:
print_missing(result["missing"])
for path in result.get("written", []):
print(f" WROTE: {path}")
print_survey(result)
return 0
+1
View File
@@ -130,6 +130,7 @@ COMMANDS = {
"romset_recipes.py": (
"romrecipes/romsets.py", "romrecipes/pool.py", "romrecipes/pins.py", "romrecipes/identify.py",
"romrecipes/ledger.py", "romrecipes/members.py", "romrecipes/capture.py", "romrecipes/build.py",
"romrecipes/survey.py", "romrecipes/text.py",
),
"provenance_report.py": ("acquire/provenance.py",),
"auto_fetch.py": ("acquire/fetch.py",),
+6 -14
View File
@@ -738,7 +738,7 @@ class TheMissingReportNamesItsTargets(unittest.TestCase):
import contextlib
import io
import romset_recipes
from romrecipes.text import print_missing
gap = {
"constructible": [],
@@ -749,7 +749,7 @@ class TheMissingReportNamesItsTargets(unittest.TestCase):
}
out = io.StringIO()
with contextlib.redirect_stdout(out):
romset_recipes.print_missing(gap)
print_missing(gap)
text = out.getvalue()
self.assertIn("NOT REPRODUCIBLE: neogeo.zip (2 pinned: aaaaaaaa, bbbbbbbb)", text)
self.assertIn("NOT REPRODUCIBLE: aes.zip (1 pinned: cccccccc)", text)
@@ -824,19 +824,11 @@ class WriteRunsTheReportItWrites(unittest.TestCase):
--write saves come from the missing-pins report, which did not run."""
def test_write_implies_missing(self):
import argparse
from romrecipes.survey import survey_modes
import romset_recipes
args = argparse.Namespace(identify=True, missing=False, write=True)
romset_recipes._resolve_modes(args)
self.assertEqual((args.identify, args.missing), (True, True))
default = argparse.Namespace(identify=False, missing=False, write=False)
romset_recipes._resolve_modes(default)
self.assertEqual((default.identify, default.missing), (True, True))
alone = argparse.Namespace(identify=True, missing=False, write=False)
romset_recipes._resolve_modes(alone)
self.assertEqual((alone.identify, alone.missing), (True, False))
self.assertEqual(survey_modes(True, False, True), (True, True))
self.assertEqual(survey_modes(False, False, False), (True, True))
self.assertEqual(survey_modes(True, False, False), (True, False))