refactor: split validation by subject

This commit is contained in:
Abdessamad Derraz committed 2026-11-24 05:54:38 +01:00
1 parent c6352f2db1
commit 39a4c86917
51 files changed
+808 -804

No files matched your search

+3 -691
View File
@@ -8,32 +8,21 @@ truth data for reporting.
from __future__ import annotations
import os
import zipfile
from collections.abc import Callable, Collection, Iterator, Mapping, Sequence
from typing import TYPE_CHECKING, TypedDict
from collections.abc import Collection, Mapping, Sequence
from resolve.content import (
adler32_of,
content_fits,
declared_content_checks,
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
from model.profiles import CONTENT_CHECKS, entry_system_ids, lists_files
from core.hashing import compute_hashes, parse_hash_list
from core.paths import BIOS_DIR, sanitize_pack_path
from core.hashing import lists_hashes, md5_composite
from resolve.nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file
from core.ziptools import check_inside_zip, check_inside_zip_data
from core.paths import BIOS_DIR
if TYPE_CHECKING:
from typing_extensions import Unpack
from resolve.entryscope import opens_by_name
# Validation types that require console-specific cryptographic keys.
# verify.py cannot reproduce these: size checks still apply if combined.
@@ -605,680 +594,3 @@ def _merged_hash_failure(
emus = _emulators_for_check("adler32", pe)
return _adler32_refusal(actual_adler, entry["adler32"]), emus
return None
def read_from_system_dir(file_entry: dict, standalone: bool = False) -> bool:
"""Whether the emulator reads this entry from the system directory.
A file loaded from the save, content or working directory is not in the
BIOS tree: no platform lists it, and the truth model must not ask a
platform to declare it. Packs place one read below the save directory
there (read_from_save_dir), never in the BIOS tree. Two builds can read one file from two
places: libretro Dolphin keeps its User tree in the save directory, the
standalone app in its own folder, so ``load_from`` can be keyed by build.
"""
load_from = _load_from(file_entry, standalone)
return not load_from or load_from == "system_dir"
def _load_from(file_entry: dict, standalone: bool) -> str:
"""The ``load_from`` value that applies to one build."""
load_from = file_entry.get("load_from", "")
if isinstance(load_from, dict):
load_from = load_from.get("standalone" if standalone else "libretro", "")
return load_from or ""
def read_from_save_dir(file_entry: dict, standalone: bool = False) -> bool:
"""Whether the libretro build reads this entry below the frontend's save
directory, the one RETRO_ENVIRONMENT_GET_SAVE_DIRECTORY returns.
``path`` is then relative to that directory. A standalone app has no
frontend to hand it one: its files are placed by ``standalone_path``.
"""
return not standalone and _load_from(file_entry, False) == "save_dir"
def entry_root(file_entry: dict, standalone: bool = False) -> str:
"""The frontend directory an entry's ``path`` is relative to: ``save``
for a file the libretro build reads below the save directory, else
``system``."""
return "save" if read_from_save_dir(file_entry, standalone) else "system"
def outside_gap_scope(file_entry: dict, is_standalone: bool) -> bool:
"""Whether an entry is a file the platform's pack would carry for this build.
Read by the gap report and by verify's undeclared-file pass, so both set
aside the same entries: a placeholder standing for a family of files, a
file the user imports through the UI (``path: null``), an entry of the
build the platform does not run, a file read outside the system and
save directories, and a filename-agnostic entry the builder scans for
itself. A file the libretro build reads below the save directory is in
scope: the pack places it there (``entry_root``).
"""
name = file_entry.get("name", "")
if "<" in name or ">" in name or "*" in name:
return True
if "path" in file_entry and file_entry["path"] is None:
return True
if not read_by_build(file_entry, is_standalone):
return True
return not (
read_from_system_dir(file_entry, is_standalone)
or read_from_save_dir(file_entry, is_standalone)
) or bool(file_entry.get("agnostic"))
def case_folded_slots(
config: dict, declarations: Mapping[str, list[tuple[int | None, str]]],
) -> frozenset[str]:
"""The slots a platform whose filesystem folds case fills, any spelling.
On RetroBat the 32X_G_BIOS.BIN it declares is the file BlastEm opens as
32X_G_BIOS.bin. On Lakka bios.col and BIOS.col are two files: nothing.
"""
if not config.get("case_insensitive_fs", False):
return frozenset()
return frozenset(
where for places in declarations.values() for _size, where in places if where
)
def declaration_settles(
file_entry: dict,
fname: str,
declared_names: Mapping[str, list[tuple[int | None, str]]] | set[str],
dest: str = "",
folded_slots: frozenset[str] = frozenset(),
declared_contents: Mapping[str, set[str]] | None = None,
) -> bool:
"""Whether a platform declaration meets a core's requirement.
An entry the core finds by content (``found_by: content`` on the entry)
is met by any declaration of a file it accepts by hash, in the folder it
scans: atari800 takes RetroDECK's ROM_BASIC_A by its CRC32, so its own
label for that ROM is not one more file to ship.
A platform declaring the name the core reads has met the requirement
where the declaration fills the entry's own slot, whose content the slot
arbitration decides, or elsewhere at a size the core accepts: the builder
copies that file to the core's path. Galaksija's 4 KiB ROM1.BIN does not
stand for DOSBox's 32 KiB SC-55 one. The builder copies nothing for an
alias, so an alias answers only where the core reads it: quasi88 reads
n88sub.rom or disk.rom in quasi88/, and System.dat names quasi88/disk.rom.
RetroDECK's root MSX.ROM is not CLK's MSX/MSX.ROM, and RetroBat's 16 KiB
MSX DISK.ROM at the root is not the 256-byte Disk II ROM gsplus also
accepts as c600.rom. The archive answers by its name. A bare set of names
carries no slot or size and answers by name.
Read by verify and by the gap report, which settled on the name alone
and left DOSBox's SC-55 ROMs off the gaps page. ``folded_slots``
(case_folded_slots) are slots a declaration fills in another spelling on
a filesystem that folds case: the core opens that file there.
"""
if file_entry.get("archive") in declared_names:
return True
slot = sanitize_pack_path(dest or fname).lower()
directory = slot if dest.endswith("/") else slot.rpartition("/")[0]
if declared_contents and file_entry.get("found_by") == "content":
for field in ("md5", "sha1", "crc32"):
values = file_entry.get(field) or []
for value in values if isinstance(values, list) else str(values).split(","):
folders = declared_contents.get(f"{field}:{str(value).strip().lower()}")
if folders and directory in folders:
return True
if not dest.endswith("/") and slot in folded_slots:
return True
for name in (fname, *file_entry.get("aliases", [])):
if name not in declared_names:
continue
if not isinstance(declared_names, Mapping):
return True
if name == fname:
if any(
where == slot or name_match_size_ok(file_entry, size)
for size, where in declared_names[name]
):
return True
continue
read_at = f"{directory}/{name}".lower() if directory else name.lower()
if any(
where == read_at and name_match_size_ok(file_entry, size)
for size, where in declared_names[name]
):
return True
return False
def with_archive_members(entry: dict, files: list[dict]) -> dict:
"""A loose entry resolved as the archive its profile reads members from.
gngeopi declares neogeo.zip and, apart, the ROMs it opens inside it. The
members decide which same-named copy is the archive: resolved by name
alone, the loose entry took another copy than the archive pass and the
profile blocked its own archive.
"""
if entry.get("archive"):
return entry
members = archive_members(entry.get("name", ""), files)
return {**entry, "members": members} if members else entry
def opens_by_name(file_entry: dict, profile: dict, standalone: bool = False) -> bool:
"""Whether the code opens this entry by its name.
A core that scans a folder and identifies firmware by content
(DuckStation by MD5, bios.cpp:208) gives its entries names that are
labels. `found_by` says which, on the file or the profile, keyed by
build when the two builds differ.
"""
for source in (file_entry, profile):
value = source.get("found_by")
if isinstance(value, dict):
value = value.get("standalone" if standalone else "libretro")
if value:
return value != "content"
return True
def read_by_build(entry: dict, standalone: bool) -> bool:
"""Whether the build that runs (standalone or libretro) reads the entry."""
return entry.get("mode") != ("libretro" if standalone else "standalone")
def filter_files_by_mode(files: list[dict], standalone: bool) -> list[dict]:
"""Filter file entries by libretro/standalone mode."""
return [f for f in files if read_by_build(f, standalone)]
def installed_with_emulator(entry: dict, platform: str = "") -> bool:
"""Whether the emulator as this platform installs it already brings the entry.
`bundled` describes the emulator's own release. A platform package can
differ both ways: Batocera's hcl package installs the binary alone and
sends users to fetch the data (`not_bundled_on`), while its blueMSX core
package copies the machines and databases beside the core
(`installed_on`).
"""
if platform and platform in (entry.get("installed_on") or []):
return True
return bool(entry.get("bundled")) and platform not in (entry.get("not_bundled_on") or [])
def installed_everywhere(entry: dict) -> bool:
"""Whether the emulator brings the entry on every setup, for a view that names none.
An entry a platform package leaves out (`not_bundled_on`) is a file that
setup's users still need: touchHLE panics without its fonts on ROCKNIX.
"""
return bool(entry.get("bundled")) and not entry.get("not_bundled_on")
def unread_on(entry: dict, platform: str) -> bool:
"""Whether this platform's launcher points the emulator at other files.
RetroBat starts standalone BlastEm with absolute paths to its own BIOS
names in the config it writes, so the defaults the emulator would read
(cdbios.bin, colecovision_bios.col) are never opened there.
"""
return bool(platform) and platform in (entry.get("unread_on") or [])
def deliverable(entries: list[dict], standalone: bool, platform: str = "") -> list[dict]:
"""The entries of one build a pack has to bring.
A file or tree installed with the emulator is already on the user's
machine: shipping it again only weighs the pack. `bundled` is scoped by
`mode` like any entry, so PPSSPP's assets, shipped by the standalone
release and not by the libretro core, still reach a RetroArch pack.
"""
return [
e for e in filter_files_by_mode(entries, standalone)
if not installed_with_emulator(e, platform) and not unread_on(e, platform)
]
def _platform_accepted(file_entry: dict, platform_digest: str) -> set[str]:
"""The values of the digest the frontend compares that the entry declares."""
declared = file_entry.get(platform_digest) or ""
if platform_digest == "md5":
return set(parse_hash_list(declared))
if isinstance(declared, str) and declared:
return {declared.lower()}
if isinstance(declared, list):
return {str(value).lower() for value in declared}
return set()
def _variant_candidates(expected: dict, db: dict, fname: str) -> Iterator[str]:
"""The sha1 of each held file that may stand for a name, best evidence first.
Any one accepted value names a candidate: the index merges what several
emulators accept, and their own checks then judge each file.
"""
# Sorted: the index holds sets, whose order follows the per-process
# string hash, and the first passing candidate is the one shipped.
for hash_type in ("sha1", "md5", "crc32", "sha256"):
for value in sorted(expected.get(hash_type) or []):
yield from records_for_hash(db, hash_type, value)
yield from db.get("indexes", {}).get("by_name", {}).get(fname, [])
def find_validated_variant(
file_entry: dict,
db: dict,
current_path: str,
validation_index: dict,
bios_dir: str = BIOS_DIR,
platform_digest: str | None = None,
emulators: set[str] | None = None,
strict: bool = False,
) -> str | None:
"""A held file the emulator's own checks accept, in place of current_path.
Candidates come first from the hashes the emulator declares, which finds
a dump stored under another name, then from the files sharing the name.
platform_digest is the hash the frontend compares ("md5", "sha1") or None
when it reads no bytes: a candidate must then also carry a value the
entry declares, since the frontend would reject anything else. The
report and the packs read this one function, so the file a report counts
as satisfying the emulator is the file a pack ships.
"""
fname = file_entry.get("name", "")
if not fname or fname not in validation_index:
return None
accepted: set[str] = set()
if platform_digest:
if file_entry.get("zipped_file"):
return None
accepted = _platform_accepted(file_entry, platform_digest)
files_db = db.get("files", {})
current_real = os.path.realpath(current_path)
seen: set[str] = set()
for sha1 in _variant_candidates(validation_index[fname], db, fname):
entry = files_db.get(sha1) or {}
path = entry.get("path", "")
if not path or not os.path.exists(path):
continue
real = os.path.realpath(path)
if real == current_real or real in seen:
continue
seen.add(real)
if accepted and str(entry.get(platform_digest, "")).lower() not in accepted:
continue
if check_file_validation(
path, fname, validation_index, bios_dir, emulators, strict
) is None:
return path
return None
def agnostic_substitute(
file_entry: dict, sys_id: str, db: dict, platform_profiles: dict[str, dict]
) -> tuple[str, str] | None:
"""(path, directory) of a held file a filename-agnostic core can boot.
A core with `bios_mode: agnostic` (PCSX2 picks any image in its BIOS
folder) is served by any image of the right size, renamed to what the
platform declares. That only satisfies a frontend that checks existence:
a digest frontend compares the bytes. Only the platform's own cores are
asked, and the pack and verify read this one answer. An entry that
declares a content hash names one file: no substitute stands for it.
"""
if lists_hashes(file_entry):
return None
by_name = db.get("indexes", {}).get("by_name", {})
files_db = db.get("files", {})
for profile in platform_profiles.values():
if profile.get("bios_mode") != "agnostic":
continue
if sys_id not in set(profile.get("systems", [])):
continue
for entry in profile.get("files", []):
for sha1 in by_name.get(entry.get("name", ""), []):
path = files_db.get(sha1, {}).get("path", "")
if not path:
continue
prefix = path.rsplit("/", 1)[0] + "/"
for candidate in files_db.values():
held = candidate.get("path", "")
if (
held.startswith(prefix)
and os.path.exists(held)
and shape_fits(entry, held, candidate.get("size", 0))
):
return held, prefix
break
return None
def frontend_digest_matches(
file_entry: dict, local_path: str | None, algorithm: str, rule: str = ""
) -> bool:
"""Whether the frontend's own digest accepts the file.
resolve_local_file calls a file `hash_mismatch` when any declared hash
disagrees, but a frontend compares one digest. verify_entry_md5 reads it
too: Recalbox hashes a ZIP by its members. Batocera compares the whole
md5 string (batocera-systems:1088), so a value cut short accepts nothing. Under SIZE_AND_ANY_HASH (RomM) the declared size must
match and then any one of md5, sha1 and crc32 does: a mistyped hash next
to a right one does not withhold the file, a wrong size does.
"""
if not local_path:
return False
def composite() -> str | None:
if ".zip" not in os.path.basename(local_path):
return None
try:
return md5_composite(local_path)
except (zipfile.BadZipFile, OSError):
return None
return digest_verdict(
file_entry, os.path.getsize(local_path), lambda: compute_hashes(local_path),
algorithm, rule, composite,
)
def digest_verdict(
file_entry: dict,
size: int,
hashes: Callable[[], dict[str, str]],
algorithm: str,
rule: str = "",
composite: Callable[[], str | None] = lambda: None,
) -> bool:
"""The frontend's acceptance rule over content given by its size, its
digests and, for an archive, its member digest.
One rule for a file on disk and for a member of a built pack: the pack
check once compared only the md5 and refused, under RomM's rule, the
revision the builder had rightly shipped on its sha1 and size.
"""
if rule == SIZE_AND_ANY_HASH:
# RomM reads an absent size as 0: such an entry never verifies.
if size != int(file_entry.get("size") or 0):
return False
digests = hashes()
return any(
digests[field].lower() == str(file_entry[field]).strip().lower()
for field in ("md5", "sha1", "crc32")
if file_entry.get(field)
)
if algorithm == "md5":
declared = parse_hash_list(file_entry.get("md5"))
else:
value = file_entry.get(algorithm)
values = value if isinstance(value, list) else [value]
declared = [str(v).strip().lower() for v in values if v]
if not declared:
return False
actual = hashes()[algorithm].lower()
if algorithm != "md5":
return actual in declared
# Recalbox hashes a .zip by its members only (Bios.cpp:64-68), so the
# container's own md5 answers nothing there.
composite_only = file_entry.get("zip_digest") == "composite"
if not composite_only and actual in declared:
return True
member_digest = composite()
if not member_digest:
return False
return member_digest.lower() in declared
def inner_rom_check(file_entry: dict, local_path: str) -> str:
"""How an archive answers an entry that pins a ROM inside it.
Batocera, RetroBat and ROCKNIX hash a member of the ZIP, never the ZIP:
the resolver hands back the archive as a mismatch and this decides it.
Returns check_inside_zip's answer for the first accepted MD5 that
matches, else for the last one tried. The pack and the install manifest
both read it, so a file one of them ships is a file the other lists.
"""
return _first_accepted_md5(
file_entry,
lambda md5: check_inside_zip(local_path, file_entry["zipped_file"], md5),
)
def inner_rom_data_check(file_entry: dict, data: bytes) -> str:
"""inner_rom_check on the bytes of an archive, as a pack holds it."""
return _first_accepted_md5(
file_entry,
lambda md5: check_inside_zip_data(data, file_entry["zipped_file"], md5),
)
def _first_accepted_md5(file_entry: dict, check: Callable[[str], str]) -> str:
# With no md5 declared, checkInsideZip still runs and needs the member.
result = "not_in_zip"
for candidate in parse_hash_list(file_entry.get("md5")) or [""]:
result = check(candidate)
if result == "ok":
break
return result
def baseline_verdict(
file_entry: dict,
local_path: str | None,
status: str,
verification_mode: str,
rule: str = "",
) -> tuple[str, str | None]:
"""The status a platform entry ships under, or why a hash platform refuses it.
Batocera hashes the member, never the ZIP: a zipped_file entry is checked
inside the archive whatever the outer resolution said, as verify does. A
frontend that hashes one digest accepts a file whose other declared
hashes disagree. The pack builder and the install manifest both read
this, so the one-line installer never places a file the pack refused.
Existence platforms never read the bytes: nothing is refused here.
"""
if not hash_mismatch_excludes_file(verification_mode):
return status, None
member = file_entry.get("zipped_file")
if member and local_path:
result = inner_rom_check(file_entry, local_path)
if result == "ok":
return "zip_exact", None
if result == "not_in_zip":
return status, f"{member} not found inside ZIP"
if result == "error":
return status, "cannot read ZIP"
return status, f"{member} MD5 mismatch inside ZIP"
if rule == SIZE_AND_ANY_HASH and local_path:
# A hash found by the resolver does not settle it: the size the
# frontend compares first can still be declared otherwise.
if frontend_digest_matches(file_entry, local_path, "", rule):
return status, None
return status, "size or hash mismatch"
if status != "hash_mismatch":
return status, None
if frontend_digest_matches(file_entry, local_path, digest_algorithm(verification_mode)):
return "frontend_digest_exact", None
return status, "hash mismatch"
def destination_owners(profiles: dict) -> dict[str, list[tuple[str, str]]]:
"""For each file name, the path tail each emulator reads it under."""
owners: dict[str, list[tuple[str, str]]] = {}
for emu_name, profile in profiles.items():
for f in profile.get("files", []):
name = str(f.get("name") or "")
if not name:
continue
for declared in {f.get("path"), f.get("standalone_path")} - {None, ""} or {name}:
owners.setdefault(name.lower(), []).append(
(str(declared).replace("\\", "/").lower(), emu_name)
)
return owners
def _owners_of(destination: str, name: str, owners: dict) -> set[str]:
"""Emulators whose declared path is the longest tail of the destination."""
destination = destination.replace("\\", "/").lower()
matching = [
(tail, emu) for tail, emu in owners.get(name.lower(), [])
if destination == tail or destination.endswith("/" + tail)
]
if not matching:
return set()
longest = max(len(tail) for tail, _emu in matching)
return {emu for tail, emu in matching if len(tail) == longest}
class Judges(TypedDict, total=False):
"""The cores that judge a file in validated_choice, each by its own entries."""
emulators: set[str] | None
def validated_choice(
file_entry: dict,
local_path: str | None,
db: dict,
validation_index: dict,
bios_dir: str,
platform_digest: str | None,
destination: str = "",
owners: dict | None = None,
**judging: Unpack[Judges],
) -> tuple[str | None, str | None]:
"""The file a platform destination ships, and the disagreement if any.
A frontend's own check can pass while an emulator it runs rejects the
file. A held variant both accept replaces it. The pack and the install
manifest both read this, so they name the same file. A destination
another emulator declares more precisely is that emulator's: ZEsarUX's
48 KB cpc6128.rom check has no say over ep128emu/roms/cpc6128.rom.
"""
unknown = sorted(set(judging) - set(Judges.__annotations__))
if unknown:
raise TypeError(f"validated_choice() got an unexpected keyword argument '{unknown[0]}'")
emulators = judging.get("emulators")
if not local_path or not validation_index:
return local_path, None
name = file_entry.get("name", "")
rules = validation_index.get(name)
judges: set[str] | None = emulators
if rules and judges is None and owners and destination:
owning = _owners_of(destination, name, owners)
if not owning & set(rules["emulators"]):
# No core that checks this name reads this destination: PC-98's
# bios.rom rules have no say over roms/ibmpcjr/bios.rom.
return local_path, None
# The cores that read this destination judge it, each by its own
# entries.
judges = owning & set(rules["emulators"])
def check(path: str, strict: bool) -> tuple[str, list[str]] | None:
return check_file_validation(path, name, validation_index, bios_dir, judges, strict)
def variant(strict: bool) -> str | None:
return find_validated_variant(
file_entry, db, local_path, validation_index, bios_dir,
platform_digest=platform_digest, emulators=judges, strict=strict,
)
if not check(local_path, True):
return local_path, None
# A held file every check passes, warn-level ones included, comes first,
# then the file itself when only a warning fails (the core runs it),
# then a held file the core at least runs.
better = variant(True)
if better:
return better, None
failed = check(local_path, False)
if not failed:
return local_path, None
better = variant(False)
if better:
return better, None
reason, failing = failed
said = f"{', '.join(failing)} says {reason}"
return local_path, Refusal(said, reason.accepted) if isinstance(reason, Refusal) else said
def existence_discrepancy(file_entry: dict, local_path: str, platform_display: str) -> str:
"""What an existence platform is told when its declared hash contradicts
the file it loads: the file is kept, the gap is said out loud. The pack
and verify both print this one line."""
declared = file_entry.get("md5", "") or file_entry.get("sha1", "")
actual = compute_hashes(local_path)
return (
f"packed per {platform_display} existence check: declared hash {declared}, "
f"file md5 {actual['md5']} sha1 {actual['sha1']}"
)
def same_slot_entries(files: list, name: str, path: str) -> list[dict]:
"""The entries of one profile that name the same file at the same path.
A profile lists every version its code takes under one name (each GRP
of Raze's table, eduke32's demo and retail NWINTER.GRP): any of them
fills the slot.
"""
return [
entry for entry in files or []
if isinstance(entry, dict) and entry.get("name") == name
and (entry.get("path") or name) == path
]
def slot_index(files: list) -> dict[tuple[str, str], list[dict]]:
"""A profile's entries keyed by (name, path), as same_slot_entries
matches them: one pass, then one lookup per extra."""
index: dict[tuple[str, str], list[dict]] = {}
for entry in files or []:
if isinstance(entry, dict) and isinstance(entry.get("name"), str):
name = entry["name"]
index.setdefault((name, entry.get("path") or name), []).append(entry)
return index
def extra_alternatives(fe: dict, profiles: Mapping | None) -> list[dict]:
"""The versions the extra's own profile accepts at the extra's slot."""
if not profiles:
return []
profile = profiles.get(fe.get("source_profile") or "", {})
name = fe.get("source_name") or fe.get("name", "")
return same_slot_entries(
profile.get("files") or [], name, fe.get("source_path") or name
)
def core_size_refusal(
file_entry: dict, local_path: str | None, alternatives: Sequence[dict] = (),
) -> str | None:
"""Why the core refuses this copy by the size its own code checks, or None.
The one rule the builder, the install manifest and verify read for a
core's file. An existence platform never opens the bytes, so a copy whose
hash disagrees still ships to it, but a core that measures the file turns
one of the wrong size away: Basilisk II stops on the Apple IIGS' 128 KB
ROM (main_unix.cpp:692), so packing that file for it serves nothing.
``alternatives`` are the other versions the profile accepts at the same
slot: a copy any of them takes is not refused.
"""
if not local_path or not os.path.isfile(local_path):
return None
size = os.path.getsize(local_path)
sized = [entry for entry in (file_entry, *alternatives) if name_match_size_ok(entry, size)]
if any(content_fits(entry, local_path) for entry in sized):
return None
if sized:
tests = sorted({check for entry in sized for check in declared_content_checks(entry)})
return f"the core's {', '.join(tests)} test turns it away"
declared = file_entry.get("size")
bounds = [] if declared is None else [str(declared)]
multiple = file_entry.get("size_multiple")
if multiple or any(file_entry.get(k) is not None for k in ("min_size", "max_size")):
window = f"{file_entry.get('min_size', 0)} to {file_entry.get('max_size', 'any')}"
bounds.append(f"{window} in multiples of {multiple}" if multiple else window)
return f"{size} bytes, the core checks for {' or '.join(bounds)}"