fix: judge declared sizes per entry with size_fits

This commit is contained in:
Abdessamad Derraz committed 2026-11-21 06:01:46 +01:00
1 parent 2308039452
commit b81e89dbfb
6 files changed
+78 -82

No files matched your search

+2 -8
View File
@@ -11,6 +11,7 @@ from pathlib import Path
from core.hashing import parse_hash_list
from core.paths import REPO_ROOT
from resolve.content import size_fits
HASH_FIELDS = ("sha1", "md5", "sha256")
@@ -22,14 +23,7 @@ def _crc_key(value: str) -> str:
def _fits(size: int | None, entry: dict) -> bool:
"""Whether a size meets what a profile entry states about it."""
if size is None:
return False
declared = entry.get("size")
if declared is not None:
accepted = declared if isinstance(declared, list) else [declared]
return size in {int(value) for value in accepted}
low, high = entry.get("min_size"), entry.get("max_size")
return (low is None or size >= int(low)) and (high is None or size <= int(high))
return size is not None and size_fits(entry, size)
def profile_needs(profiles: dict, db: dict) -> dict:
+2 -8
View File
@@ -21,6 +21,7 @@ from resolve.cores import resolve_platform_cores
from resolve.reconcile import HASH_FIELDS, hash_values
from core.hashing import lists_hashes
from resolve.collisions import accepted_by_all, find_collisions
from resolve.content import size_fits
from resolve.validation import opens_by_name, outside_gap_scope
@@ -39,14 +40,7 @@ def _size_fits(entry: dict, local: str) -> bool:
size = os.path.getsize(local)
except OSError:
return False
declared = entry.get("size")
sizes = declared if isinstance(declared, list) else [declared]
sizes = [s for s in sizes if isinstance(s, int)]
if sizes and size not in sizes:
return False
if isinstance(entry.get("min_size"), int) and size < entry["min_size"]:
return False
return not (isinstance(entry.get("max_size"), int) and size > entry["max_size"])
return size_fits(entry, size)
def _reads(entry: dict, by_name: bool, local: str, db: dict) -> bool:
+15 -5
View File
@@ -214,7 +214,12 @@ def declares_shape(file_entry: dict) -> bool:
def size_fits(file_entry: dict, candidate_size: int) -> bool:
"""Whether a size is one the entry declares.
"""Whether a size is one the entry declares (size_refusal)."""
return size_refusal(file_entry, candidate_size) is None
def size_refusal(file_entry: dict, candidate_size: int) -> str | None:
"""Why the entry's declared sizes turn a size away, or None.
``size`` is an exact size or the list of sizes the code accepts, and it
outranks a ``min_size``/``max_size`` range. ``size_multiple`` is a
@@ -225,15 +230,20 @@ def size_fits(file_entry: dict, candidate_size: int) -> bool:
declared = file_entry.get("size")
if declared is not None:
allowed = declared if isinstance(declared, list) else [declared]
return candidate_size in allowed
if candidate_size in allowed:
return None
accepted = ",".join(str(s) for s in sorted(allowed))
return f"size mismatch: got {candidate_size}, accepted [{accepted}]"
low = file_entry.get("min_size")
high = file_entry.get("max_size")
if low is not None and candidate_size < low:
return False
return f"size too small: min {low}, got {candidate_size}"
if high is not None and candidate_size > high:
return False
return f"size too large: max {high}, got {candidate_size}"
multiple = file_entry.get("size_multiple")
return not (multiple and candidate_size % int(multiple))
if multiple and candidate_size % int(multiple):
return f"size mismatch: got {candidate_size}, accepted multiples of {multiple}"
return None
class DeclaredHashes(TypedDict):
+19 -56
View File
@@ -20,6 +20,7 @@ from resolve.content import (
name_match_size_ok,
parse_validation,
shape_fits,
size_refusal,
)
from resolve.archives import archive_members
from model.profiles import CONTENT_CHECKS, entry_system_ids, lists_files
@@ -107,17 +108,11 @@ def warned_checks(f: dict, checks: Collection[str]) -> set[str]:
def _rule_size_failure(rule: dict, local_path: str) -> str | None:
"""Why one entry's size check rejects a file, or None."""
actual_size = os.path.getsize(local_path)
if rule["sizes"] and actual_size not in rule["sizes"]:
accepted = ",".join(str(s) for s in sorted(rule["sizes"]))
return f"size mismatch: got {actual_size}, accepted [{accepted}]"
if rule["min_size"] is not None and actual_size < rule["min_size"]:
return f"size too small: min {rule['min_size']}, got {actual_size}"
if rule["max_size"] is not None and actual_size > rule["max_size"]:
return f"size too large: max {rule['max_size']}, got {actual_size}"
if rule.get("size_multiple") and actual_size % int(rule["size_multiple"]):
return f"size mismatch: got {actual_size}, accepted multiples of {rule['size_multiple']}"
return None
declared = {
"size": sorted(rule["sizes"]) or None, "min_size": rule["min_size"],
"max_size": rule["max_size"], "size_multiple": rule.get("size_multiple"),
}
return size_refusal(declared, os.path.getsize(local_path))
def _rule_failure(
@@ -229,10 +224,6 @@ def _labels_widened(profile: dict) -> list[dict]:
def _new_index_entry() -> dict:
return {
"checks": set(),
"sizes": set(),
"min_size": None,
"max_size": None,
"size_multiples": set(),
"crc32": set(),
"md5": set(),
"sha1": set(),
@@ -246,27 +237,6 @@ def _new_index_entry() -> dict:
}
def _merge_sizes(item: dict, f: dict) -> None:
raw_size = f.get("size")
if raw_size is not None:
if isinstance(raw_size, list):
item["sizes"].update(raw_size)
else:
item["sizes"].add(raw_size)
if f.get("min_size") is not None:
cur = item["min_size"]
item["min_size"] = (
min(cur, f["min_size"]) if cur is not None else f["min_size"]
)
if f.get("size_multiple"):
item["size_multiples"].add(int(f["size_multiple"]))
if f.get("max_size") is not None:
cur = item["max_size"]
item["max_size"] = (
max(cur, f["max_size"]) if cur is not None else f["max_size"]
)
def _merge_hashes(item: dict, f: dict, checks: list[str]) -> None:
# Hash checks: collect all accepted hashes as sets (multiple valid
# versions of the same file, e.g. MT-32 ROM versions)
@@ -341,9 +311,6 @@ def _index_entry(index: dict[str, dict], emu_name: str, f: dict, checks: list[st
item["checks"].update(checks)
# Track non-reproducible crypto checks
item["crypto_only"].update(c for c in checks if c in _CRYPTO_CHECKS)
# Size checks
if "size" in checks:
_merge_sizes(item, f)
_merge_hashes(item, f, checks)
_merge_per_emulator(item, emu_name, f, checks)
@@ -545,23 +512,19 @@ def _per_emulator_failure(
def _merged_size_failure(
entry: dict, local_path: str, pe: dict[str, dict],
) -> tuple[str, list[str]] | None:
actual_size = os.path.getsize(local_path)
if entry["sizes"] and actual_size not in entry["sizes"]:
expected = ",".join(str(s) for s in sorted(entry["sizes"]))
emus = _emulators_for_check("size", pe)
return f"size mismatch: got {actual_size}, accepted [{expected}]", emus
if entry["min_size"] is not None and actual_size < entry["min_size"]:
emus = _emulators_for_check("size", pe)
return f"size too small: min {entry['min_size']}, got {actual_size}", emus
if entry["max_size"] is not None and actual_size > entry["max_size"]:
emus = _emulators_for_check("size", pe)
return f"size too large: max {entry['max_size']}, got {actual_size}", emus
multiples = entry.get("size_multiples") or set()
if multiples and all(actual_size % m for m in multiples):
emus = _emulators_for_check("size", pe)
accepted = ",".join(str(m) for m in sorted(multiples))
return f"size mismatch: got {actual_size}, accepted multiples of [{accepted}]", emus
return None
"""Refused only when every entry that checks the size turns it away.
Each entry is judged by its own sizes: pooling one core's exact sizes
with another's min_size refused the Apple IIGS ROM that gsplus takes.
"""
rules = [
r for r in entry.get("rules", [])
if "size" in r["checks"] and "size" not in r["warn"]
]
reasons = [_rule_size_failure(rule, local_path) for rule in rules]
if not reasons or not all(reasons):
return None
return _merged_reason([r for r in reasons if r]), _emulators_for_check("size", pe)
def _merged_hash_failure(
+29 -5
View File
@@ -1266,7 +1266,7 @@ class TestE2E(unittest.TestCase):
index = build_validation_index(profiles)
self.assertIn("present_req.bin", index)
self.assertIn("size", index["present_req.bin"]["checks"])
self.assertIn(16, index["present_req.bin"]["sizes"])
self.assertIn(16, {s for r in index["present_req.bin"]["rules"] for s in r["sizes"]})
self.assertIn("correct_hash.bin", index)
self.assertIn("crc32", index["correct_hash.bin"]["checks"])
@@ -1347,7 +1347,31 @@ class TestE2E(unittest.TestCase):
},
}
index = build_validation_index(profiles)
self.assertEqual(index["shared.bin"]["sizes"], {512, 1024})
self.assertEqual([r["sizes"] for r in index["shared.bin"]["rules"]], [{512}, {1024}])
def test_71b_validation_sizes_judged_per_entry(self):
"""One core's exact size is never bounded by another core's minimum:
pooled, gsplus's 131072-byte Apple IIGS ROM fell under basiliskii's
min_size and was refused."""
import tempfile
profiles = {
"exact": {"type": "libretro", "files": [
{"name": "ROM", "validation": ["size"], "size": [131072, 262144]}]},
"ranged": {"type": "libretro", "files": [
{"name": "ROM", "validation": ["size"], "min_size": 377670}]},
}
index = build_validation_index(profiles)
with tempfile.TemporaryDirectory() as tmp:
path = os.path.join(tmp, "ROM")
with open(path, "wb") as f:
f.write(b"\0" * 131072)
self.assertIsNone(check_file_validation(path, "ROM", index))
with open(path, "wb") as f:
f.write(b"\0" * 1000)
reason, emus = check_file_validation(path, "ROM", index)
self.assertIn("size", reason)
self.assertEqual(emus, ["exact", "ranged"])
def test_79_validation_md5_pass(self):
"""File with correct MD5 passes validation."""
@@ -1392,9 +1416,9 @@ class TestE2E(unittest.TestCase):
path = self.files["present_req.bin"]["path"]
reason = check_file_validation(path, "present_req.bin", index)
self.assertIsNone(reason)
# Verify the index has min/max
self.assertEqual(index["present_req.bin"]["min_size"], 10)
self.assertEqual(index["present_req.bin"]["max_size"], 100)
# Each entry keeps its own min/max
rules = index["present_req.bin"]["rules"]
self.assertIn((10, 100), {(r["min_size"], r["max_size"]) for r in rules})
def test_84_validation_crypto_tracked(self):
"""Signature/crypto checks are tracked as non-reproducible."""
+11
View File
@@ -726,5 +726,16 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase):
self.assertEqual(len(romsets_holding({"crc32": "00000001", "size": 8}, index)), 1)
class SizeRule(unittest.TestCase):
def test_a_granule_is_read_as_size_fits_reads_it(self):
from scripts.acquire.provenance import _fits
flash = {"min_size": 65536, "size_multiple": 65536}
self.assertTrue(_fits(131072, flash))
self.assertFalse(_fits(70000, flash))
self.assertFalse(_fits(None, flash))
if __name__ == "__main__":
unittest.main()