fix: one rule for the held file a hash names

The system index read sha1 and md5 only, the file lookup any index
with no size bound, the gap table any index unbounded. declared_records
in model.database follows the resolver: a crc32 names only a record of
the declared size, and beside a stronger hash only what it names.
systems.json gains 511 held files declared by sha256 or crc32, and 41
MAME members no longer point at Chihiro's ver1305.bin through the crc32
of an erased flash block.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 02:18:40 +01:00
1 parent f143a8719b
commit 40dadc5dcd
6 files changed
+98 -44

No files matched your search

+31
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import json
import os
from collections.abc import Iterable, Mapping
from pathlib import Path
from core.cli import InputMissing, SourceUnreadable
@@ -121,6 +122,36 @@ def records_for_hash(db: dict, kind: str, value: object) -> list[str]:
return [sha1 for sha1 in named if sha1 in files]
def declared_records(
db: dict, declared: Mapping[str, Iterable[str]], size: object = None,
) -> dict[tuple[str, str], list[str]]:
"""Each declared (algorithm, value) -> the sha1 of every held record it names.
``declared`` is an entry's hash lists by algorithm (declared_hash_lists).
A crc32 follows the resolver's rule (resolve_local_file): it names only
a record of the declared size, one value or a list of them, and beside
a stronger declared hash only a record that hash names too. An
algorithm the database has no index for (adler32) names nothing.
"""
files = db.get("files", {})
sizes = None if size is None else size if isinstance(size, list) else [size]
named: dict[tuple[str, str], list[str]] = {}
for algorithm in (a for a in declared if a == "sha1" or a in _HASH_INDEXES):
for value in declared[algorithm]:
named[(algorithm, value)] = records_for_hash(db, algorithm, value)
stronger = {sha1 for (algorithm, _v), found in named.items()
if algorithm != "crc32" for sha1 in found}
strong_declared = any(algorithm != "crc32" for algorithm, _v in named)
for pair, found in named.items():
if pair[0] == "crc32":
named[pair] = [
sha1 for sha1 in found
if (sizes is None or files[sha1].get("size") in sizes)
and (not strong_declared or sha1 in stronger)
]
return named
def record_for_hash(db: dict, kind: str, value: object) -> str | None:
"""The sha1 of the first held record one hash value names."""
return next(iter(records_for_hash(db, kind, value)), None)
+5 -7
View File
@@ -6,11 +6,11 @@ import urllib.parse
from collections.abc import Callable
from model.collection import group_by_manufacturer, manufacturer_slug
from model.database import sha1_at
from model.database import declared_records, sha1_at
from model.systemnames import system_name
from model.profiles import is_emulator
from sitegen.config import SITE_URL
from core.hashing import parse_hash_list
from core.hashing import declared_hash_lists
from sitegen.lookup import site_path
from sitegen.render import card_anchor
from sitegen.runlinks import console_href
@@ -30,7 +30,6 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
from sitegen.runlinks import card_page, system_section
files = db.get("files") or {}
by_md5 = (db.get("indexes") or {}).get("by_md5") or {}
held: dict[str, set[str]] = {}
for coverage in coverages.values():
for detail in coverage.get("details") or []:
@@ -48,10 +47,9 @@ def system_index_items(db: dict, coverages: dict, profiles: dict) -> list[dict]:
ids = ([str(entry["system"])] if entry.get("system")
else [str(s) for s in entry.get("systems") or []] or
(own if len(own) == 1 else []))
found = {v for v in parse_hash_list(entry.get("sha1")) if v in files}
for md5 in parse_hash_list(entry.get("md5")):
match = by_md5.get(md5)
found.update([match] if isinstance(match, str) else match or [])
found = {sha1 for named in declared_records(
db, declared_hash_lists(entry), entry.get("size")).values()
for sha1 in named}
for sys_id in ids:
held.setdefault(sys_id, set()).update(found)
manufacturers = {manufacturer_slug(mfr): mfr for mfr in group_by_manufacturer(db)}
+3 -13
View File
@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING
from core.hashing import declared_hash_lists
from core.text import series
from model.database import sha1_at
from model.database import declared_records, sha1_at
from model.platforms import native_layer
from packs.crossref import gap_source_counts, whole_tree_gaps
from resolve.nativemode import check_label
@@ -46,19 +46,9 @@ def _held_accepted(accepted: dict[str, list[str]], db: dict | None) -> str:
"""
if not accepted or not db:
return ""
indexes = db.get("indexes", {})
files = db.get("files", {})
for algo, values in accepted.items():
for value in values:
value = value.lower()
if algo == "sha1":
sha1 = value if value in files else None
else:
sha1 = indexes.get(f"by_{algo}", {}).get(value)
path = files.get(sha1 or "", {}).get("path")
if path:
return path
return ""
return next((path for named in declared_records(db, accepted).values()
for sha1 in named if (path := files[sha1].get("path"))), "")
def _declarations(cov: dict) -> dict[int, dict]:
+25 -22
View File
@@ -12,6 +12,7 @@ from pathlib import Path
from core.hashing import declared_hash_lists
from model import siteinputs
from model.collection import manufacturer_slug
from model.database import declared_records
from model.registry import load_versions, versions_file_for
from model.systemnames import system_name
from model.profiles import is_emulator
@@ -387,9 +388,18 @@ def _collection_lookup_records(
return records
def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) -> list[dict]:
def _designated(db: dict, holder: dict) -> dict[tuple[str, str], str]:
"""Each value an entry declares -> the one collection file it names,
by model.database.declared_records. A value naming several names none."""
named = declared_records(db, declared_hash_lists(holder, HASH_ALGORITHMS), holder.get("size"))
return {pair: found[0] for pair, found in named.items() if len(found) == 1}
def _platform_lookup_records(
coverages: dict, consumers: FileConsumers | None, db: dict,
) -> list[dict]:
"""A platform's declared values, each leading to the system section of
its page."""
its page, and to the collection file a value names."""
records: list[dict] = []
for key, coverage in sorted(coverages.items()):
for system_id, system in sorted((coverage["config"].get("systems") or {}).items()):
@@ -400,17 +410,20 @@ def _platform_lookup_records(coverages: dict, consumers: FileConsumers | None) -
# no collection file by itself: the archive holding it is the one.
archive = (consumers.sha1_of(entry)
if consumers is not None and entry.get("zipped_file") else None)
designated = _designated(db, entry)
records.extend({
"value": value, "algorithm": algorithm, "layer": "platform",
"owner": key, "name": str(entry.get("name", "")), "url": url,
**({"system_name": system_label} if system_label else {}),
**({"sha1": archive} if archive else {}),
**({"sha1": sha1} if (sha1 := archive or designated.get((algorithm, value)))
else {}),
} for algorithm, value in hash_pairs(entry))
return records
def _emulator_lookup_records(profiles: dict) -> list[dict]:
"""A profile's declared values, each leading to the entry's card."""
def _emulator_lookup_records(profiles: dict, db: dict) -> list[dict]:
"""A profile's declared values, each leading to the entry's card, and to
the collection file a value names."""
records: list[dict] = []
for key, profile in sorted(profiles.items()):
if not is_emulator(profile):
@@ -427,10 +440,12 @@ def _emulator_lookup_records(profiles: dict) -> list[dict]:
if isinstance(member, dict) and member.get("name")
]
for name, holder in holders:
designated = _designated(db, holder)
records.extend({
"value": value, "algorithm": algorithm, "layer": "emulator",
"owner": key, "name": name, "url": url,
**({"system_name": entry_label} if entry_label else {}),
**({"sha1": sha1} if (sha1 := designated.get((algorithm, value))) else {}),
} for algorithm, value in hash_pairs(holder))
return records
@@ -456,11 +471,11 @@ def file_lookup_records(
files = db.get("files", {})
named = _console_system_names(profiles, coverages)
records = _collection_lookup_records(files, named, locations, members or {})
records += _platform_lookup_records(coverages, consumers)
records += _emulator_lookup_records(profiles)
records += _platform_lookup_records(coverages, consumers, db)
records += _emulator_lookup_records(profiles, db)
records += retired_records(retired or {}, files, locations)
records += wanted_records(wanted or [])
records += _held_under_every_hash(records, files, db.get("indexes") or {})
records += _held_under_every_hash(records, files)
for record in records:
if record["layer"] in ("platform", "emulator"):
record.setdefault("declared", record["algorithm"])
@@ -521,17 +536,7 @@ def _read_by_name(records: list[dict], files: dict, consumers: FileConsumers) ->
return added
def _collection_sha1(files: dict, indexes: dict, algorithm: str, value: str) -> str | None:
"""The collection file a declared value designates, None when none does."""
if algorithm == "sha1":
return value if value in files else None
found = indexes.get(f"by_{algorithm}", {}).get(value)
if isinstance(found, list):
found = found[0] if len(found) == 1 else None
return found if found in files else None
def _held_under_every_hash(records: list[dict], files: dict, indexes: dict) -> list[dict]:
def _held_under_every_hash(records: list[dict], files: dict) -> list[dict]:
"""A platform or emulator record whose value designates a collection
file, written under the file's other hashes too.
@@ -543,11 +548,9 @@ def _held_under_every_hash(records: list[dict], files: dict, indexes: dict) -> l
for record in records:
if record["layer"] not in ("platform", "emulator"):
continue
sha1 = record.get("sha1") or _collection_sha1(
files, indexes, record["algorithm"], record["value"])
sha1 = record.get("sha1")
if sha1 not in files:
continue
record["sha1"] = sha1
copies.extend({**record, "value": value, "algorithm": algorithm,
"declared": record["algorithm"]}
for algorithm, value in hash_pairs(files[sha1])
+33 -1
View File
@@ -15,7 +15,7 @@ import tempfile
import unittest
from pathlib import Path
from model.database import record_for_hash, records_for_hash
from model.database import declared_records, record_for_hash, records_for_hash
from packs.crossref import entry_source
from packs.integrity import _repo_satisfies_declaration
from resolve.localfile import held_record_for
@@ -55,6 +55,38 @@ class RecordsForHash(unittest.TestCase):
self.assertEqual(records_for_hash(db, "md5", MD5_B[:29]), [])
class DeclaredRecords(unittest.TestCase):
"""The site's system index, file lookup and gap table name a held file
by one rule: systems.json missed 494 files declared by crc32 or sha256."""
def setUp(self):
self.db = _db(
{SHA_A: {"path": "a", "size": 4}, SHA_B: {"path": "b", "size": 8}},
by_md5={MD5_A: SHA_A}, by_sha256={"f" * 64: SHA_B},
by_crc32={"deadbeef": SHA_A, "cafef00d": SHA_B},
)
def test_a_crc32_alone_names_a_record_of_the_declared_size(self):
found = declared_records(self.db, {"crc32": ["deadbeef"]}, 4)
self.assertEqual(found, {("crc32", "deadbeef"): [SHA_A]})
found = declared_records(self.db, {"crc32": ["deadbeef"]}, [8, 16])
self.assertEqual(found, {("crc32", "deadbeef"): []})
def test_a_crc32_beside_a_stronger_hash_names_what_that_hash_names(self):
# An erased flash block shares its crc32 with every other one.
found = declared_records(self.db, {"sha1": [SHA_B], "crc32": ["deadbeef"]})
self.assertEqual(found, {("sha1", SHA_B): [SHA_B], ("crc32", "deadbeef"): []})
found = declared_records(self.db, {"md5": [MD5_A], "crc32": ["deadbeef"]})
self.assertEqual(found[("crc32", "deadbeef")], [SHA_A])
def test_sha256_and_a_cut_md5_name_their_record(self):
found = declared_records(self.db, {"sha256": ["f" * 64], "md5": [MD5_A[:29]]})
self.assertEqual(found, {("sha256", "f" * 64): [SHA_B], ("md5", MD5_A[:29]): [SHA_A]})
def test_an_algorithm_without_an_index_names_nothing(self):
self.assertEqual(declared_records(self.db, {"adler32": ["1234abcd"]}), {})
class GapReportHeldRule(unittest.TestCase):
def setUp(self):
self.db = _db(
+1 -1
View File
@@ -785,7 +785,7 @@ class TheLookupRecipeSaysWhatASha1Misses(unittest.TestCase):
def test_the_page_and_the_records_agree(self):
record = {"layer": "platform", "algorithm": "md5", "value": "0" * 32,
"name": "dmg_boot.bin", "owner": "recalbox"}
self.assertEqual(lookup._held_under_every_hash([record], {}, {}), [])
self.assertEqual(lookup._held_under_every_hash([record], {}), [])
self.assertNotIn("sha1", record)
page = " ".join(datapage.generate_data_page([]).split())
self.assertNotIn("none is needed", page)