From 2ff4acb9650aa29b5eb89c41ea93625bc245d202 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:24:50 +0100 Subject: [PATCH] fix: merge size refusals on data, not text --- scripts/resolve/content.py | 80 ++++++++++++++++++++++++++++++----- scripts/resolve/validation.py | 64 +++++++++++++++++----------- tests/test_content_checks.py | 16 +++++++ 3 files changed, 125 insertions(+), 35 deletions(-) diff --git a/scripts/resolve/content.py b/scripts/resolve/content.py index 9b81b6b8c..f3c544bd3 100644 --- a/scripts/resolve/content.py +++ b/scripts/resolve/content.py @@ -6,8 +6,8 @@ import functools import hashlib import json import os -from collections.abc import Collection -from typing import TYPE_CHECKING, TypedDict +from collections.abc import Collection, Iterable, Sequence +from typing import TYPE_CHECKING, Optional, TypedDict from core.hashing import compute_hashes from core.ziptools import check_inside_zip @@ -218,7 +218,63 @@ def size_fits(file_entry: dict, candidate_size: int) -> bool: return size_refusal(file_entry, candidate_size) is None -def size_refusal(file_entry: dict, candidate_size: int) -> str | None: +Window = tuple[Optional[int], Optional[int], Optional[int]] + + +class SizeRefusal(str): + """A size check's refusal: the message for people, the accepted sizes as data. + + ``sizes`` are the exact sizes the entry takes and ``windows`` its + (min_size, max_size, size_multiple) ranges. Merging reads them, never + the message. + """ + + got: int + sizes: tuple[int, ...] + windows: tuple[Window, ...] + + def __new__( + cls, message: str, got: int, sizes: Iterable[int], windows: Iterable[Window] = (), + ) -> SizeRefusal: + refusal = super().__new__(cls, message) + refusal.got = got + refusal.sizes = tuple(sorted(set(sizes))) + refusal.windows = tuple(dict.fromkeys(windows)) + return refusal + + +def _window_text(window: Window) -> str: + low, high, multiple = window + if low is not None and high is not None: + bounds = f"{low} to {high}" + elif low is not None: + bounds = f"min {low}" + elif high is not None: + bounds = f"max {high}" + else: + return f"multiples of {multiple}" + return f"{bounds} in multiples of {multiple}" if multiple else bounds + + +def merged_size_refusal(refusals: Sequence[SizeRefusal]) -> SizeRefusal: + """One refusal for several entries that each turn the same size away. + + Every size and window any of them accepts is named: Raze lists three + BLOOD.RFF sizes, and a core can pair exact sizes in one entry with a + window in another. + """ + if len(refusals) == 1: + return refusals[0] + got = refusals[0].got + sizes = sorted({size for refusal in refusals for size in refusal.sizes}) + windows = list(dict.fromkeys(w for refusal in refusals for w in refusal.windows)) + parts = [f"[{','.join(str(size) for size in sizes)}]"] if sizes else [] + parts += [_window_text(window) for window in windows] + return SizeRefusal(f"size mismatch: got {got}, accepted {' or '.join(parts)}", + got, sizes, windows) + + +def size_refusal(file_entry: dict, candidate_size: int) -> SizeRefusal | None: """Why the entry's declared sizes turn a size away, or None. ``size`` is the exact size, or the list of sizes, the code accepts. @@ -241,15 +297,19 @@ def size_refusal(file_entry: dict, candidate_size: int) -> str | None: if not allowed: return None accepted = ",".join(str(s) for s in sorted(allowed)) - return f"size mismatch: got {candidate_size}, accepted [{accepted}]" + return SizeRefusal(f"size mismatch: got {candidate_size}, accepted [{accepted}]", + candidate_size, allowed) exact = f" or [{','.join(str(s) for s in sorted(allowed))}]" if allowed else "" if low is not None and candidate_size < low: - return f"size too small: min {low}{exact}, got {candidate_size}" - if high is not None and candidate_size > high: - return f"size too large: max {high}{exact}, got {candidate_size}" - if multiple and candidate_size % int(multiple): - return f"size mismatch: got {candidate_size}, accepted multiples of {multiple}{exact}" - return None + message = f"size too small: min {low}{exact}, got {candidate_size}" + elif high is not None and candidate_size > high: + message = f"size too large: max {high}{exact}, got {candidate_size}" + elif multiple and candidate_size % int(multiple): + message = f"size mismatch: got {candidate_size}, accepted multiples of {multiple}{exact}" + else: + return None + window = (low, high, int(multiple) if multiple else None) + return SizeRefusal(message, candidate_size, allowed, [window]) class DeclaredHashes(TypedDict): diff --git a/scripts/resolve/validation.py b/scripts/resolve/validation.py index 326b63d10..439566f57 100644 --- a/scripts/resolve/validation.py +++ b/scripts/resolve/validation.py @@ -8,7 +8,6 @@ truth data for reporting. from __future__ import annotations import os -import re import zipfile from collections.abc import Callable, Collection, Iterator, Mapping, Sequence from typing import TYPE_CHECKING, TypedDict @@ -20,7 +19,9 @@ from resolve.content import ( name_match_size_ok, parse_validation, shape_fits, + merged_size_refusal, size_refusal, + SizeRefusal, ) from resolve.archives import archive_members from model.database import records_for_hash @@ -56,21 +57,41 @@ class Refusal(str): ``accepted`` maps the algorithm to the values the check takes, in the order the message lists them. Reports that look the dumps up read it, never the message, which is free to change. + + ``check``, ``got`` and ``values`` say which check refused which digest + and what it takes, so refusals of one check merge on data. An Adler-32 + check names its values there but accepts no dump a catalog can look up. """ accepted: dict[str, list[str]] + check: str + got: str + values: list[str] - def __new__(cls, message: str, accepted: Mapping[str, Sequence[str]]) -> Refusal: + def __new__( + cls, message: str, accepted: Mapping[str, Sequence[str]], + check: str = "", got: str = "", values: Sequence[str] = (), + ) -> Refusal: refusal = super().__new__(cls, message) refusal.accepted = {algo: list(values) for algo, values in accepted.items()} + refusal.check, refusal.got, refusal.values = check, got, list(values) return refusal +def _check_refusal(check: str, got: str, values: list[str], lookup: bool) -> Refusal: + """The refusal of a digest check, rendered from its data.""" + return Refusal(f"{check} mismatch: got {got}, accepted [{','.join(values)}]", + {check: values} if lookup else {}, check, got, values) + + def _hash_refusal(hash_type: str, got: str, accepted: Collection[str]) -> Refusal: """The refusal of a hash check that does not take ``got``.""" - values = sorted(accepted) - return Refusal(f"{hash_type} mismatch: got {got}, accepted [{','.join(values)}]", - {hash_type: values}) + return _check_refusal(hash_type, got, sorted(accepted), True) + + +def _adler32_refusal(got: str, accepted: Collection[str]) -> Refusal: + """The refusal of an Adler-32 check that does not take ``got``.""" + return _check_refusal("adler32", f"0x{got}", sorted(accepted), False) def accepted_hashes(reason: str | None) -> dict[str, list[str]]: @@ -173,8 +194,7 @@ def _rule_failure( hashes.update(compute_hashes(local_path)) actual = hashes["adler32"].lower() if actual not in rule["adler32"]: - accepted = ",".join(sorted(rule["adler32"])) - return f"adler32 mismatch: got 0x{actual}, accepted [{accepted}]" + return _adler32_refusal(actual, rule["adler32"]) for check, spec in rule.get("content", {}).items(): if check not in skip and not content_fits({"validation": [check], check: spec}, local_path): return _CONTENT_REASONS[check] @@ -433,24 +453,22 @@ def _emulators_for_check( return sorted(result) -_REASON = re.compile(r"^(\w+ mismatch): got (\S+), accepted \[(.*)\]$") - - def _merged_reason(reasons: list[str]) -> str: """One reason for every entry of a core that turned the copy away. Raze lists three BLOOD.RFF sizes and the message named the first one - alone. Reasons of one kind are merged into a single accepted list. + alone. Refusals of one check on one value are merged from their data + into a single accepted list. """ - parsed = [m for m in (_REASON.match(reason) for reason in reasons) if m] - if len(parsed) == len(reasons) and len({(m.group(1), m.group(2)) for m in parsed}) == 1: - accepted = sorted({v for m in parsed for v in m.group(3).split(",") if v}, - key=lambda v: (len(v), v)) - message = f"{parsed[0].group(1)}: got {parsed[0].group(2)}, accepted [{','.join(accepted)}]" - algorithms = {algo for reason in reasons for algo in accepted_hashes(reason)} - if len(algorithms) == 1 and all(isinstance(reason, Refusal) for reason in reasons): - return Refusal(message, {algorithms.pop(): accepted}) - return message + sized = [reason for reason in reasons if isinstance(reason, SizeRefusal)] + if len(sized) == len(reasons) and len({reason.got for reason in sized}) == 1: + return merged_size_refusal(sized) + checked = [reason for reason in reasons if isinstance(reason, Refusal) and reason.check] + if len(checked) == len(reasons) and len({(r.check, r.got) for r in checked}) == 1: + first = checked[0] + values = sorted({v for r in checked for v in r.values}, key=lambda v: (len(v), v)) + return _check_refusal(first.check, first.got, values, + all(r.accepted for r in checked)) return reasons[0] @@ -584,12 +602,8 @@ def _merged_hash_failure( if entry.get("adler32_byteswap"): actual_adler = _adler32_byteswapped(local_path) if actual_adler not in entry["adler32"]: - expected = ",".join(sorted(entry["adler32"])) emus = _emulators_for_check("adler32", pe) - return ( - f"adler32 mismatch: got 0x{actual_adler}, accepted [{expected}]", - emus, - ) + return _adler32_refusal(actual_adler, entry["adler32"]), emus return None diff --git a/tests/test_content_checks.py b/tests/test_content_checks.py index eadae82b5..1b192a09e 100644 --- a/tests/test_content_checks.py +++ b/tests/test_content_checks.py @@ -241,6 +241,22 @@ class OtherContentTests(unittest.TestCase): path.write_bytes(b"\0" * 143200) self.assertIsNone(core_size_refusal(disk, str(path))) + def test_a_core_refusal_names_every_entry_s_sizes(self): + """The merge parsed the message: a second entry's window was dropped + and the report named the first entry's sizes alone.""" + from resolve.validation import _merged_reason + + exact = [size_refusal({"size": [300]}, 50), size_refusal({"size": [100, 2048]}, 50)] + self.assertEqual(_merged_reason(exact), "size mismatch: got 50, accepted [100,300,2048]") + mixed = [size_refusal({"size": [100]}, 50), + size_refusal({"min_size": 200, "max_size": 300}, 50), + size_refusal({"min_size": 65536, "size_multiple": 65536}, 50)] + self.assertEqual(_merged_reason(mixed), + "size mismatch: got 50, accepted [100] or 200 to 300 " + "or min 65536 in multiples of 65536") + lone = size_refusal({"min_size": 200, "max_size": 300}, 50) + self.assertEqual(_merged_reason([lone]), "size too small: min 200, got 50") + def test_profiles_with_a_size_and_a_window_take_the_window(self): profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) entries = {