fix: read catalog coverage under the database

This commit is contained in:
Abdessamad Derraz committed 2026-11-24 02:19:13 +01:00
1 parent b350c21329
commit 02c33be3b5
16 files changed
+129 -52

No files matched your search

+1
View File
@@ -50,6 +50,7 @@ on:
- "scripts/model/collection.py"
- "scripts/model/composition.py"
- "scripts/model/database.py"
- "scripts/model/dbpaths.py"
- "scripts/model/declarations.py"
- "scripts/model/dumpcatalog.py"
- "scripts/model/exportchanges.py"
+27 -22
View File
@@ -13,12 +13,13 @@ from __future__ import annotations
import array
import functools
import hashlib
import os
import zipfile
from collections import defaultdict
from collections.abc import Callable, Iterable, Sequence
from pathlib import Path
from core.ziptools import is_archive_path, zip_members
from model.dbpaths import on_disk
# A held file larger than this is not read: no chip image is near it.
MAX_SOURCE_SIZE = 64 * 1024 * 1024
@@ -117,53 +118,56 @@ def _shift_operator(len2: int) -> tuple[int, ...]:
return tuple(columns)
def _read(held: dict, archives: dict[str, zipfile.ZipFile] | None = None) -> bytes | None:
def _read(held: dict, archives: dict[Path, zipfile.ZipFile] | None = None) -> bytes | None:
"""The bytes of a held file, or of a member read out of its archive.
`archives` keeps each archive open across its members: reopened for
every one, a MAME set of a hundred chips parsed its directory a
hundred times.
hundred times. `file` is where the bytes sit on disk, the archive for a
member, and `path` the name the database gives them.
"""
try:
if held.get("member"):
if archives is None:
with zipfile.ZipFile(held["archive"]) as zf:
with zipfile.ZipFile(held["file"]) as zf:
return zf.read(held["member"])
opened = archives.get(held["archive"])
opened = archives.get(held["file"])
if opened is None:
opened = archives[held["archive"]] = zipfile.ZipFile(held["archive"])
opened = archives[held["file"]] = zipfile.ZipFile(held["file"])
return opened.read(held["member"])
with open(held["path"], "rb") as handle:
with open(held["file"], "rb") as handle:
return handle.read()
except (OSError, KeyError, zipfile.BadZipFile):
return None
def _held_sources(db: dict) -> list[dict]:
def _held_sources(db: dict, root: Path) -> list[dict]:
"""Every file the collection holds, the members of its archives included.
A romset holds chips a catalog lists on their own: cdi910.rom inside
cdi910.zip is the CD-i 910 BIOS byte-swapped, and the two halves of the
Salora Manager sit in manager.zip. Read from the top level alone, they
stayed MISSING. A member's group is its archive, as a file's is its
directory: the pairs a catalog splits come from one machine.
directory: the pairs a catalog splits come from one machine. Paths are
read under *root*, the database's own folder.
"""
sources: list[dict] = []
for record in db.get("files", {}).values():
path = record.get("path", "")
if not os.path.exists(path):
file = on_disk(root, path)
if not file.exists():
continue
if 0 < record.get("size", 0) <= MAX_SOURCE_SIZE:
sources.append({**record, "group": os.path.dirname(path)})
sources.append({**record, "file": file, "group": str(Path(path).parent)})
if not is_archive_path(path):
continue
try:
members = zip_members(path)
members = zip_members(file)
except (OSError, zipfile.BadZipFile):
continue
sources.extend(
{
"path": f"{path}/{member.name}", "archive": path,
"path": f"{path}/{member.name}", "file": file,
"member": member.name, "size": member.size,
"crc32": member.crc32, "group": path,
}
@@ -173,19 +177,20 @@ def _held_sources(db: dict) -> list[dict]:
return sources
def derivable(entries: Iterable[dict], db: dict) -> dict[str, dict]:
def derivable(entries: Iterable[dict], db: dict, root: Path) -> dict[str, dict]:
"""Missing sha1 to the held file or member and the transform that
produce its bytes. Archives stay open for the whole pass."""
archives: dict[str, zipfile.ZipFile] = {}
produce its bytes, the database's paths read under *root*. Archives
stay open for the whole pass."""
archives: dict[Path, zipfile.ZipFile] = {}
try:
return _derivable(entries, db, archives)
return _derivable(entries, db, root, archives)
finally:
for zf in archives.values():
zf.close()
def _derivable(
entries: Iterable[dict], db: dict, archives: dict[str, zipfile.ZipFile]
entries: Iterable[dict], db: dict, root: Path, archives: dict[Path, zipfile.ZipFile]
) -> dict[str, dict]:
"""Only held files whose size can produce a wanted size are read, and a
concatenation is only tried within one directory or one archive: the
@@ -203,7 +208,7 @@ def _derivable(
sizes = {size for size, _sha1 in wanted}
found: dict[str, dict] = {}
files = _held_sources(db)
files = _held_sources(db, root)
_find_transformed(files, wanted, sizes, archives, found)
_find_concatenated(files, by_size_crc, sizes, archives, found)
return found
@@ -213,7 +218,7 @@ def _find_transformed(
files: list[dict],
wanted: dict[tuple[int, str], str],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
archives: dict[Path, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 one transform of a held file produces."""
@@ -247,7 +252,7 @@ def _find_concatenated(
files: list[dict],
by_size_crc: dict[tuple[int, int], list[str]],
sizes: set[int],
archives: dict[str, zipfile.ZipFile],
archives: dict[Path, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record each wanted sha1 two held files of one group make end to end."""
@@ -280,7 +285,7 @@ def _try_pair(
total: int,
combined: dict[tuple[str, str, int], int],
by_size_crc: dict[tuple[int, int], list[str]],
archives: dict[str, zipfile.ZipFile],
archives: dict[Path, zipfile.ZipFile],
found: dict[str, dict],
) -> None:
"""Record the wanted sha1 first + second makes, if their crc names one."""
+17 -12
View File
@@ -4,7 +4,6 @@ from __future__ import annotations
import hashlib
import json
import os
import sys
import zipfile
from pathlib import Path
@@ -12,6 +11,7 @@ from pathlib import Path
from core.hashing import parse_hash_list
from core.paths import REPO_ROOT
from core.ziptools import is_archive_path, zip_members
from model.dbpaths import on_disk
from resolve.content import size_fits
from resolve.validation import installed_everywhere
@@ -124,22 +124,28 @@ def needs_filled(entry: dict, needs: dict) -> list[dict]:
return sorted(found.values(), key=lambda n: (not n["required"], n["emulator"], n["name"]))
def archive_members(db: dict) -> dict[tuple[str, int], list[tuple[str, str]]]:
def archive_members(db: dict, root: Path) -> dict[tuple[str, int], list[tuple[str, str]]]:
"""(crc32, size) of every member of the collection's ZIPs -> (zip, member).
Read from the central directories alone: a romset member is a dump the
collection already holds, and listing it as an acquisition target sent
searches after astrocdw.zip's bioswhit.bin and the Gamate BIOS.
searches after astrocdw.zip's bioswhit.bin and the Gamate BIOS. *root* is
the folder the database's paths are relative to, never the working
directory: the site read another tree's archives for a collection named
by --db.
"""
members: dict[tuple[str, int], list[tuple[str, str]]] = {}
for entry in db.get("files", {}).values():
path = entry.get("path", "")
if not is_archive_path(path) or not os.path.exists(path):
if not is_archive_path(path):
continue
file = on_disk(root, path)
if not file.exists():
continue
try:
for member in zip_members(path):
for member in zip_members(file):
key = (member.crc32, member.size)
members.setdefault(key, []).append((path, member.name))
members.setdefault(key, []).append((str(file), member.name))
except (zipfile.BadZipFile, OSError) as exc:
print(f" WARNING: {path}: {exc}", file=sys.stderr)
return members
@@ -169,10 +175,7 @@ def _held_in_archive(entry: dict, members: dict) -> bool:
return False
RECIPES_DIR = REPO_ROOT / "recipes"
def romset_index(recipes_dir: Path = RECIPES_DIR) -> dict[tuple[str, int], list[dict]]:
def romset_index(recipes_dir: Path) -> dict[tuple[str, int], list[dict]]:
"""(crc32, size) of every member of an imported romset -> where it sits.
A dump the collection lacks may still ship inside an emulator's romset:
@@ -244,6 +247,7 @@ def build_report(
members: dict | None = None,
romsets: dict | None = None,
needs: dict | None = None,
root: Path = REPO_ROOT,
) -> dict:
"""Compare each snapshot against the collection.
@@ -253,13 +257,14 @@ def build_report(
all are out of scope and only counted. No-Intro tags every non-game
dump "[BIOS]", including digital title distribution, so without this
split the target list is swamped by content the project never ships.
Archives and recipes are read under *root*, the database's own folder.
"""
by_sha1 = db.get("files", {})
# The members a romset holds are held too, whoever asks: the site built
# its Wanted page without them and asked the public for the Astrocade
# and Gamate BIOS that astrocdw.zip and gamate.zip already carry.
members = archive_members(db) if members is None else members
romsets = romset_index() if romsets is None else romsets
members = archive_members(db, root) if members is None else members
romsets = romset_index(root / "recipes") if romsets is None else romsets
by_md5_size = {
(entry.get("md5", ""), entry.get("size", 0)) for entry in by_sha1.values()
}
File renamed without changes.
+2 -1
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from core.paths import REPO_ROOT
from model import releaserecord
from model.dbpaths import on_disk
@dataclass(frozen=True)
@@ -48,7 +49,7 @@ def bios_dir(db: dict) -> Path:
def collection_path(rel: str) -> Path:
"""A path database.json names, under the database's own folder."""
return current().db.parent / rel
return on_disk(current().db.parent, rel)
def manifests_dir() -> Path:
+5 -2
View File
@@ -22,6 +22,7 @@ import argparse
import json
import os
import sys
from pathlib import Path
sys.path.insert(0, os.path.dirname(__file__))
from core.cli import add_repo_inputs
@@ -79,13 +80,15 @@ def main() -> int:
print(f"No provenance snapshots in {args.provenance_dir}/")
return 0
# The database's paths and its recipes sit under its own folder.
root = Path(args.db).resolve().parent
needs = profile_needs(load_emulator_profiles(args.emulators_dir), db)
report = build_report(db, snapshots, archive_members(db), needs=needs)
report = build_report(db, snapshots, archive_members(db, root), needs=needs, root=root)
derived: dict[str, dict] = {}
if args.derive:
from acquire.derivations import derivable
derived = derivable((e for d in report.values() for e in d["missing"]), db)
derived = derivable((e for d in report.values() for e in d["missing"]), db, root)
for data in report.values():
data["derivable"] = {
e["sha1"]: derived[e["sha1"]] for e in data["missing"]
+1 -1
View File
@@ -11,7 +11,7 @@ from pathlib import Path
from core.hashing import compute_hashes
from core.torrentzip import write_torrentzip, zlib_ng_version
from core.ziptools import is_archive_path, zip_members
from romrecipes.collection import on_disk
from model.dbpaths import on_disk
from romrecipes.members import member_sha1, member_opener
+1 -1
View File
@@ -13,7 +13,7 @@ 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.collection import on_disk
from model.dbpaths import on_disk
from romrecipes.ledger import database_archives, load_ledger, write_ledger
from romrecipes.members import member_sha1, member_opener
from romrecipes.pins import container_entries
+1 -1
View File
@@ -10,7 +10,7 @@ from pathlib import Path
from core.torrentzip import is_torrentzip
from core.ziptools import zip_members
from romrecipes.collection import on_disk
from model.dbpaths import on_disk
from romrecipes.pins import container_entries
from romrecipes.pool import AtomPool
from romrecipes.romsets import Recipe
+1 -1
View File
@@ -11,7 +11,7 @@ from pathlib import Path
from core.paths import REPO_ROOT
from core.torrentzip import build_torrentzip, writer_identity, zlib_ng_version
from core.ziptools import is_archive_path, zip_members
from romrecipes.collection import collection_root, on_disk
from model.dbpaths import collection_root, on_disk
from romrecipes.romsets import Recipe
+1 -1
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from core.torrentzip import zlib_ng_version
from romrecipes.build import AtomIndex, BuildTally, build_records, build_targets
from romrecipes.capture import ZlibNgError, capture_ledger
from romrecipes.collection import collection_root
from model.dbpaths import collection_root
from romrecipes.ledger import load_ledger
from romrecipes.text import print_build_result, print_build_totals, print_capture
+2 -1
View File
@@ -670,7 +670,8 @@ def generate_site(args: argparse.Namespace) -> None:
# Built once, the derivable dumps taken out once: the provenance page and
# the CSV it links to must list the same dumps.
dumps = wanted_dumps(
build_report(db, load_provenance_snapshots(), needs=profile_needs(profiles, db)),
build_report(db, load_provenance_snapshots(), needs=profile_needs(profiles, db),
root=siteinputs.current().db.parent),
load_derivable(),
)
+1 -1
View File
@@ -102,7 +102,7 @@ COMMANDS = {
"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", "romrecipes/runs.py", "romrecipes/collection.py",
"romrecipes/text.py", "romrecipes/runs.py",
),
"provenance_report.py": ("acquire/provenance.py",),
"auto_fetch.py": ("acquire/fetch.py", "acquire/fetchtext.py", "acquire/placement.py"),
+1 -1
View File
@@ -4898,7 +4898,7 @@ class TheWantedPageCountsRomsetMembers(unittest.TestCase):
calls = []
def members(db):
def members(db, root):
calls.append(db)
return {}
+32 -5
View File
@@ -48,7 +48,7 @@ class HeldDumpsAnswerCatalogEntries(unittest.TestCase):
image = os.urandom(64)
db = {"files": {"x": _held(self.tmp / "kick.rom", image)}}
high = derivations._swap16(derivations._words(image, 0))
found = derivations.derivable([_wanted(high)], db)
found = derivations.derivable([_wanted(high)], db, self.tmp)
self.assertEqual(found[hashlib.sha1(high).hexdigest()]["transform"],
"even words, byte-swapped")
@@ -56,16 +56,43 @@ class HeldDumpsAnswerCatalogEntries(unittest.TestCase):
low, high = os.urandom(32), os.urandom(32)
db = {"files": {"a": _held(self.tmp / "basiclo.bin", low),
"b": _held(self.tmp / "basichi.bin", high)}}
found = derivations.derivable([_wanted(low + high)], db)
found = derivations.derivable([_wanted(low + high)], db, self.tmp)
self.assertEqual(found[hashlib.sha1(low + high).hexdigest()]["from"],
[str(self.tmp / "basiclo.bin"), str(self.tmp / "basichi.bin")])
def test_unrelated_bytes_are_not_claimed(self):
db = {"files": {"a": _held(self.tmp / "a.bin", os.urandom(64))}}
self.assertEqual(derivations.derivable([_wanted(os.urandom(32))], db), {})
self.assertEqual(derivations.derivable([_wanted(os.urandom(32))], db, self.tmp), {})
class PathsAreReadUnderTheCollection(unittest.TestCase):
"""provenance_report --db tmp/x/database.json --derive moved to the
repository root, then read the database's relative paths from there: the
checkout's bios/, not the collection the run named."""
def test_a_relative_path_is_read_under_the_root_not_the_working_directory(self):
import zipfile
root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, root, True)
chip, image = os.urandom(64), os.urandom(32)
(root / "bios" / "X").mkdir(parents=True)
with zipfile.ZipFile(root / "bios" / "X" / "set.zip", "w") as zf:
zf.writestr("chip.rom", chip)
(root / "bios" / "X" / "loose.bin").write_bytes(image)
db = {"files": {
"a" * 40: {"path": "bios/X/set.zip", "size": 1},
"b" * 40: {"path": "bios/X/loose.bin", "size": len(image)},
}}
swapped, reversed_image = derivations._swap16(chip), derivations._swap16(image)
found = derivations.derivable([_wanted(swapped), _wanted(reversed_image)], db, root)
self.assertEqual(found[hashlib.sha1(swapped).hexdigest()]["from"],
["bios/X/set.zip/chip.rom"])
self.assertEqual(found[hashlib.sha1(reversed_image).hexdigest()]["from"],
["bios/X/loose.bin"])
class ARomsetMemberIsASource(unittest.TestCase):
"""cdi910.rom inside cdi910.zip is the CD-i 910 BIOS byte-swapped, and
manager.zip holds the two halves of the Salora Manager: read from the
@@ -86,7 +113,7 @@ class ARomsetMemberIsASource(unittest.TestCase):
swapped = derivations._swap16(chip)
found = derivations.derivable(
[_wanted(swapped), {**_wanted(low + high), "crc32": f"{zlib.crc32(low + high):08x}"}],
db,
db, root,
)
self.assertEqual(found[hashlib.sha1(swapped).hexdigest()]["transform"], "byte-swapped")
self.assertEqual(found[hashlib.sha1(low + high).hexdigest()]["transform"], "concatenated")
@@ -131,7 +158,7 @@ class OneContentIsTransformedOnce(unittest.TestCase):
transforms = tuple((name, size, counted(fn)) for name, size, fn in derivations.TRANSFORMS)
swapped = derivations._swap16(chip)
with unittest.mock.patch.object(derivations, "TRANSFORMS", transforms):
found = derivations.derivable([_wanted(swapped)], {"files": files})
found = derivations.derivable([_wanted(swapped)], {"files": files}, root)
self.assertEqual(found[hashlib.sha1(swapped).hexdigest()]["from"],
[f"{root / 'a.zip'}/chip.rom"])
useful = [t for t in transforms if t[1](len(chip)) == len(chip)]
+36 -2
View File
@@ -573,7 +573,7 @@ class ArchiveMembersAreHeld(unittest.TestCase):
}
wrong = dict(entry, name="other.bin", sha1="0" * 40)
snapshots = {"no-intro": {"entries": [entry, wrong]}}
report = build_report(db, snapshots, archive_members(db))
report = build_report(db, snapshots, archive_members(db, Path(tmp)))
self.assertEqual(report["no-intro"]["matched"], 1)
self.assertEqual([e["name"] for e in report["no-intro"]["missing"]], ["other.bin"])
@@ -586,10 +586,44 @@ class ArchiveMembersAreHeld(unittest.TestCase):
copy = Path(tmp) / "bbcm.zip.4cc3e25a"
with zipfile.ZipFile(copy, "w") as zf:
zf.writestr("mos.rom", b"mos")
members = archive_members({"files": {"z": {"path": str(copy)}}})
members = archive_members({"files": {"z": {"path": str(copy)}}}, Path(tmp))
self.assertEqual([m for ms in members.values() for _p, m in ms], ["mos.rom"])
class CollectionPathsAreReadUnderItsRoot(unittest.TestCase):
"""The site installs --db, then built the Wanted page from the archives
of the working directory's tree: a dump held in the named collection's
set.zip was listed missing."""
def test_members_and_recipes_come_from_the_root(self):
import hashlib
import zlib
from scripts.acquire import provenance as acquire_provenance
data = b"held" * 100
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
(root / "bios" / "X").mkdir(parents=True)
with zipfile.ZipFile(root / "bios" / "X" / "set.zip", "w") as zf:
zf.writestr("a.rom", data)
(root / "recipes").mkdir()
(root / "recipes" / "mame.json").write_text(json.dumps({"source": "mame", "entries": [
{"name": "other.zip", "dat": "mame0289", "members": [
{"name": "b.rom", "size": 5, "crc32": f"{zlib.crc32(b'other'):08x}"}]}]}),
encoding="utf-8")
db = {"files": {"s": {"path": "bios/X/set.zip", "md5": "x", "size": 1}}}
held = {"name": "held.bin", "dat": "D", "size": len(data),
"crc32": f"{zlib.crc32(data):08x}", "sha1": hashlib.sha1(data).hexdigest()}
other = {"name": "other.bin", "dat": "D", "size": 5,
"crc32": f"{zlib.crc32(b'other'):08x}"}
report = acquire_provenance.build_report(
db, {"no-intro": {"entries": [held, other]}}, root=root)
missing = report["no-intro"]["missing"]
self.assertEqual([e["name"] for e in missing], ["other.bin"])
self.assertEqual([h["archive"] for h in missing[0]["romsets"]], ["other.zip"])
class OneDumpIsCountedOnce(unittest.TestCase):
"""No-Intro's three FM-7 DATs each list DICROM.rom and KANJI.rom: the
report said 2 485 missing where 2 284 distinct dumps were missing, and