"""A pack is a function of its inputs, not of the clock it was built on.""" from __future__ import annotations import tests import hashlib import os import tempfile import time import unittest import zipfile from pathlib import Path from scripts.packs.archive import FIXED_DATE_TIME class TestPackDeterminism(unittest.TestCase): """A pack is a function of its inputs, not of the clock it was built on.""" def setUp(self): self._tmp = tempfile.TemporaryDirectory() self.tmp = Path(self._tmp.name) self.bios = self.tmp / "bios" self.platforms = self.tmp / "platforms" self.bios.mkdir() self.platforms.mkdir() payload = b"DETERMINISM_PAYLOAD" (self.bios / "boot.rom").write_bytes(payload) sha1 = hashlib.sha1(payload).hexdigest() # A romset goes through the deterministic rebuild, which stages the # archive in a temporary file. Copying that file into the pack took # its mtime, the wall clock, so 348 members of the real Recalbox # pack moved between two builds while every byte matched. Without a # romset here the fixture never reaches that path. romset = self.bios / "romset.zip" with zipfile.ZipFile(romset, "w") as archive: archive.writestr("rom_a.bin", b"ROM A CONTENT") archive.writestr("rom_b.bin", b"ROM B CONTENT") rom_bytes = romset.read_bytes() rom_sha1 = hashlib.sha1(rom_bytes).hexdigest() self.db = { "generated_at": "2026-01-02T03:04:05Z", "files": { sha1: { "path": str(self.bios / "boot.rom"), "name": "boot.rom", "size": len(payload), "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), }, rom_sha1: { "path": str(romset), "name": "romset.zip", "size": len(rom_bytes), "sha1": rom_sha1, "md5": hashlib.md5(rom_bytes).hexdigest(), }, }, "indexes": { "by_md5": {hashlib.md5(payload).hexdigest(): sha1}, "by_name": {"boot.rom": [sha1], "romset.zip": [rom_sha1]}, "by_crc32": {}, "by_sha256": {}, "by_path_suffix": {}, }, } (self.platforms / "detplat.yml").write_text( "platform: DetPlat\n" "verification_mode: existence\n" "base_destination: system\n" "systems:\n" " test-sys:\n" " files:\n" " - name: boot.rom\n" " destination: boot.rom\n" " required: true\n" " - name: romset.zip\n" " destination: romset.zip\n" " required: true\n" ) def tearDown(self): self._tmp.cleanup() def _build(self, out_name: str) -> Path: from scripts.packs.platformpack import generate_pack out = self.tmp / out_name out.mkdir() path = generate_pack( "detplat", str(self.platforms), self.db, str(self.bios), str(out), offline=True, ) self.assertIsNotNone(path) return Path(path) def test_two_builds_are_byte_identical(self): first = self._build("out1") time.sleep(2.1) # ZIP mtimes are 2s-granular: cross a whole tick second = self._build("out2") self.assertEqual( hashlib.sha256(first.read_bytes()).hexdigest(), hashlib.sha256(second.read_bytes()).hexdigest(), ) def test_the_rebuild_path_ran(self): """Guard the guard: a fixture without a romset proves nothing.""" pack = self._build("out1") with zipfile.ZipFile(pack) as zf: names = {i.filename.rsplit("/", 1)[-1] for i in zf.infolist()} self.assertIn("romset.zip", names) def test_a_romset_is_the_collection_bytes_and_the_wiki_says_so(self): """The pack copies each ZIP byte for byte since fed03c3db, and the wiki still told a third party to rebuild romsets to compare.""" pack = self._build("out1") with zipfile.ZipFile(pack) as zf: member = next(n for n in zf.namelist() if n.endswith("romset.zip")) self.assertEqual(zf.read(member), (self.bios / "romset.zip").read_bytes()) root = Path(__file__).resolve().parent.parent / "wiki" for page in ("architecture.md", "tools.md"): with self.subTest(page=page): text = " ".join((root / page).read_text(encoding="utf-8").split()) self.assertNotIn("rebuilt deterministically", text) self.assertNotIn("rebuilds MAME", text) self.assertNotIn("Rebuild MAME BIOS ZIPs", text) def test_every_member_carries_the_fixed_epoch(self): """A member's date must come from the build's inputs, not its clock. ZipFile.write copies the source file's mtime, which is the checkout time for a collection file and the wall clock for one staged in tmp/. """ pack = self._build("out1") with zipfile.ZipFile(pack) as zf: dates = {i.date_time for i in zf.infolist()} self.assertEqual(dates, {FIXED_DATE_TIME}) def test_generated_members_carry_the_fixed_epoch(self): pack = self._build("out1") with zipfile.ZipFile(pack) as zf: generated = [ i for i in zf.infolist() if i.filename.rsplit("/", 1)[-1].startswith( ("README.txt", "INSTRUCTIONS_", "RENAMED_") ) ] self.assertTrue(generated, "pack should carry a generated README") for info in generated: self.assertEqual(info.date_time, FIXED_DATE_TIME) def _build_emulator(self, out_name: str) -> Path: from scripts.packs.emulatorpack import generate_emulator_pack out = self.tmp / out_name out.mkdir() (self.tmp / "emulators").mkdir(exist_ok=True) (self.tmp / "emulators" / "detcore.yml").write_text( "emulator: detcore\n" "type: libretro\n" "display_name: DetCore\n" "systems: [test-sys]\n" "cores: [detcore]\n" "files:\n" " - name: boot.rom\n" " system: test-sys\n" " required: true\n" " - name: romset.zip\n" " system: test-sys\n" " required: true\n" ) from model.profiles import emulator_profiles_cache emulator_profiles_cache.clear() path = generate_emulator_pack( ["detcore"], str(self.tmp / "emulators"), self.db, str(self.bios), str(out), offline=True, ) emulator_profiles_cache.clear() self.assertIsNotNone(path) return Path(path) def test_an_emulator_pack_is_byte_identical_too(self): """A distinct build path, and one the platform packs do not cover.""" first = self._build_emulator("emu1") time.sleep(2.1) second = self._build_emulator("emu2") self.assertEqual( hashlib.sha256(first.read_bytes()).hexdigest(), hashlib.sha256(second.read_bytes()).hexdigest(), ) def test_every_emulator_pack_member_carries_the_fixed_epoch(self): pack = self._build_emulator("emu1") with zipfile.ZipFile(pack) as zf: self.assertEqual({i.date_time for i in zf.infolist()}, {FIXED_DATE_TIME}) def test_an_executable_source_stays_executable(self): """Pinning the mode stripped the bit the RetroDECK pack needs. It ships the two Voxatron engine binaries, and extracted at 644 they cannot be run. The bit is read from the header, as the manifest reads it, so a ROM committed with an execute bit stays 644. """ import os import stat as stat_module runnable = self.bios / "engine.bin" runnable.write_bytes(b"\x7fELF NOT REALLY") os.chmod(runnable, 0o644) os.chmod(self.bios / "boot.rom", 0o755) digest = hashlib.sha1(runnable.read_bytes()).hexdigest() self.db["files"][digest] = { "path": str(runnable), "name": "engine.bin", "size": runnable.stat().st_size, "sha1": digest, "md5": hashlib.md5(runnable.read_bytes()).hexdigest(), } self.db["indexes"]["by_name"]["engine.bin"] = [digest] config = (self.platforms / "detplat.yml") config.write_text( config.read_text() + " - name: engine.bin\n" + " destination: engine.bin\n" + " required: true\n" ) pack = self._build("exec1") with zipfile.ZipFile(pack) as zf: modes = { i.filename.rsplit("/", 1)[-1]: (i.external_attr >> 16) & 0o777 for i in zf.infolist() } self.assertIn("engine.bin", modes, sorted(modes)) self.assertEqual( modes["engine.bin"] & stat_module.S_IXUSR, stat_module.S_IXUSR, "a runnable payload must stay runnable after extraction", ) self.assertEqual( modes["boot.rom"] & 0o777, 0o644, "a plain ROM keeps the fixed mode, whatever the local filesystem says", ) def test_injected_manifest_is_pinned_to_the_database(self): from scripts.packs.finalize import inject_manifest from scripts.packs.integrity import verify_pack pack = self._build("out1") ok, manifest = verify_pack(str(pack), self.db) self.assertTrue(ok, manifest.get("errors")) self.assertEqual(manifest["generated"], self.db["generated_at"]) inject_manifest(str(pack), manifest) with zipfile.ZipFile(pack) as zf: info = zf.getinfo("manifest.json") self.assertEqual(info.date_time, FIXED_DATE_TIME) class ManifestInjectionIsAtomic(unittest.TestCase): """inject_manifest appended to the final pack in place: zipfile writes the member over the old central directory and the new one only on close, so a process killed in between left a BadZipFile where a valid pack had been.""" def test_a_kill_mid_write_leaves_the_pack_readable(self): import tempfile from unittest import mock from scripts.packs import finalize with tempfile.TemporaryDirectory() as d: pack = Path(d) / "Pack.zip" with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as zf: for i in range(20): zf.writestr(f"bios/{i}.bin", os.urandom(4096)) before = pack.read_bytes() def die(zf, name, text): zf.writestr(name, text) zf.fp.flush() raise KeyboardInterrupt with mock.patch.object(finalize, "write_generated_member", die), \ self.assertRaises(KeyboardInterrupt): finalize.inject_manifest(str(pack), {"files": ["x"] * 2000}) self.assertEqual(pack.read_bytes(), before) self.assertEqual( [p.name for p in Path(d).iterdir()], ["Pack.zip"], "the scratch copy is removed", ) class PackMemberCompression(unittest.TestCase): """A pack deflated every member, archives and PNGs included: 16 GB of already-compressed data deflated again on each full build for 0.18 % of the packs' size.""" def _pack(self, tmp: Path, name: str) -> Path: from scripts.packs.archive import add_pack_member source = tmp / "member" source.write_bytes(b"\x00" * 4096) pack = tmp / name with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as zf: for arcname in ("bios/a.zip", "bios/b.PNG", "bios/c.bin", "bios/d.pk3"): add_pack_member(zf, str(source), arcname) return pack def test_compressed_formats_are_stored_and_the_rest_deflated(self): with tempfile.TemporaryDirectory() as tmp: pack = self._pack(Path(tmp), "pack.zip") with zipfile.ZipFile(pack) as zf: kinds = {i.filename: i.compress_type for i in zf.infolist()} self.assertEqual(kinds, { "bios/a.zip": zipfile.ZIP_STORED, "bios/b.PNG": zipfile.ZIP_STORED, "bios/c.bin": zipfile.ZIP_DEFLATED, "bios/d.pk3": zipfile.ZIP_DEFLATED, }) def test_the_pack_stays_byte_reproducible(self): with tempfile.TemporaryDirectory() as tmp: first = self._pack(Path(tmp), "one.zip").read_bytes() time.sleep(1.1) second = self._pack(Path(tmp), "two.zip").read_bytes() self.assertEqual(hashlib.sha256(first).hexdigest(), hashlib.sha256(second).hexdigest()) if __name__ == "__main__": unittest.main()