From 198515f1cb6f67e45c9e259503a1d13f98160eb6 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:57:30 +0100 Subject: [PATCH] refactor: move dedup and integrity into collection --- scripts/bios_integrity.py | 151 +-------------- scripts/collection/__init__.py | 2 +- scripts/collection/clonemap.py | 95 +++++++++ scripts/collection/dedup.py | 126 ++++++++++++ scripts/collection/duplicates.py | 123 ++++++++++++ scripts/collection/gitrestore.py | 59 ++++++ scripts/collection/integrity.py | 105 ++++++++++ scripts/dedup.py | 320 +------------------------------ tests/sources.py | 4 + tests/test_audit_regressions.py | 2 +- tests/test_autorun.py | 5 +- tests/test_dedup.py | 24 +-- tests/test_layers.py | 1 + wiki/architecture.md | 1 + 14 files changed, 532 insertions(+), 486 deletions(-) create mode 100644 scripts/collection/clonemap.py create mode 100644 scripts/collection/dedup.py create mode 100644 scripts/collection/duplicates.py create mode 100644 scripts/collection/gitrestore.py create mode 100644 scripts/collection/integrity.py diff --git a/scripts/bios_integrity.py b/scripts/bios_integrity.py index cf0eb1a59..701ac8b94 100644 --- a/scripts/bios_integrity.py +++ b/scripts/bios_integrity.py @@ -32,162 +32,15 @@ Usage: from __future__ import annotations import argparse -import hashlib import json import os -import subprocess import sys -import tempfile -from collections.abc import Callable -from dataclasses import dataclass, field from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from collection.gitrestore import GitFailed +from collection.integrity import check from core.cli import add_repo_inputs -from core.hashing import file_digest, git_blob_sha -from model.largefiles import load_registered_paths - -MISREAD = "misread" -RESTORED = "restored" -FLAGGED = "flagged" -SKIPPED = "skipped" - - -@dataclass(frozen=True) -class Finding: - path: str - verdict: str # misread, restored, flagged, skipped - reason: str - expected: str - found: str = "" - - -@dataclass -class Report: - checked: int = 0 - findings: list[Finding] = field(default_factory=list) - - def counts(self) -> dict[str, int]: - counts: dict[str, int] = {} - for f in self.findings: - counts[f.verdict] = counts.get(f.verdict, 0) + 1 - return counts - - def as_dict(self) -> dict: - return { - "checked": self.checked, - "counts": self.counts(), - "findings": [f.__dict__ for f in self.findings], - } - - @property - def clean(self) -> bool: - return all(f.verdict in (MISREAD, RESTORED) for f in self.findings) - - -class GitFailed(RuntimeError): - """A git command failed: its empty output says nothing about the file.""" - - -def git(root: Path, *args: str) -> subprocess.CompletedProcess: - """Run git in root. A failure raises: an unreadable index read as an empty - status made a session's working change look unmodified, and --apply wrote - HEAD's bytes over it.""" - done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False) - if done.returncode: - message = done.stderr.decode(errors="replace").strip() - raise GitFailed(f"git {' '.join(args)} exited {done.returncode}: {message}") - return done - - -def head_blob(root: Path, path: str) -> str: - """The blob HEAD records for path, empty when HEAD has none.""" - out = git(root, "ls-tree", "HEAD", "--", path).stdout.decode() - parts = out.split() - return parts[2] if len(parts) >= 3 and parts[1] == "blob" else "" - - -def modified_for_git(root: Path, path: str) -> bool: - return bool(git(root, "status", "--porcelain", "--", path).stdout.strip()) - - -def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str: - """Write the blob's bytes over path, after checking them. Empty on success.""" - data = git(root, "cat-file", "blob", blob).stdout - object_id = git_blob_sha(data) - if object_id != blob: - return f"blob read back as {object_id[:12]}, not {blob[:12]}" - if hashlib.sha1(data).hexdigest() != expected: - return "HEAD holds other bytes than database.json records" - target = root / path - handle, scratch = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.") - try: - with os.fdopen(handle, "wb") as out: - out.write(data) - os.chmod(scratch, target.stat().st_mode & 0o777) - os.replace(scratch, target) - except OSError: - if os.path.exists(scratch): - os.unlink(scratch) - raise - return "" - - -def check( - root: Path, - db: dict, - apply: bool, - hasher: Callable[[Path], str] = file_digest, -) -> Report: - """Hash every database path, confirm each mismatch, repair what may be.""" - ignored = set(load_registered_paths(root / ".gitignore")) - report = Report() - for key, entry in sorted(db.get("files", {}).items(), key=lambda kv: kv[1]["path"]): - path = entry["path"] - expected = str(entry.get("sha1") or key).lower() - local = root / path - if not local.is_file(): - continue # a release asset not fetched yet, verify reports it - report.checked += 1 - first = hasher(local) - if first == expected: - continue - second = hasher(local) - if second != first: - verdict = MISREAD if second == expected else FLAGGED - report.findings.append(Finding( - path, verdict, f"two reads disagree ({first[:12]}, {second[:12]})", - expected, second)) - continue - if path in ignored: - report.findings.append(Finding( - path, FLAGGED, "gitignored large file, never repaired here", expected, first)) - continue - blob = head_blob(root, path) - if not blob: - report.findings.append(Finding(path, FLAGGED, "not in HEAD", expected, first)) - continue - if modified_for_git(root, path): - report.findings.append(Finding( - path, SKIPPED, "modified for git: a working change, left alone", - expected, first)) - continue - if not apply: - report.findings.append(Finding( - path, FLAGGED, "bit flip, restorable from HEAD with --apply", expected, first)) - continue - problem = restore_from_blob(root, path, blob, expected) - if problem: - report.findings.append(Finding(path, FLAGGED, problem, expected, first)) - continue - after = hasher(local) - if after == expected: - report.findings.append(Finding( - path, RESTORED, f"restored from blob {blob[:12]}", expected, first)) - else: - report.findings.append(Finding( - path, FLAGGED, f"restored but reads {after[:12]}", expected, after)) - return report def main() -> int: diff --git a/scripts/collection/__init__.py b/scripts/collection/__init__.py index bf9136c5d..78260062e 100644 --- a/scripts/collection/__init__.py +++ b/scripts/collection/__init__.py @@ -1 +1 @@ -"""The collection held in bios/: its scan, its database and the checks of its files.""" +"""The collection under bios/: its database, its duplicates and the integrity of its bytes.""" diff --git a/scripts/collection/clonemap.py b/scripts/collection/clonemap.py new file mode 100644 index 000000000..c8ba6a5a7 --- /dev/null +++ b/scripts/collection/clonemap.py @@ -0,0 +1,95 @@ +"""The MAME clone map _mame_clones.json: where it lives, reading, merging and writing it.""" + +from __future__ import annotations + +import json +import os + +from core.artifacts import write_text_atomic + + +def clone_map_path(bios_dir: str) -> str: + """The clone map beside the scanned tree. + + That is where get_mame_clone_map() reads it for the real layout. A path + relative to the working directory let a scan of a fixture tree rewrite + the repository's own map. + """ + return os.path.join(os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json") + + +def read_clone_map(clone_path: str) -> object: + """The clone map an earlier run wrote, {} when there is none.""" + # Read before anything is removed: the map is cumulative, and a run that + # stopped on an unreadable one after deleting clones would lose them. + try: + with open(clone_path) as f: + return json.load(f) + except FileNotFoundError: + return {} + except json.JSONDecodeError as e: + raise SystemExit( + f"{clone_path} is not valid JSON ({e}). Restore it from git " + "before deduplicating again" + ) from e + + +def record_clone_map( + mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool +) -> None: + """Write the clone map, merged with what earlier runs recorded.""" + # A group is only visible while both copies are on disk, and this run + # has just deleted the clone. Writing only what was seen this time + # therefore erases every mapping an earlier run recorded, and the + # canonical zip stops answering to the names it stands in for. The + # older entries stay valid: their canonical file is still here. + if not dry_run and isinstance(previous, dict): + merged = dict(previous) + merged.update(mame_clones) + mame_clones = collapse_clone_chains(merged) + if dry_run: + print(f"\nWould write MAME clone map: {clone_path}") + else: + write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) + print(f"\nWrote MAME clone map: {clone_path}") + print( + f" {len(mame_clones)} canonical ZIPs with " + f"{sum(len(v['clones']) for v in mame_clones.values())} clones" + ) + + +def collapse_clone_chains(clone_map: dict[str, dict]) -> dict[str, dict]: + """Point every clone at a canonical archive that still exists. + + The map is cumulative. When a later run finds that a canonical archive is + itself a byte-identical copy of another and removes it, the entry that + named it as canonical would send its clones to a file that is gone: + sys68k_cpu21a pointed at sys68k_cpu21 after sys68k_cpu21 became a clone + of sys68k_cpu20. Each such entry's clones move to the final canonical. + """ + owner = { + clone: canonical + for canonical, entry in clone_map.items() + for clone in entry.get("clones", []) + } + + def final(name: str) -> str: + seen = {name} + while name in owner: + name = owner[name] + if name in seen: + raise ValueError(f"clone map loops through {name}") + seen.add(name) + return name + + collapsed: dict[str, dict] = {} + for canonical, entry in clone_map.items(): + target = final(canonical) + kept = collapsed.setdefault(target, {**clone_map.get(target, entry), "clones": []}) + names = set(kept["clones"]) | set(entry.get("clones", [])) + if target != canonical: + names.add(canonical) + names.discard(target) + kept["clones"] = sorted(names) + kept["total_copies"] = len(kept["clones"]) + return collapsed diff --git a/scripts/collection/dedup.py b/scripts/collection/dedup.py new file mode 100644 index 000000000..a3de25676 --- /dev/null +++ b/scripts/collection/dedup.py @@ -0,0 +1,126 @@ +"""Deduplication of bios/: one canonical file per content, the other copies removed.""" + +from __future__ import annotations + +import os + +from collection.clonemap import clone_map_path, read_clone_map, record_clone_map +from collection.duplicates import path_priority, plan_group_removals, scan_duplicates +from core.sizes import size_text + + +def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]: + """Remove (or name, in a dry run) each copy beside the canonical file.""" + removed: list[str] = [] + for dup in true_dupes_to_remove: + if dup == canonical: + continue + if not os.path.exists(dup): + continue + if dry_run: + print(f" WOULD REMOVE: {dup}") + else: + try: + os.remove(dup) + except OSError as e: + print(f" WARNING: cannot remove {dup}: {e}") + continue + # Clean up empty .variants/ directories + parent = os.path.dirname(dup) + if os.path.basename(parent) == ".variants" and not os.listdir(parent): + os.rmdir(parent) + removed.append(dup) + return removed + + +def _settle_group(paths: list[str], true_dupes_to_remove: list[str], dry_run: bool) -> dict: + """Keep the best copy of one content and remove the others.""" + # Find the best canonical across all paths + all_paths = [p for p in paths if p not in true_dupes_to_remove] + if not all_paths: + # All copies were marked for removal: keep the best one + all_paths_sorted = sorted(paths, key=path_priority) + all_paths = [all_paths_sorted[0]] + true_dupes_to_remove = [p for p in paths if p != all_paths[0]] + + canonical = sorted(all_paths, key=path_priority)[0] + canonical_name = os.path.basename(canonical) + + all_names = set(os.path.basename(p) for p in paths) + alias_names = sorted(all_names - {canonical_name}) + + size = os.path.getsize(canonical) + removed = _remove_copies(canonical, true_dupes_to_remove, dry_run) + + if alias_names or true_dupes_to_remove: + action = "Would remove" if dry_run else "Removed" + dn = os.path.basename(canonical) + print(f" {dn} (keep: {canonical})") + if true_dupes_to_remove: + print(f" {action} {len(true_dupes_to_remove)} copies") + if alias_names: + print(f" MAME clones: {alias_names}") + return { + "canonical": canonical, + "removed": removed, + "aliases": alias_names, + "saved": size * len(removed), + } + + +def _remove_empty_dirs(bios_dir: str) -> int: + """Remove the directories the removals left empty, bottom up.""" + empty_cleaned = 0 + for root, dirs, files in os.walk(bios_dir, topdown=False): + if not files and not dirs and root != bios_dir: + os.rmdir(root) + empty_cleaned += 1 + return empty_cleaned + + +def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: + """Remove true duplicates, map MAME device clones. + + True duplicates (same name, different dirs): removes copies. + MAME clones (different names, same content, same dir): creates mapping. + + Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}} + """ + clone_path = clone_map_path(bios_dir) + previous = read_clone_map(clone_path) + + sha1_groups = scan_duplicates(bios_dir) + results: dict[str, dict] = {} + total_removed = 0 + total_saved = 0 + mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]} + + for sha1, paths in sorted(sha1_groups.items()): + if len(paths) <= 1: + continue + + true_dupes_to_remove = plan_group_removals(sha1, paths, mame_clones) + + if not true_dupes_to_remove: + continue + + settled = _settle_group(paths, true_dupes_to_remove, dry_run) + total_removed += len(settled["removed"]) + total_saved += settled.pop("saved") + results[sha1] = settled + + # Clean up empty directories + empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir) + + prefix = "Would remove" if dry_run else "Removed" + print(f"\n{prefix}: {total_removed} files") + print( + f"Space {'to save' if dry_run else 'saved'}: {size_text(total_saved)}" + ) + if not dry_run and empty_cleaned: + print(f"Cleaned {empty_cleaned} empty directories") + + if mame_clones: + record_clone_map(mame_clones, previous, clone_path, dry_run) + + return results diff --git a/scripts/collection/duplicates.py b/scripts/collection/duplicates.py new file mode 100644 index 000000000..7440e64eb --- /dev/null +++ b/scripts/collection/duplicates.py @@ -0,0 +1,123 @@ +"""Which files of bios/ hold the same content, and which of those copies may go.""" + +from __future__ import annotations + +import os +from collections import defaultdict +from pathlib import Path + +from core.hashing import compute_hashes +from model.nodedup import in_nodedup_dir + + +def path_priority(path: str) -> tuple: + """Lower score = better candidate to keep as canonical. + + Prefers: shorter path, non-variant, non-MAME (system-specific over generic). + """ + parts = Path(path).parts + is_variant = ".variants" in parts + is_mame = "MAME" in parts + is_arcade = "Arcade" in parts + return (is_variant, is_mame, is_arcade, len(parts), path) + + +def _is_mame_dir(path: str) -> bool: + """Check if a path is in a MAME-specific directory.""" + parts = Path(path).parts + return "MAME" in parts or "Arcade" in parts + + +def scan_duplicates(bios_dir: str) -> dict[str, list[str]]: + """Files grouped by SHA1, excluding no-dedup directories. + + Two equal files have the same size, so only files that share a size are + read, and for the sha1 alone: hashing the whole tree with every digest + took 33 s for a scan that reads a quarter of it. A file alone at its + size is in no group of two and is left out. + """ + by_size: dict[int, list[str]] = defaultdict(list) + for root, _dirs, files in os.walk(bios_dir): + for name in files: + path = os.path.join(root, name) + if in_nodedup_dir(path): + continue + by_size[os.path.getsize(path)].append(path) + + sha1_to_paths: dict[str, list[str]] = defaultdict(list) + for paths in by_size.values(): + if len(paths) < 2: + continue + for path in paths: + sha1_to_paths[compute_hashes(path, frozenset({"sha1"}))["sha1"]].append(path) + return sha1_to_paths + + +def plan_group_removals( + sha1: str, paths: list[str], mame_clones: dict +) -> list[str]: + """Decide which copies of one content hash may go. + + Two files with the same content are not automatically interchangeable. + Same name in different directories is a true duplicate. Different names + are only collapsible when they are MAME device clones, which is why the + check is narrowed to zips under a MAME directory: anywhere else each + name may be the one some emulator looks for. + + Records clone groups in *mame_clones* and returns the paths to remove. + """ + true_dupes_to_remove: list[str] = [] + # Separate by filename: same name = true duplicate, different name = clone + by_name: dict[str, list[str]] = defaultdict(list) + for p in paths: + by_name[os.path.basename(p)].append(p) + + # True duplicates: same filename in multiple directories + true_dupes_to_remove = [] + for name_paths in by_name.values(): + if len(name_paths) > 1: + name_paths.sort(key=path_priority) + true_dupes_to_remove.extend(name_paths[1:]) + + # A variant exists to hold a content its primary does not. Once another + # file holds the same bytes, the copy under .variants/ answers nothing + # the index does not already know, whatever its name or suffix: the + # resolver finds the content by hash and writes it under the name the + # destination asks for. + remaining = [p for p in paths if p not in true_dupes_to_remove] + variants = [p for p in remaining if ".variants" in Path(p).parts] + if variants: + holders = [p for p in remaining if p not in variants] or [ + min(variants, key=path_priority) + ] + true_dupes_to_remove.extend(p for p in variants if p not in holders) + + # Different filenames, same content: need special handling + unique_names = sorted(by_name.keys()) + if len(unique_names) > 1: + # Check if these are all in MAME/Arcade dirs AND all ZIPs + all_mame_zip = all( + any(_is_mame_dir(p) for p in name_paths) + for name_paths in by_name.values() + ) and all(n.endswith(".zip") for n in unique_names) + if all_mame_zip: + # MAME device clones: different ZIP names, same ROM content + # Keep one canonical, remove clones, record in clone map + canonical_name = min(unique_names, key=len) + clone_names = sorted(n for n in unique_names if n != canonical_name) + if clone_names: + mame_clones[canonical_name] = { + "sha1": sha1, + "clones": clone_names, + "total_copies": sum(len(by_name[n]) for n in clone_names), + } + for clone_name in clone_names: + for p in by_name[clone_name]: + true_dupes_to_remove.append(p) + else: + # Non-MAME different names (e.g., 64DD_IPL_US.n64 vs IPL_USA.n64) + # Keep ALL: each name may be needed by a different emulator + # Only remove true duplicates (same name in multiple dirs) + pass + + return true_dupes_to_remove diff --git a/scripts/collection/gitrestore.py b/scripts/collection/gitrestore.py new file mode 100644 index 000000000..a131008bd --- /dev/null +++ b/scripts/collection/gitrestore.py @@ -0,0 +1,59 @@ +"""What git records for a collection file, and restoring its bytes from the blob in HEAD.""" + +from __future__ import annotations + +import hashlib +import os +import subprocess +import tempfile +from pathlib import Path + +from core.hashing import git_blob_sha + + +class GitFailed(RuntimeError): + """A git command failed: its empty output says nothing about the file.""" + + +def git(root: Path, *args: str) -> subprocess.CompletedProcess: + """Run git in root. A failure raises: an unreadable index read as an empty + status made a session's working change look unmodified, and --apply wrote + HEAD's bytes over it.""" + done = subprocess.run(["git", "-C", str(root), *args], capture_output=True, check=False) + if done.returncode: + message = done.stderr.decode(errors="replace").strip() + raise GitFailed(f"git {' '.join(args)} exited {done.returncode}: {message}") + return done + + +def head_blob(root: Path, path: str) -> str: + """The blob HEAD records for path, empty when HEAD has none.""" + out = git(root, "ls-tree", "HEAD", "--", path).stdout.decode() + parts = out.split() + return parts[2] if len(parts) >= 3 and parts[1] == "blob" else "" + + +def modified_for_git(root: Path, path: str) -> bool: + return bool(git(root, "status", "--porcelain", "--", path).stdout.strip()) + + +def restore_from_blob(root: Path, path: str, blob: str, expected: str) -> str: + """Write the blob's bytes over path, after checking them. Empty on success.""" + data = git(root, "cat-file", "blob", blob).stdout + object_id = git_blob_sha(data) + if object_id != blob: + return f"blob read back as {object_id[:12]}, not {blob[:12]}" + if hashlib.sha1(data).hexdigest() != expected: + return "HEAD holds other bytes than database.json records" + target = root / path + handle, scratch = tempfile.mkstemp(dir=target.parent, prefix=f".{target.name}.") + try: + with os.fdopen(handle, "wb") as out: + out.write(data) + os.chmod(scratch, target.stat().st_mode & 0o777) + os.replace(scratch, target) + except OSError: + if os.path.exists(scratch): + os.unlink(scratch) + raise + return "" diff --git a/scripts/collection/integrity.py b/scripts/collection/integrity.py new file mode 100644 index 000000000..0e8e61328 --- /dev/null +++ b/scripts/collection/integrity.py @@ -0,0 +1,105 @@ +"""Every file database.json names, hashed again, each confirmed bit flip repaired or flagged.""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field +from pathlib import Path + +from collection.gitrestore import head_blob, modified_for_git, restore_from_blob +from core.hashing import file_digest +from model.largefiles import load_registered_paths + +MISREAD = "misread" +RESTORED = "restored" +FLAGGED = "flagged" +SKIPPED = "skipped" + + +@dataclass(frozen=True) +class Finding: + path: str + verdict: str # misread, restored, flagged, skipped + reason: str + expected: str + found: str = "" + + +@dataclass +class Report: + checked: int = 0 + findings: list[Finding] = field(default_factory=list) + + def counts(self) -> dict[str, int]: + counts: dict[str, int] = {} + for f in self.findings: + counts[f.verdict] = counts.get(f.verdict, 0) + 1 + return counts + + def as_dict(self) -> dict: + return { + "checked": self.checked, + "counts": self.counts(), + "findings": [f.__dict__ for f in self.findings], + } + + @property + def clean(self) -> bool: + return all(f.verdict in (MISREAD, RESTORED) for f in self.findings) + + +def check( + root: Path, + db: dict, + apply: bool, + hasher: Callable[[Path], str] = file_digest, +) -> Report: + """Hash every database path, confirm each mismatch, repair what may be.""" + ignored = set(load_registered_paths(root / ".gitignore")) + report = Report() + for key, entry in sorted(db.get("files", {}).items(), key=lambda kv: kv[1]["path"]): + path = entry["path"] + expected = str(entry.get("sha1") or key).lower() + local = root / path + if not local.is_file(): + continue # a release asset not fetched yet, verify reports it + report.checked += 1 + first = hasher(local) + if first == expected: + continue + second = hasher(local) + if second != first: + verdict = MISREAD if second == expected else FLAGGED + report.findings.append(Finding( + path, verdict, f"two reads disagree ({first[:12]}, {second[:12]})", + expected, second)) + continue + if path in ignored: + report.findings.append(Finding( + path, FLAGGED, "gitignored large file, never repaired here", expected, first)) + continue + blob = head_blob(root, path) + if not blob: + report.findings.append(Finding(path, FLAGGED, "not in HEAD", expected, first)) + continue + if modified_for_git(root, path): + report.findings.append(Finding( + path, SKIPPED, "modified for git: a working change, left alone", + expected, first)) + continue + if not apply: + report.findings.append(Finding( + path, FLAGGED, "bit flip, restorable from HEAD with --apply", expected, first)) + continue + problem = restore_from_blob(root, path, blob, expected) + if problem: + report.findings.append(Finding(path, FLAGGED, problem, expected, first)) + continue + after = hasher(local) + if after == expected: + report.findings.append(Finding( + path, RESTORED, f"restored from blob {blob[:12]}", expected, first)) + else: + report.findings.append(Finding( + path, FLAGGED, f"restored but reads {after[:12]}", expected, after)) + return report diff --git a/scripts/dedup.py b/scripts/dedup.py index bc8d13db7..3661f6468 100644 --- a/scripts/dedup.py +++ b/scripts/dedup.py @@ -21,330 +21,12 @@ After dedup, run generate_db.py --force to rebuild database indexes. from __future__ import annotations import argparse -import json import os import sys -from collections import defaultdict -from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from core.hashing import compute_hashes -from core.sizes import size_text +from collection.dedup import deduplicate from core.cli import add_repo_inputs, require_directory -from core.artifacts import write_text_atomic -from model.nodedup import in_nodedup_dir - - -def path_priority(path: str) -> tuple: - """Lower score = better candidate to keep as canonical. - - Prefers: shorter path, non-variant, non-MAME (system-specific over generic). - """ - parts = Path(path).parts - is_variant = ".variants" in parts - is_mame = "MAME" in parts - is_arcade = "Arcade" in parts - return (is_variant, is_mame, is_arcade, len(parts), path) - - -def _is_mame_dir(path: str) -> bool: - """Check if a path is in a MAME-specific directory.""" - parts = Path(path).parts - return "MAME" in parts or "Arcade" in parts - - -def scan_duplicates(bios_dir: str) -> dict[str, list[str]]: - """Files grouped by SHA1, excluding no-dedup directories. - - Two equal files have the same size, so only files that share a size are - read, and for the sha1 alone: hashing the whole tree with every digest - took 33 s for a scan that reads a quarter of it. A file alone at its - size is in no group of two and is left out. - """ - by_size: dict[int, list[str]] = defaultdict(list) - for root, _dirs, files in os.walk(bios_dir): - for name in files: - path = os.path.join(root, name) - if in_nodedup_dir(path): - continue - by_size[os.path.getsize(path)].append(path) - - sha1_to_paths: dict[str, list[str]] = defaultdict(list) - for paths in by_size.values(): - if len(paths) < 2: - continue - for path in paths: - sha1_to_paths[compute_hashes(path, frozenset({"sha1"}))["sha1"]].append(path) - return sha1_to_paths - - -def _plan_group_removals( - sha1: str, paths: list[str], mame_clones: dict -) -> list[str]: - """Decide which copies of one content hash may go. - - Two files with the same content are not automatically interchangeable. - Same name in different directories is a true duplicate. Different names - are only collapsible when they are MAME device clones, which is why the - check is narrowed to zips under a MAME directory: anywhere else each - name may be the one some emulator looks for. - - Records clone groups in *mame_clones* and returns the paths to remove. - """ - true_dupes_to_remove: list[str] = [] - # Separate by filename: same name = true duplicate, different name = clone - by_name: dict[str, list[str]] = defaultdict(list) - for p in paths: - by_name[os.path.basename(p)].append(p) - - # True duplicates: same filename in multiple directories - true_dupes_to_remove = [] - for name_paths in by_name.values(): - if len(name_paths) > 1: - name_paths.sort(key=path_priority) - true_dupes_to_remove.extend(name_paths[1:]) - - # A variant exists to hold a content its primary does not. Once another - # file holds the same bytes, the copy under .variants/ answers nothing - # the index does not already know, whatever its name or suffix: the - # resolver finds the content by hash and writes it under the name the - # destination asks for. - remaining = [p for p in paths if p not in true_dupes_to_remove] - variants = [p for p in remaining if ".variants" in Path(p).parts] - if variants: - holders = [p for p in remaining if p not in variants] or [ - min(variants, key=path_priority) - ] - true_dupes_to_remove.extend(p for p in variants if p not in holders) - - # Different filenames, same content: need special handling - unique_names = sorted(by_name.keys()) - if len(unique_names) > 1: - # Check if these are all in MAME/Arcade dirs AND all ZIPs - all_mame_zip = all( - any(_is_mame_dir(p) for p in name_paths) - for name_paths in by_name.values() - ) and all(n.endswith(".zip") for n in unique_names) - if all_mame_zip: - # MAME device clones: different ZIP names, same ROM content - # Keep one canonical, remove clones, record in clone map - canonical_name = min(unique_names, key=len) - clone_names = sorted(n for n in unique_names if n != canonical_name) - if clone_names: - mame_clones[canonical_name] = { - "sha1": sha1, - "clones": clone_names, - "total_copies": sum(len(by_name[n]) for n in clone_names), - } - for clone_name in clone_names: - for p in by_name[clone_name]: - true_dupes_to_remove.append(p) - else: - # Non-MAME different names (e.g., 64DD_IPL_US.n64 vs IPL_USA.n64) - # Keep ALL: each name may be needed by a different emulator - # Only remove true duplicates (same name in multiple dirs) - pass - - return true_dupes_to_remove - - -def _read_clone_map(clone_path: str) -> object: - """The clone map an earlier run wrote, {} when there is none.""" - # Read before anything is removed: the map is cumulative, and a run that - # stopped on an unreadable one after deleting clones would lose them. - try: - with open(clone_path) as f: - return json.load(f) - except FileNotFoundError: - return {} - except json.JSONDecodeError as e: - raise SystemExit( - f"{clone_path} is not valid JSON ({e}). Restore it from git " - "before deduplicating again" - ) from e - - -def _remove_copies(canonical: str, true_dupes_to_remove: list[str], dry_run: bool) -> list[str]: - """Remove (or name, in a dry run) each copy beside the canonical file.""" - removed: list[str] = [] - for dup in true_dupes_to_remove: - if dup == canonical: - continue - if not os.path.exists(dup): - continue - if dry_run: - print(f" WOULD REMOVE: {dup}") - else: - try: - os.remove(dup) - except OSError as e: - print(f" WARNING: cannot remove {dup}: {e}") - continue - # Clean up empty .variants/ directories - parent = os.path.dirname(dup) - if os.path.basename(parent) == ".variants" and not os.listdir(parent): - os.rmdir(parent) - removed.append(dup) - return removed - - -def _settle_group(paths: list[str], true_dupes_to_remove: list[str], dry_run: bool) -> dict: - """Keep the best copy of one content and remove the others.""" - # Find the best canonical across all paths - all_paths = [p for p in paths if p not in true_dupes_to_remove] - if not all_paths: - # All copies were marked for removal: keep the best one - all_paths_sorted = sorted(paths, key=path_priority) - all_paths = [all_paths_sorted[0]] - true_dupes_to_remove = [p for p in paths if p != all_paths[0]] - - canonical = sorted(all_paths, key=path_priority)[0] - canonical_name = os.path.basename(canonical) - - all_names = set(os.path.basename(p) for p in paths) - alias_names = sorted(all_names - {canonical_name}) - - size = os.path.getsize(canonical) - removed = _remove_copies(canonical, true_dupes_to_remove, dry_run) - - if alias_names or true_dupes_to_remove: - action = "Would remove" if dry_run else "Removed" - dn = os.path.basename(canonical) - print(f" {dn} (keep: {canonical})") - if true_dupes_to_remove: - print(f" {action} {len(true_dupes_to_remove)} copies") - if alias_names: - print(f" MAME clones: {alias_names}") - return { - "canonical": canonical, - "removed": removed, - "aliases": alias_names, - "saved": size * len(removed), - } - - -def _remove_empty_dirs(bios_dir: str) -> int: - """Remove the directories the removals left empty, bottom up.""" - empty_cleaned = 0 - for root, dirs, files in os.walk(bios_dir, topdown=False): - if not files and not dirs and root != bios_dir: - os.rmdir(root) - empty_cleaned += 1 - return empty_cleaned - - -def _record_clone_map( - mame_clones: dict[str, dict], previous: object, clone_path: str, dry_run: bool -) -> None: - """Write the clone map, merged with what earlier runs recorded.""" - # A group is only visible while both copies are on disk, and this run - # has just deleted the clone. Writing only what was seen this time - # therefore erases every mapping an earlier run recorded, and the - # canonical zip stops answering to the names it stands in for. The - # older entries stay valid: their canonical file is still here. - if not dry_run and isinstance(previous, dict): - merged = dict(previous) - merged.update(mame_clones) - mame_clones = collapse_clone_chains(merged) - if dry_run: - print(f"\nWould write MAME clone map: {clone_path}") - else: - write_text_atomic(clone_path, json.dumps(mame_clones, indent=2, sort_keys=True)) - print(f"\nWrote MAME clone map: {clone_path}") - print( - f" {len(mame_clones)} canonical ZIPs with " - f"{sum(len(v['clones']) for v in mame_clones.values())} clones" - ) - - -def deduplicate(bios_dir: str, dry_run: bool = False) -> dict: - """Remove true duplicates, map MAME device clones. - - True duplicates (same name, different dirs): removes copies. - MAME clones (different names, same content, same dir): creates mapping. - - Returns dict of {sha1: {"canonical": path, "removed": [paths], "aliases": [names]}} - """ - # Beside the scanned tree, where get_mame_clone_map() reads it for - # the real layout. A path relative to the working directory let a - # scan of a fixture tree rewrite the repository's own map. - clone_path = os.path.join( - os.path.dirname(os.path.abspath(bios_dir)), "_mame_clones.json" - ) - previous = _read_clone_map(clone_path) - - sha1_groups = scan_duplicates(bios_dir) - results: dict[str, dict] = {} - total_removed = 0 - total_saved = 0 - mame_clones: dict[str, dict] = {} # canonical_name -> {sha1, clones: [names]} - - for sha1, paths in sorted(sha1_groups.items()): - if len(paths) <= 1: - continue - - true_dupes_to_remove = _plan_group_removals(sha1, paths, mame_clones) - - if not true_dupes_to_remove: - continue - - settled = _settle_group(paths, true_dupes_to_remove, dry_run) - total_removed += len(settled["removed"]) - total_saved += settled.pop("saved") - results[sha1] = settled - - # Clean up empty directories - empty_cleaned = 0 if dry_run else _remove_empty_dirs(bios_dir) - - prefix = "Would remove" if dry_run else "Removed" - print(f"\n{prefix}: {total_removed} files") - print( - f"Space {'to save' if dry_run else 'saved'}: {size_text(total_saved)}" - ) - if not dry_run and empty_cleaned: - print(f"Cleaned {empty_cleaned} empty directories") - - if mame_clones: - _record_clone_map(mame_clones, previous, clone_path, dry_run) - - return results - - -def collapse_clone_chains(clone_map: dict[str, dict]) -> dict[str, dict]: - """Point every clone at a canonical archive that still exists. - - The map is cumulative. When a later run finds that a canonical archive is - itself a byte-identical copy of another and removes it, the entry that - named it as canonical would send its clones to a file that is gone: - sys68k_cpu21a pointed at sys68k_cpu21 after sys68k_cpu21 became a clone - of sys68k_cpu20. Each such entry's clones move to the final canonical. - """ - owner = { - clone: canonical - for canonical, entry in clone_map.items() - for clone in entry.get("clones", []) - } - - def final(name: str) -> str: - seen = {name} - while name in owner: - name = owner[name] - if name in seen: - raise ValueError(f"clone map loops through {name}") - seen.add(name) - return name - - collapsed: dict[str, dict] = {} - for canonical, entry in clone_map.items(): - target = final(canonical) - kept = collapsed.setdefault(target, {**clone_map.get(target, entry), "clones": []}) - names = set(kept["clones"]) | set(entry.get("clones", [])) - if target != canonical: - names.add(canonical) - names.discard(target) - kept["clones"] = sorted(names) - kept["total_copies"] = len(kept["clones"]) - return collapsed def main() -> None: diff --git a/tests/sources.py b/tests/sources.py index b02a231b8..a144cab43 100644 --- a/tests/sources.py +++ b/tests/sources.py @@ -35,6 +35,10 @@ COMMANDS = { "collection/scan.py", "collection/hashcache.py", "collection/releaseassets.py", "collection/declared.py", "collection/aliases.py", "collection/indexes.py", "collection/record.py", ), + "dedup.py": ( + "model/nodedup.py", "collection/dedup.py", "collection/duplicates.py", + "collection/clonemap.py", + "bios_integrity.py": ("collection/integrity.py", "collection/gitrestore.py"), "release_record.py": ("model/releaserecord.py", "release/record.py"), "release_notes.py": ("release/notes.py",), "check_release.py": ("release/check.py",), diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index e2b1b8699..7fe235591 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -3732,7 +3732,7 @@ class GeneratedModelsAreWrittenWhole(unittest.TestCase): self.assertNotIn('open(clone_path, "w")', source) def test_an_unreadable_clone_map_stops_the_run(self): - from scripts import dedup + from collection import dedup with tempfile.TemporaryDirectory() as directory: root = Path(directory) diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 4771971ad..04cb3a7d3 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -32,7 +32,8 @@ from core import childenv from core.hashing import file_digest from core import hostguard from core import statefile -import bios_integrity as bib +from collection import integrity as bib +from collection.gitrestore import GitFailed import cleanup_disk as cd from release import sync @@ -906,7 +907,7 @@ class BiosIntegrity(Scratch): rel = "bios/Sony/edited.bin" (self.repo / rel).write_bytes(b"\x02" * 80) (self.repo / ".git" / "index").write_bytes(b"garbage\n") - with self.assertRaises(bib.GitFailed): + with self.assertRaises(GitFailed): bib.check(self.repo, self.db, apply=True) self.assertEqual((self.repo / rel).read_bytes(), b"\x02" * 80) diff --git a/tests/test_dedup.py b/tests/test_dedup.py index da2bd1942..5fde4eb7a 100644 --- a/tests/test_dedup.py +++ b/tests/test_dedup.py @@ -18,7 +18,7 @@ import tempfile import unittest from pathlib import Path -import dedup +from collection import clonemap, dedup, duplicates from model import nodedup @@ -277,13 +277,13 @@ class CloneMapSurvivesASecondRun(_Bios): class PathPriority(unittest.TestCase): def test_shorter_paths_sort_first(self): - short = dedup.path_priority("bios/Sony/PS/a.bin") - deep = dedup.path_priority("bios/Sony/PS/x/y/z/a.bin") + short = duplicates.path_priority("bios/Sony/PS/a.bin") + deep = duplicates.path_priority("bios/Sony/PS/x/y/z/a.bin") self.assertLess(short, deep) def test_a_variant_sorts_after_a_primary(self): - primary = dedup.path_priority("bios/Sony/PS/a.bin") - variant = dedup.path_priority("bios/Sony/PS/.variants/a.bin") + primary = duplicates.path_priority("bios/Sony/PS/a.bin") + variant = duplicates.path_priority("bios/Sony/PS/.variants/a.bin") self.assertLess(primary, variant) def test_protected_directories_are_recognised(self): @@ -321,14 +321,14 @@ class OnlyFilesSharingASizeAreHashed(_Bios): self.write("C/other.bin", b"a payload of its own length") self.write("D/same_size.bin", b"IDENTICAL PAYLOAX") calls: list[tuple[str, frozenset | None]] = [] - real = dedup.compute_hashes + real = duplicates.compute_hashes def spy(path, algorithms=None, cache=True): calls.append((os.path.relpath(path, self.bios), algorithms)) return real(path, algorithms, cache) - with mock.patch.object(dedup, "compute_hashes", spy): - groups = dedup.scan_duplicates(str(self.bios)) + with mock.patch.object(duplicates, "compute_hashes", spy): + groups = duplicates.scan_duplicates(str(self.bios)) self.assertEqual( sorted(path for path, _algos in calls), sorted(os.path.join(*p.split("/")) for p in ("A/one.bin", "B/one.bin", "D/same_size.bin")), @@ -347,23 +347,19 @@ class CloneChainsCollapse(unittest.TestCase): pointed at a file that no longer existed.""" def test_clones_follow_to_the_canonical_that_exists(self): - import dedup - chain = { "cpu20.zip": {"clones": ["cpu21.zip"], "sha1": "a", "total_copies": 1}, "cpu21.zip": {"clones": ["cpu21a.zip", "cpu21b.zip"], "sha1": "a", "total_copies": 2}, } - self.assertEqual(dedup.collapse_clone_chains(chain), { + self.assertEqual(clonemap.collapse_clone_chains(chain), { "cpu20.zip": {"clones": ["cpu21.zip", "cpu21a.zip", "cpu21b.zip"], "sha1": "a", "total_copies": 3}, }) def test_a_loop_is_refused(self): - import dedup - loop = {"a.zip": {"clones": ["b.zip"]}, "b.zip": {"clones": ["a.zip"]}} with self.assertRaises(ValueError): - dedup.collapse_clone_chains(loop) + clonemap.collapse_clone_chains(loop) if __name__ == "__main__": diff --git a/tests/test_layers.py b/tests/test_layers.py index 2b5dd6f62..9c4e5b1b6 100644 --- a/tests/test_layers.py +++ b/tests/test_layers.py @@ -29,6 +29,7 @@ COMMAND_LAYER = 4 SIBLING_IMPORTS: dict[str, frozenset[str]] = { # A search starts from what verify finds missing. "acquire": frozenset({"packs"}), + "collection": frozenset(), "packs": frozenset(), # A campaign commits its findings the way the unattended jobs commit. "probes": frozenset({"unattended"}), diff --git a/wiki/architecture.md b/wiki/architecture.md index 1fa5b2d60..4d4fc6a94 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -39,6 +39,7 @@ scripts/ all tooling (Python and pyyaml, jsonschema for schema c model/ data loading: database, platforms, registry, profiles, targets, catalogues resolve/ from declarations to files: content checks, resolution, layouts, cores, truth packs/ pack building and verification: selection, archives, manifests, coverage + collection/ upkeep of bios/: duplicates, the MAME clone map, bit flips found and repaired profiling/ emulator profiles confronted with their upstream source (profile_sync.py) collection/ the scan of bios/ into database.json: digests, aliases, indexes romrecipes/ romset identification, rebuilt pinned archives, each archive's recipe