fix: settle a platform declaration in one place

The pack builder and the manifest each coded the copy a declaration
ships: resolve, agnostic substitute, frontend verdict, then the cores'
choice. The builder skipped the cores' choice once an earlier
declaration of the path was refused, and shipped the copy the name found
while the installer placed the variant the core accepts.
DeclarationJudge in packs/declsettle.py now settles it for both, and the
cores choose on every copy shipped.
This commit is contained in:
Abdessamad Derraz committed 2026-11-23 21:02:46 +01:00
1 parent d2f4ef6f9c
commit 5b3f0c3f4c
8 files changed
+248 -158

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
"""The copy a platform declaration ships, settled once for the pack and the manifest."""
from __future__ import annotations
from dataclasses import dataclass
from resolve.nativemode import digest_algorithm, reads_file_contents
from resolve.packfiles import resolve_declaration
from resolve.validation import agnostic_substitute, baseline_verdict, validated_choice
@dataclass(frozen=True)
class Settlement:
"""What a platform declaration comes to.
``resolved`` is the copy the resolver (or a filename-agnostic core's
substitute) found, ``path`` the copy shipped once the platform's cores
have judged it. ``status`` is the frontend's verdict, ``refusal`` why a
hash frontend rejects the copy, ``disagreement`` what a core says
against a copy the frontend accepts. ``agnostic_dir`` is set when a
substitute stands in for a file the collection does not hold.
"""
resolved: str | None
path: str | None
status: str
refusal: str | None = None
disagreement: str | None = None
agnostic_dir: str | None = None
@property
def ships(self) -> bool:
"""Whether a file is placed: found, local and not refused."""
return self.refusal is None and self.status not in ("not_found", "external")
@dataclass(frozen=True)
class DeclarationJudge:
"""The rules a platform declaration is settled by: the collection, the
frontend's verification mode and the cores the platform runs."""
db: dict
bios_dir: str
zip_contents: dict
data_registry: dict | None
offline: bool | None
verification_mode: str
hash_rule: str
profiles: dict[str, dict]
validation_index: dict
validation_owners: dict
def verdict(self, file_entry: dict, local_path: str | None, status: str) -> tuple[str, str | None]:
"""The frontend's verdict on a copy, as baseline_verdict reads it."""
return baseline_verdict(
file_entry, local_path, status, self.verification_mode, self.hash_rule,
)
def settle(
self, file_entry: dict, sys_id: str, dest: str, override: str | None,
) -> Settlement:
"""Resolve a declaration, substitute for it, judge it and let the
cores choose the copy, in the order the pack and the installer share."""
local_path, status = resolve_declaration(
file_entry, self.db, self.bios_dir, self.zip_contents, self.data_registry,
override, offline=self.offline,
)
agnostic_dir = None
if status == "not_found" and not reads_file_contents(self.verification_mode):
# A filename-agnostic core takes any image of its system,
# renamed. Only an existence frontend accepts that.
found = agnostic_substitute(file_entry, sys_id, self.db, self.profiles)
if found and found[0]:
local_path, agnostic_dir = found
status = "agnostic_fallback"
if status in ("not_found", "external"):
return Settlement(local_path, local_path, status, agnostic_dir=agnostic_dir)
# A member missing from a zipped_file archive, or a hash the
# frontend rejects.
status, refusal = self.verdict(file_entry, local_path, status)
if refusal:
return Settlement(local_path, local_path, status, refusal, agnostic_dir=agnostic_dir)
# A frontend's own check can pass while a core it runs rejects the
# file: a held variant both accept is shipped instead.
chosen, disagreement = validated_choice(
file_entry, local_path, self.db, self.validation_index, self.bios_dir,
digest_algorithm(self.verification_mode), dest, self.validation_owners,
)
return Settlement(local_path, chosen, status, None, disagreement, agnostic_dir)
+17 -36
View File
@@ -25,6 +25,7 @@ from packs.datatrees import (
pack_markers,
tree_readers,
)
from packs.declsettle import DeclarationJudge
from packs.extras import (
collect_emulator_extras,
extra_region_key,
@@ -56,14 +57,11 @@ from packs.standalone import standalone_copies, standalone_layouts
from resolve.contentlayout import TARGET_KEY
from resolve.cores import filter_systems_by_target, resolve_platform_cores as _platform_cores
from resolve.gamedata import GAME_DATA, is_game_data, platform_game_data, without_game_data
from resolve.nativemode import digest_algorithm, platform_mode, reads_file_contents
from resolve.packfiles import preferred_entries as _preferred_entries, resolve_declaration
from resolve.nativemode import platform_mode
from resolve.packfiles import preferred_entries as _preferred_entries
from resolve.validation import (
build_validation_index,
agnostic_substitute,
baseline_verdict,
destination_owners,
validated_choice,
)
if TYPE_CHECKING:
@@ -718,43 +716,26 @@ def generate_manifest(
)
config, verification_mode = build.config, build.verification_mode
declarations = DeclarationJudge(
db, bios_dir, build.zip_contents, build.data_registry, opts.offline,
verification_mode, config.get("hash_rule", ""), build.manifest_profiles,
build.manifest_validation, build.manifest_owners,
)
def settle(
file_entry: dict, sys_id: str, dest: str, override: str | None
) -> tuple[str | None, str]:
"""The file served once the slot is settled, or None and why not."""
local_path, status = resolve_declaration(
file_entry,
db,
bios_dir,
build.zip_contents,
build.data_registry,
override,
offline=opts.offline,
)
if status == "not_found" and not reads_file_contents(verification_mode):
found = agnostic_substitute(file_entry, sys_id, db, build.manifest_profiles)
if found:
local_path, status = found[0], "agnostic_fallback"
if os.path.basename(local_path) != file_entry.get("name", ""):
# The pack explains the rename in a note of its own.
build.rename_notes.add(file_entry.get("name", ""))
# The builder's verdict: a hash platform omits what its frontend
# would reject, a zipped_file archive included when the member is
# missing whatever the outer resolution said. An existence
# platform never reads the bytes.
status, refusal = baseline_verdict(
file_entry, local_path, status, verification_mode,
config.get("hash_rule", ""),
)
if refusal or status in ("not_found", "external"):
return None, "hash_mismatch" if refusal else status
settled = declarations.settle(file_entry, sys_id, dest, override)
renamed = os.path.basename(settled.resolved or "") != file_entry.get("name", "")
if settled.agnostic_dir and renamed:
# The pack explains the rename in a note of its own.
build.rename_notes.add(file_entry.get("name", ""))
if not settled.ships:
return None, "hash_mismatch" if settled.refusal else settled.status
# The variant the pack ships when an emulator rejects the
# resolved file: the installer must place the same bytes.
local_path, _disagreement = validated_choice(
file_entry, local_path, db, build.manifest_validation, bios_dir,
digest_algorithm(verification_mode), dest, build.manifest_owners,
)
return local_path, status
return settled.path, settled.status
if opts.source != "truth":
build.list_baseline(settle)
+60 -103
View File
@@ -37,6 +37,7 @@ from packs.datatrees import (
data_directory_members,
pack_markers,
)
from packs.declsettle import DeclarationJudge, Settlement
from packs.naming import system_display_name
from packs.extras import (
ExtraResolver,
@@ -58,23 +59,19 @@ from resolve.contentlayout import TARGET_KEY
from resolve.cores import platform_scope_systems, system_scope_error
from resolve.gamedata import GameDataCut, without_game_data
from resolve.nativemode import (
digest_algorithm, hash_mismatch_excludes_file, platform_mode, reads_file_contents,
hash_mismatch_excludes_file, platform_mode, reads_file_contents,
)
from resolve.packfiles import (
download_external,
preferred_entries as _preferred_entries,
resolve_declaration,
resolve_file,
)
from resolve.validation import (
build_validation_index,
parse_validation,
agnostic_substitute,
baseline_verdict,
destination_owners,
existence_discrepancy,
extra_alternatives,
validated_choice,
)
if TYPE_CHECKING:
@@ -483,15 +480,13 @@ class PlatformPackOutcome:
class _PlatformPackBuild:
"""One platform pack being written: its members and what each slot came to.
The four lookups are bound by build_platform_pack, the one place that
says how a platform file and a core extra are found and judged.
A platform file is settled by the DeclarationJudge the install manifest
reads too, and a core extra by the lookup build_platform_pack binds.
"""
plan: _PlatformPlan
zf: zipfile.ZipFile | PackRecord
resolve: Callable[[dict, str], tuple[str | None, str]]
verdict: Callable[[dict, str | None, str], tuple[str, str | None]]
judge: Callable[[dict, str | None, str], tuple[str | None, str | None]]
declarations: DeclarationJudge
resolve_extra: Callable[[dict, str], tuple[str | None, str, str]]
placed: Placed = field(init=False)
total_files: int = 0
@@ -542,9 +537,8 @@ class _PlatformPackBuild:
# judged by the member inside, and a frontend that hashes
# one digest accepts a file another declared hash
# contradicts, as verify judges it.
conflict_status, refusal = baseline_verdict(
file_entry, conflict_path, conflict_status, plan.verification_mode,
plan.config.get("hash_rule", ""),
conflict_status, refusal = self.declarations.verdict(
file_entry, conflict_path, conflict_status,
)
if conflict_status == "not_found":
self.file_status[full_dest] = "missing"
@@ -579,19 +573,21 @@ class _PlatformPackBuild:
self._write_instructions(file_entry, full_dest)
return
local_path, status = self.resolve(file_entry, full_dest)
if status == "external":
settled = self.declarations.settle(
file_entry, sys_id, dest, plan.slot_overrides.get(full_dest),
)
if settled.status == "external":
self._pack_external(file_entry, full_dest)
return
if status == "not_found":
local_path = self._agnostic_fallback(sys_id, file_entry, full_dest, already_packed)
if local_path is None:
return
status = "agnostic_fallback"
# Fall through to normal packing below
chosen = self._settle_declared(file_entry, full_dest, dest, local_path, status, already_packed)
if chosen is not None:
self._ship_declared(file_entry, full_dest, chosen, already_packed)
if settled.status == "not_found":
if not already_packed:
self.file_status[full_dest] = "missing"
self.file_reasons[full_dest] = "not found"
return
if settled.agnostic_dir and settled.resolved:
self._note_rename(file_entry, settled.resolved, settled.agnostic_dir)
if self._settle_declared(file_entry, full_dest, settled, already_packed) and settled.path:
self._ship_declared(file_entry, full_dest, settled.path, already_packed)
def _judge_unnamed(self, sys_id: str, file_entry: dict) -> None:
# EmuDeck-style entries (system:md5 whitelist, no filename).
@@ -605,7 +601,7 @@ class _PlatformPackBuild:
)
if held_status == "not_found" or not held:
self.file_status[fkey] = "missing"
elif self.verdict(file_entry, held, held_status)[1]:
elif self.declarations.verdict(file_entry, held, held_status)[1]:
self.file_status[fkey] = "excluded"
else:
self.file_status.setdefault(fkey, "ok")
@@ -655,68 +651,48 @@ class _PlatformPackBuild:
if os.path.exists(tmp_path):
os.unlink(tmp_path)
def _agnostic_fallback(
self, sys_id: str, file_entry: dict, full_dest: str, already_packed: bool,
) -> str | None:
# A filename-agnostic core takes any image of its system,
# renamed. Only an existence frontend accepts that.
def _note_rename(self, file_entry: dict, local_path: str, agnostic_path: str) -> None:
# A filename-agnostic core's substitute ships under the declared
# name: a note says which image it is.
plan = self.plan
found = None
if not reads_file_contents(plan.verification_mode):
found = agnostic_substitute(file_entry, sys_id, plan.db, plan.platform_profiles)
if not found or not found[0]:
if not already_packed:
self.file_status[full_dest] = "missing"
self.file_reasons[full_dest] = "not found"
return None
local_path, agnostic_path = found
original_name = os.path.basename(local_path)
dest_name = file_entry.get("name", "")
if original_name != dest_name and agnostic_path:
alt_names = [
entry.get("name", "")
for entry in plan.db.get("files", {}).values()
if entry.get("path", "").startswith(agnostic_path)
and entry.get("name", "") and entry.get("name", "") != original_name
]
readme_text = build_agnostic_rename_readme(dest_name, original_name, alt_names)
readme_name = f"RENAMED_{dest_name}.txt"
readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name
if readme_full not in self.placed.destinations:
write_generated_member(self.zf, self._flat(readme_full), readme_text)
self.placed.destinations.add(readme_full)
return local_path
if original_name == dest_name:
return
alt_names = [
entry.get("name", "")
for entry in plan.db.get("files", {}).values()
if entry.get("path", "").startswith(agnostic_path)
and entry.get("name", "") and entry.get("name", "") != original_name
]
readme_text = build_agnostic_rename_readme(dest_name, original_name, alt_names)
readme_name = f"RENAMED_{dest_name}.txt"
readme_full = f"{plan.base_dest}/{readme_name}" if plan.base_dest else readme_name
if readme_full not in self.placed.destinations:
write_generated_member(self.zf, self._flat(readme_full), readme_text)
self.placed.destinations.add(readme_full)
def _settle_declared(
self,
file_entry: dict,
full_dest: str,
dest: str,
local_path: str | None,
status: str,
already_packed: bool,
) -> str | None:
"""The copy a declaration ships once judged, or None when refused."""
self, file_entry: dict, full_dest: str, settled: Settlement, already_packed: bool,
) -> bool:
"""Record what a declaration came to, and whether its copy ships."""
plan = self.plan
# The verdict the install manifest reads too: a member missing
# from a zipped_file archive, or a hash the frontend rejects.
status, refusal = self.verdict(file_entry, local_path, status)
if refusal:
if settled.refusal:
# An earlier declaration of this path shipped a file this
# one refuses: it is in the pack, untested as verify
# counts it, not excluded.
self.file_status[full_dest] = "untested" if already_packed else "excluded"
self.file_reasons[full_dest] = refusal
return None
self.file_reasons[full_dest] = settled.refusal
return False
if not hash_mismatch_excludes_file(plan.verification_mode) and (
status == "hash_mismatch" and local_path
settled.status == "hash_mismatch" and settled.resolved
):
# Existence platforms accept any file at the declared path:
# their code never reads the bytes. An upstream hash that
# contradicts a local dump is reported, not acted on.
self.file_reasons.setdefault(
full_dest,
existence_discrepancy(file_entry, local_path, plan.platform_display),
existence_discrepancy(file_entry, settled.resolved, plan.platform_display),
)
if self.file_status.get(full_dest) == "missing":
# An earlier declaration of this path found nothing, and this
@@ -726,16 +702,14 @@ class _PlatformPackBuild:
self.file_status.setdefault(full_dest, "ok")
# Emulator-level validation: informational only for platform packs.
# Platform verification (existence/md5) is the authority for pack status.
# Emulator checks are supplementary: logged but don't downgrade.
# When a discrepancy is found, try to find a file satisfying both.
if self.file_status.get(full_dest) == "ok":
local_path, disagreement = self.judge(file_entry, local_path, dest)
if disagreement:
self.file_reasons.setdefault(
full_dest, f"{plan.platform_display} says OK but {disagreement}"
)
return local_path
# Platform verification (existence/md5) is the authority for pack
# status. The copy the cores chose ships whatever an earlier
# declaration of this path came to, as the installer places it.
if settled.disagreement and self.file_status.get(full_dest) == "ok":
self.file_reasons.setdefault(
full_dest, f"{plan.platform_display} says OK but {settled.disagreement}"
)
return True
def _ship_declared(
self, file_entry: dict, full_dest: str, local_path: str, already_packed: bool,
@@ -1092,28 +1066,11 @@ def build_platform_pack(
if isinstance(plan, str):
return PlatformPackOutcome(zip_path=None, refusal=plan)
def resolve(file_entry: dict, full_dest: str) -> tuple[str | None, str]:
return resolve_declaration(
file_entry,
db,
bios_dir,
plan.zip_contents,
opts.data_registry,
plan.slot_overrides.get(full_dest),
offline=opts.offline,
)
def verdict(file_entry: dict, local_path: str | None, status: str) -> tuple[str, str | None]:
return baseline_verdict(
file_entry, local_path, status, plan.verification_mode,
plan.config.get("hash_rule", ""),
)
def judge(file_entry: dict, local_path: str | None, dest: str) -> tuple[str | None, str | None]:
return validated_choice(
file_entry, local_path, db, plan.validation_index, bios_dir,
digest_algorithm(plan.verification_mode), dest, plan.validation_owners,
)
declarations = DeclarationJudge(
db, bios_dir, plan.zip_contents, opts.data_registry, opts.offline,
plan.verification_mode, plan.config.get("hash_rule", ""), plan.platform_profiles,
plan.validation_index, plan.validation_owners,
)
extra_resolver = ExtraResolver(
db, bios_dir, plan.zip_contents, opts.data_registry, plan.validation_index,
@@ -1127,7 +1084,7 @@ def build_platform_pack(
contextlib.nullcontext(opts.record) if opts.record is not None
else writing_pack(plan.zip_path)
) as zf:
build = _PlatformPackBuild(plan, zf, resolve, verdict, judge, resolve_extra)
build = _PlatformPackBuild(plan, zf, declarations, resolve_extra)
build.run()
if opts.counts is not None:
opts.counts.append(pack_counts(plan.zip_path, build.file_status, build.core_count))
+1
View File
@@ -25,6 +25,7 @@ COMMANDS = {
"packs/packoptions.py", "packs/packmodes.py", "packs/packcounts.py",
"packs/emulatorentries.py", "packs/integrity.py",
"packs/hashinput.py", "packs/hashlookup.py", "packs/executable.py",
"packs/declsettle.py",
),
"verify.py": (
"packs/verdicts.py", "packs/gaps.py", "packs/coverage.py", "packs/emulatorcheck.py",
+1 -1
View File
@@ -48,7 +48,7 @@ class AgnosticSubstitute(unittest.TestCase):
def test_every_reader_calls_it_behind_the_existence_gate(self):
builder = script_source("generate_pack.py")
verify = script_source("verify.py")
self.assertEqual(builder.count("agnostic_substitute(file_entry, sys_id"), 2)
self.assertEqual(builder.count("agnostic_substitute(file_entry, sys_id"), 1)
self.assertEqual(verify.count("agnostic_substitute(file_entry, sys_id"), 1)
for source in (builder, verify):
for call in re.finditer(r"agnostic_substitute\(file_entry, sys_id", source):
+10 -3
View File
@@ -1563,9 +1563,16 @@ class OneBaselineVerdict(unittest.TestCase):
)
body = ast.get_source_segment(source, function) or ""
with self.subTest(function=name):
self.assertIn("baseline_verdict(", body)
self.assertIn("resolve_declaration(", body)
self.assertIn("DeclarationJudge(", body)
self.assertNotIn('"slot_arbitrated"', body)
judge = next(
node for node in tree.body
if isinstance(node, ast.ClassDef) and node.name == "DeclarationJudge"
)
body = ast.get_source_segment(source, judge) or ""
self.assertIn("baseline_verdict(", body)
self.assertIn("resolve_declaration(", body)
self.assertNotIn('"slot_arbitrated"', body)
def test_verify_and_the_region_pass_resolve_as_the_builder(self):
"""verify called common.resolve_local_file and put the slot override
@@ -3911,7 +3918,7 @@ class APathConflictKeepsTheMainVerdict(unittest.TestCase):
source = script_source("generate_pack.py")
branch = source[source.index("Content ships under the conflicting shape"):]
branch = branch[: branch.index("storage = file_entry.get")]
self.assertIn("baseline_verdict(", branch)
self.assertIn("self.declarations.verdict(", branch)
self.assertNotIn('conflict_status == "hash_mismatch"', branch)
+49
View File
@@ -96,5 +96,54 @@ class TwinDeclarationStatus(unittest.TestCase):
self._check(self._config("zzz", "bbb"))
class TheCoresChooseAfterARefusal(TwinDeclarationStatus):
"""A refused declaration left "excluded" on the path, and the builder
then skipped the cores' choice for the next declaration: the pack held
the copy the name found while the installer placed the variant the core
accepts."""
ACCEPTED = b"the firmware the core checks, sixty-four bytes long........."
def test_the_pack_ships_the_variant_the_manifest_places(self):
from packs.manifest import generate_manifest
accepted_sha1 = hashlib.sha1(self.ACCEPTED).hexdigest()
Path("bios/Other").mkdir()
Path("bios/Other/fw.bin").write_bytes(self.ACCEPTED)
files = dict(self.db["files"])
files[accepted_sha1] = {
"path": "bios/Other/fw.bin", "name": "fw.bin", "size": len(self.ACCEPTED),
"sha1": accepted_sha1, "md5": hashlib.md5(self.ACCEPTED).hexdigest(),
"sha256": hashlib.sha256(self.ACCEPTED).hexdigest(), "crc32": "00000002",
}
self.db = {"files": files, "indexes": build_indexes(files, {})}
self.assertEqual(self.db["indexes"]["by_name"]["fw.bin"][0], SHA1)
profile = {
"emulator": "Core", "type": "libretro", "systems": ["bbb"],
"files": [{"name": "fw.bin", "size": len(self.ACCEPTED), "validation": ["size"]}],
}
Path("emulators/core.yml").write_text(yaml.dump(profile))
config = self._config("bbb", "aaa")
config["cores"] = ["core"]
config["version"] = "1"
Path("platforms/twin.yml").write_text(yaml.dump(config))
_platform_config_cache.clear()
record = archive.PackRecord()
with contextlib.redirect_stdout(io.StringIO()):
platformpack.generate_pack(
"twin", "platforms", self.db, "bios", "out",
emulators_dir="emulators", emu_profiles={"core": profile},
record=record, offline=True,
)
manifest = generate_manifest(
"twin", "platforms", self.db, "bios", "platforms/_registry.yml",
emulators_dir="emulators", emu_profiles={"core": profile}, offline=True,
)
served = {entry["dest"]: entry["sha1"] for entry in manifest["files"]}
self.assertEqual(served.get("fw.bin"), accepted_sha1)
self.assertEqual(record.sources.get("fw.bin"), "bios/Other/fw.bin")
if __name__ == "__main__":
unittest.main()
+21 -15
View File
@@ -85,16 +85,22 @@ class ValidatedChoice(unittest.TestCase):
def test_pack_and_manifest_both_read_it(self):
tree = ast.parse(script_source("generate_pack.py"))
callers = {
node.name
for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef)
and any(
isinstance(call, ast.Call) and getattr(call.func, "id", None) == "validated_choice"
for call in ast.walk(node)
)
}
self.assertLessEqual({"build_platform_pack", "generate_manifest"}, callers)
def callers_of(name: str) -> set[str]:
return {
node.name
for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef)
and any(
isinstance(call, ast.Call) and getattr(call.func, "id", None) == name
for call in ast.walk(node)
)
}
# A platform declaration is settled by one judge, which reads it on
# every copy shipped.
self.assertLessEqual({"build_platform_pack", "generate_manifest"}, callers_of("DeclarationJudge"))
self.assertIn("settle", callers_of("validated_choice"))
# The manifest's core extras go through the builder's own lookup,
# which reads validated_choice (packextras.ExtraResolver).
resolvers = {
@@ -125,11 +131,11 @@ class ValidatedChoice(unittest.TestCase):
node for node in ast.walk(tree)
if isinstance(node, ast.FunctionDef) and node.name == "build_platform_pack"
)
calls = [
call for call in ast.walk(builder)
if isinstance(call, ast.Call) and getattr(call.func, "id", None) == "validated_choice"
]
self.assertGreaterEqual(len(calls), 1)
# The baseline goes through the judge the manifest reads too.
self.assertTrue(any(
isinstance(call, ast.Call) and getattr(call.func, "id", None) == "DeclarationJudge"
for call in ast.walk(builder)
))
# The core extras go through the lookup verify shares, which judges.
self.assertTrue(any(
isinstance(call, ast.Call) and getattr(call.func, "attr", None) == "resolve"