fix: find held records by the resolver hash rule

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:01:53 +01:00
1 parent b81e89dbfb
commit 23e3cc06b3
6 files changed
+112 -88

No files matched your search

+5 -31
View File
@@ -13,6 +13,7 @@ from pathlib import Path
from core import upstream
from core.hashing import parse_hash_list
from resolve.localfile import held_record_for
MAX_DOWNLOAD = 100 * 1024 * 1024 # 100MB per file
@@ -103,17 +104,6 @@ def find_missing(config: dict, db: dict) -> list[dict]:
return missing
def _crc32s(entry: dict) -> set[str]:
return {value.zfill(8) for value in parse_hash_list(entry.get("crc32"))}
def _size(entry: dict) -> int | None:
try:
return int(entry["size"]) if entry.get("size") is not None else None
except (TypeError, ValueError):
return None
CRYPTO_HASHES = (
("sha256", hashlib.sha256),
("sha1", hashlib.sha1),
@@ -149,26 +139,10 @@ def verify_content(data: bytes, expected: dict) -> bool:
def step1_crossref_db(entry: dict, db: dict) -> str | None:
"""Check if file exists under different name/path in database."""
files = db.get("files", {})
for sha1 in sorted(parse_hash_list(entry.get("sha1"))):
if sha1 in files:
return files[sha1]["path"]
indexes = db.get("indexes", {})
for field, index in (("sha256", "by_sha256"), ("md5", "by_md5")):
by_hash = indexes.get(index, {})
for value in sorted(parse_hash_list(entry.get(field))):
sha1_match = by_hash.get(value)
if sha1_match and sha1_match in files:
return files[sha1_match]["path"]
size = _size(entry)
if size is not None:
by_crc32 = indexes.get("by_crc32", {})
for crc in sorted(_crc32s(entry)):
sha1_match = by_crc32.get(crc)
if sha1_match in files and files[sha1_match].get("size") == size:
return files[sha1_match]["path"]
return None
"""Where the collection holds the declared content, read as the resolver
reads it: a held file a declared hash contradicts is still searched for."""
sha1 = held_record_for(entry, db)
return db["files"][sha1]["path"] if sha1 else None
def step2_scan_branches(entry: dict) -> bytes | None:
+26
View File
@@ -7,6 +7,7 @@ import os
from pathlib import Path
from core.cli import InputMissing
from core.hashing import cut_md5_owner
from core.memo import DerivedView
from core.paths import REPO_ROOT
@@ -82,6 +83,31 @@ def sha1_at(db: dict, path: str | None) -> str | None:
return found[0] if found else None
_HASH_INDEXES = {"md5": "by_md5", "crc32": "by_crc32", "sha256": "by_sha256"}
def record_for_hash(db: dict, kind: str, value: object) -> str | None:
"""The sha1 the database keys the file one hash value names under.
A cut md5 (Batocera writes 29 characters) names the one held md5 it
starts, as cut_md5_owner reads it.
"""
if not (value and isinstance(value, str)):
return None
files = db.get("files", {})
value = value.strip().lower()
if kind == "sha1":
return value if value in files else None
index = db.get("indexes", {}).get(_HASH_INDEXES[kind], {})
found = index.get(value)
if found is None and kind == "md5":
owner = cut_md5_owner(value, index)
found = index.get(owner) if owner else None
if isinstance(found, list):
found = found[0] if found else None
return found if found in files else None
_mame_clone_map_cache: dict[str, dict[str, str]] = {}
+32
View File
@@ -327,6 +327,38 @@ def _record_match_status(q: _Lookup, match_sha1: str) -> str | None:
return statuses[0] if statuses else None
def held_record_for(file_entry: dict, db: dict) -> str | None:
"""The sha1 of a record every declared hash agrees with, from the database.
The resolver's hash steps without the disk check, for a caller asking
whether the collection holds the content: sha1, sha256, md5 (a cut one
standing for the held md5 it starts), then crc32 only without a stronger
hash, bounded by the declared size.
"""
indexes = db.get("indexes", {})
by_md5 = indexes.get("by_md5", {})
md5_list = [
(cut_md5_owner(value, by_md5) or value) if len(value) < 32 else value
for value in parse_md5_list(file_entry.get("md5"))
]
q = _lookup(
file_entry, db, "", md5_list,
composite_only=file_entry.get("zip_digest") == "composite",
)
candidates = [
*q.sha1_candidates,
*(indexes.get("by_sha256", {}).get(v) for v in q.sha256_candidates),
]
if not (q.zipped_file or q.composite_only):
candidates += [by_md5.get(v) for v in md5_list]
if not (q.sha1_candidates or q.sha256_candidates or q.md5_list or q.zipped_file):
candidates += [indexes.get("by_crc32", {}).get(v) for v in q.crc_candidates]
return next(
(c for c in candidates if c and c in q.files_db and _record_match_status(q, c)),
None,
)
def _held_record(q: _Lookup, match_sha1: str) -> Resolution | None:
"""The record's path and evidence, when it satisfies the entry and is on disk."""
path = q.files_db[match_sha1]["path"]
+3 -20
View File
@@ -13,9 +13,9 @@ import urllib.error
import urllib.request
from pathlib import Path
from model.database import record_at
from model.database import record_at, record_for_hash
from model.largefiles import fetch_large_file
from core.hashing import HASH_FIELDS, cut_md5_owner, parse_hash_list
from core.hashing import HASH_FIELDS, parse_hash_list
from resolve.content import declared_hash_verdict
from resolve.localfile import resolution_is_hash_exact, resolve_local_file
from core.paths import REPO_ROOT, declared_destination
@@ -253,24 +253,7 @@ def parse_hash_file(path: str) -> list[tuple[str, str]]:
def sha1_for_hash(hash_type: str, hash_val: str, db: dict) -> str | None:
"""The database key a looked-up hash names, or None."""
files_db = db.get("files", {})
indexes = db.get("indexes", {})
sha1: str | None
if hash_type == "sha1":
sha1 = hash_val
elif hash_type == "crc32":
sha1 = indexes.get("by_crc32", {}).get(hash_val)
elif hash_type == "md5":
by_md5 = indexes.get("by_md5", {})
sha1 = by_md5.get(hash_val)
if sha1 is None:
owner = cut_md5_owner(hash_val, by_md5)
sha1 = by_md5.get(owner) if owner else None
else:
sha1 = next(
(k for k, e in files_db.items() if e.get("sha256") == hash_val), None
)
return sha1 if sha1 in files_db else None
return record_for_hash(db, hash_type, hash_val)
def lookup_hashes(
hashes: list[tuple[str, str]],
+17 -36
View File
@@ -18,6 +18,7 @@ from resolve.standalone import platform_layouts, standalone_set as platform_stan
from resolve.cores import resolve_platform_cores
from resolve.reconcile import contradicts, shares_hash
from model.alternatives import groups_of
from model.database import record_for_hash
from core.hashing import HASH_FIELDS, compute_hashes, declared_hashes, lists_hashes, parse_hash_list
from resolve.validation import (
filter_files_by_mode,
@@ -42,51 +43,31 @@ def _serialize_source_ref(sr: object) -> str:
return str(sr)
def _indexed_record(value: object, index: dict, files_db: dict) -> dict | None:
"""The database record a hash index points a single hash value to."""
if not (value and isinstance(value, str)):
return None
ref = index.get(value.lower())
if not ref:
return None
ref_sha1 = ref if isinstance(ref, str) else (ref[0] if ref else None)
if not ref_sha1:
return None
return files_db.get(ref_sha1)
def _enrich_hashes(entry: dict, db: dict) -> None:
"""Fill the hashes a profile omits from the record its own hash names.
The record is found by sha1, then md5, then crc32 with the size when the
profile gives one. Never by name: a file in bios/ under the same name may
not be the bytes the source code expects. An entry listing several
accepted values for a hash is left as is.
The record is found by sha1, sha256, then md5, then crc32 with the size
when the profile gives one. Never by name: a file in bios/ under the same
name may not be the bytes the source code expects. An entry listing
several accepted values for a hash is left as is.
"""
for h in ("sha1", "md5", "crc32"):
if isinstance(entry.get(h), list):
return
if any(isinstance(entry.get(h), list) for h in HASH_FIELDS):
return
files_db = db.get("files", {})
indexes = db.get("indexes", {})
record = None
# rust_dos names its SC-55 ROMs by sha256 alone, ares 5200.rom too.
for kind in ("sha1", "sha256", "md5"):
sha1 = record_for_hash(db, kind, entry.get(kind))
if sha1:
record = files_db[sha1]
break
# Anchor 1: SHA1 (strongest)
sha1 = entry.get("sha1")
if sha1 and isinstance(sha1, str):
record = files_db.get(sha1)
# Anchor 2: MD5 (strong)
# CRC32 (32-bit, collisions theoretically possible): the size must
# match when the profile has one.
if record is None:
record = _indexed_record(entry.get("md5"), indexes.get("by_md5", {}), files_db)
# Anchor 3: CRC32 (32-bit, collisions theoretically possible).
# Require size match when profile has a size to guard against collisions.
if record is None:
candidate = _indexed_record(
entry.get("crc32"), indexes.get("by_crc32", {}), files_db,
)
sha1 = record_for_hash(db, "crc32", entry.get("crc32"))
candidate = files_db[sha1] if sha1 else None
if candidate is not None:
profile_size = entry.get("size")
if not profile_size or candidate.get("size") == profile_size:
+29 -1
View File
@@ -6769,12 +6769,28 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase):
def test_a_held_sha256_is_found_in_the_database(self):
from scripts.acquire import fetch as acquire_fetch
db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3}},
db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3, "sha256": "f" * 64}},
"indexes": {"by_sha256": {"f" * 64: "s"}}}
self.assertEqual(
acquire_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin"
)
def test_a_held_file_a_declared_hash_contradicts_is_still_searched(self):
"""auto_fetch printed "Found in database" for a crc32 or md5 hit whose
sha1 the entry contradicts, a file verify calls missing."""
from scripts.acquire import fetch as acquire_fetch
held = {"path": "bios/x/a.bin", "sha1": "c" * 40, "md5": "d" * 32,
"crc32": "deadbeef", "size": 4}
db = {"files": {"c" * 40: held},
"indexes": {"by_crc32": {"deadbeef": "c" * 40}, "by_md5": {"d" * 32: "c" * 40}}}
find = acquire_fetch.step1_crossref_db
self.assertIsNone(find({"sha1": "a" * 40, "crc32": "deadbeef", "size": 4}, db))
self.assertIsNone(find({"sha1": "a" * 40, "md5": "d" * 32}, db))
self.assertIsNone(find({"crc32": "deadbeef", "size": 5}, db))
self.assertEqual(find({"crc32": "deadbeef", "size": 4}, db), "bios/x/a.bin")
self.assertEqual(find({"md5": "d" * 29}, db), "bios/x/a.bin")
def test_an_entry_without_a_hash_is_not_searched(self):
from unittest import mock
@@ -7295,6 +7311,18 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
self.assertEqual(sha1_for_hash("sha256", entry["sha256"], db), sha1)
self.assertEqual(sha1_for_hash("md5", entry["md5"][:29], db), sha1)
def test_the_truth_anchors_a_sha256_only_entry(self):
"""rust_dos and ares name files by sha256 alone: the truth left their
md5 empty, so md5 platforms never received them."""
from scripts.resolve.truth import _enrich_hashes
db = {"files": {"s" * 40: {"sha1": "s" * 40, "md5": "m" * 32, "sha256": "f" * 64,
"crc32": "0badf00d", "size": 16}},
"indexes": {"by_sha256": {"f" * 64: "s" * 40}}}
entry = {"name": "5200.rom", "sha256": "F" * 64}
_enrich_hashes(entry, db)
self.assertEqual((entry["md5"], entry["sha1"], entry["size"]), ("m" * 32, "s" * 40, 16))
class ErrorsGoToStderr(unittest.TestCase):
"""The lock refusal and "no pack for" went to stdout: a run redirected to