diff --git a/tests/test_conformance_diff_output_paths.py b/tests/test_conformance_diff_output_paths.py new file mode 100644 index 0000000000..7ab2f9c1bb --- /dev/null +++ b/tests/test_conformance_diff_output_paths.py @@ -0,0 +1,168 @@ +"""Synthetic CLI tests for conformance heatmap output paths.""" +import importlib.util +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "conformance" / "compare.py" +SPEC = importlib.util.spec_from_file_location("conformance_compare_output_paths", SCRIPT) +C = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = C +SPEC.loader.exec_module(C) + + +class DiffOutputPathTest(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.root = Path(temp.name) + self.reference_dir = self.root / "reference" + self.candidate_dir = self.root / "candidate" + self.reference_dir.mkdir() + self.candidate_dir.mkdir() + self.reference = self.reference_dir / "manifest.json" + self.candidate = self.candidate_dir / "manifest.json" + + def write_inputs(self, manifest, image_dir, scenes): + rows = [] + for name, filename in scenes: + image = image_dir / filename + C.write_png(image, C.make_solid_raster(1, 1, C.PNG_COLOUR_TYPE_RGB, (10, 20, 30), str(image))) + rows.append({"name": name, "png": filename, + "checks": [{"x": 0, "y": 0, "r": 10, "g": 20, "b": 30, "a": 255}]}) + C.write_selftest_manifest(manifest, "synthetic", "CPU", rows) + + def write_default_inputs(self): + self.write_inputs(self.reference, self.reference_dir, [("scene", "frame.png")]) + self.write_inputs(self.candidate, self.candidate_dir, [("scene", "frame.png")]) + + def run_diff(self, *options): + return subprocess.run( + [sys.executable, "-IB", "-X", "utf8", str(SCRIPT), "diff", "--reference", str(self.reference), + "--candidate", str(self.candidate), *options], + capture_output=True, encoding="utf-8", timeout=15, + ) + + def snapshot(self): + return {path.relative_to(self.root): path.read_bytes() for path in self.root.rglob("*") if path.is_file()} + + def assert_refuses_collision(self, output, other, *options): + before = self.snapshot() + result = self.run_diff(*options) + self.assertEqual(result.returncode, 2, result.stdout + result.stderr) + self.assertIn(str(output), result.stderr) + self.assertIn(str(other), result.stderr) + self.assertEqual(self.snapshot(), before) + + def test_first_heatmap_is_a_later_candidate_image(self): + self.write_inputs(self.reference, self.reference_dir, [("first", "one.png"), ("second", "two.png")]) + self.write_inputs(self.candidate, self.candidate_dir, [("first", "one.png"), ("second", "first.diff.png")]) + collision = self.candidate_dir / "first.diff.png" + self.assert_refuses_collision(collision, collision) + + def test_later_collision_is_rejected_before_any_heatmap_is_written(self): + self.write_inputs(self.reference, self.reference_dir, [("first", "one.png"), ("second", "two.png")]) + self.write_inputs(self.candidate, self.candidate_dir, [("first", "second.diff.png"), ("second", "two.png")]) + collision = self.candidate_dir / "second.diff.png" + self.assert_refuses_collision(collision, collision) + + def test_explicit_image_directories_can_make_a_heatmap_alias_a_reference_image(self): + images = self.root / "images" + images.mkdir() + self.write_inputs(self.reference, images, [("scene", "scene.diff.png")]) + self.write_inputs(self.candidate, images, [("scene", "frame.png")]) + collision = images / "scene.diff.png" + self.assert_refuses_collision(collision, collision, "--reference-dir", str(images), + "--candidate-dir", str(images)) + + def test_heatmap_cannot_replace_either_manifest(self): + self.write_default_inputs() + default_reference, default_candidate = self.reference, self.candidate + collision = self.candidate_dir / "scene.diff.png" + for side in ("reference", "candidate"): + with self.subTest(side=side): + self.reference, self.candidate = default_reference, default_candidate + collision.write_bytes(getattr(self, side).read_bytes()) + setattr(self, side, collision) + self.assert_refuses_collision(collision, collision, "--reference-dir", str(self.reference_dir)) + + def test_heatmap_matches_candidate_image_on_a_case_insensitive_volume(self): + self.write_inputs(self.reference, self.reference_dir, [("scene", "frame.png")]) + self.write_inputs(self.candidate, self.candidate_dir, [("scene", "SCENE.DIFF.PNG")]) + output = self.candidate_dir / "scene.diff.png" + if not output.is_file(): + self.skipTest("output directory is case-sensitive") + self.assert_refuses_collision(output, self.candidate_dir / "SCENE.DIFF.PNG") + + def test_heatmap_link_to_a_reference_image(self): + self.write_default_inputs() + source = self.reference_dir / "frame.png" + output = self.candidate_dir / "scene.diff.png" + for link in (os.link, os.symlink): + with self.subTest(link=link.__name__): + try: + link(source, output) + except OSError as exc: + self.skipTest(f"{link.__name__} unavailable: {exc}") + try: + self.assert_refuses_collision(output, source) + finally: + output.unlink() + + def test_two_heatmaps_share_a_file(self): + scenes = [("first", "one.png"), ("second", "two.png")] + self.write_inputs(self.reference, self.reference_dir, scenes) + self.write_inputs(self.candidate, self.candidate_dir, scenes) + first = self.candidate_dir / "first.diff.png" + second = self.candidate_dir / "second.diff.png" + first.write_bytes(b"old heatmap") + try: + os.link(first, second) + except OSError as exc: + self.skipTest(f"hard links unavailable: {exc}") + self.assert_refuses_collision(first, second) + + def test_missing_case_only_heatmaps_follow_directory_case_rules(self): + scenes = [("scene", "one.png"), ("SCENE", "two.png")] + self.write_inputs(self.reference, self.reference_dir, scenes) + self.write_inputs(self.candidate, self.candidate_dir, scenes) + first = self.candidate_dir / "scene.diff.png" + second = self.candidate_dir / "SCENE.diff.png" + self.assertFalse(first.exists()) + self.assertFalse(second.exists()) + if (self.candidate_dir / "ONE.PNG").exists(): + self.assert_refuses_collision(second, first) + else: + result = self.run_diff() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertFalse(first.samefile(second)) + + def test_dangling_heatmap_symlink_aliases_a_missing_heatmap(self): + scenes = [("first", "one.png"), ("second", "two.png")] + self.write_inputs(self.reference, self.reference_dir, scenes) + self.write_inputs(self.candidate, self.candidate_dir, scenes) + first = self.candidate_dir / "first.diff.png" + second = self.candidate_dir / "second.diff.png" + try: + second.symlink_to(first.name) + except OSError as exc: + self.skipTest(f"symlink unavailable: {exc}") + self.assert_refuses_collision(second, first) + self.assertFalse(first.exists()) + self.assertEqual(second.readlink(), Path(first.name)) + + def test_diff_still_replaces_an_existing_noncolliding_heatmap(self): + self.write_default_inputs() + heatmap = self.candidate_dir / "scene.diff.png" + heatmap.write_bytes(b"old heatmap") + result = self.run_diff() + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual(C.read_png(heatmap).pixel_rgba(0, 0), (48, 48, 48, 255)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_report_paths.py b/tests/test_report_paths.py index af7ce75453..dfdea3ca76 100644 --- a/tests/test_report_paths.py +++ b/tests/test_report_paths.py @@ -60,6 +60,7 @@ def test_existing_files_take_priority_over_a_matching_normalized_name(self): # Simulate a name rule folding two spellings that the directory keeps distinct. with mock.patch.object(report_paths, "_resolved_key", return_value="report.json"): self.assertFalse(report_paths.same_report_path(first, second)) + self.assertIsNone(report_paths.find_report_path_collision([first], [second])) def test_paths_that_do_not_exist_yet(self): self.assertTrue(report_paths.same_report_path(self.p("new", "x.json"), self.p("new", "..", "new", "x.json"))) @@ -79,6 +80,7 @@ def test_missing_paths_follow_a_case_sensitive_windows_directory(self): with self.subTest(first=first, second=second): self.assertFalse(report_paths.same_report_path(self.p(first), self.p(second))) self.assertFalse(report_paths.same_report_path(self.p(second), self.p(first))) + self.assertIsNone(report_paths.find_report_path_collision([self.p(first)], [self.p(second)])) self.assertEqual(os.listdir(self.dir), ["Existing.json"]) def test_one_missing_one_present_is_not_an_error(self): @@ -131,6 +133,8 @@ def test_macos_case_insensitive_volume_folds_case_and_accents(self): self.assertEqual(report_paths.path_key("/tmp/leonida_x/café.json"), report_paths.path_key("/tmp/leonida_x/café.json")) self.assertTrue(report_paths.same_report_path("/tmp/leonida_x/R.json", "/tmp/leonida_x/r.json")) + first, second = "/tmp/leonida_x/café.json", "/tmp/leonida_x/café.json" + self.assertEqual(report_paths.find_report_path_collision([first], [second]), (second, first, True)) def test_macos_case_sensitive_volume_keeps_case(self): with self.darwin(1): @@ -202,6 +206,13 @@ def test_same_report_path_asks_the_volume_when_the_name_rules_disagree(self): self.assertTrue(report_paths.same_report_path(self.p("R.json"), self.p("r.json"))) probe.assert_called_once_with(os.path.realpath(self.p("R.json")), os.path.realpath(self.p("r.json"))) + def test_indexed_check_asks_the_volume_when_the_name_keys_disagree(self): + first, second = self.p("R.json"), self.p("r.json") + with mock.patch.object(report_paths, "_resolved_key", side_effect=os.path.realpath), \ + mock.patch.object(report_paths, "_same_resolved_name", return_value=True) as probe: + self.assertEqual(report_paths.find_report_path_collision([first], [second]), (second, first, True)) + probe.assert_called_once_with(os.path.realpath(second), os.path.realpath(first)) + def test_each_path_is_resolved_once_per_call(self): # #6220's review: the key and the volume probe both want the resolved names, so resolving each path # once costs two realpath calls per guard, not four. A guard runs once per input file, so this is the diff --git a/tools/conformance/COMPARE.md b/tools/conformance/COMPARE.md index 30c2b3b84e..079037f6e9 100644 --- a/tools/conformance/COMPARE.md +++ b/tools/conformance/COMPARE.md @@ -11,14 +11,16 @@ box). Python 3.8 or newer is needed for the language features used. ``` D:\conform\tools\ - compare.py the tool - README.md this file + report_paths.py + conformance\ + compare.py + COMPARE.md ``` On the conformance box: ```powershell -& "$env:LOCALAPPDATA\Programs\Python\Python312\python.exe" D:\conform\tools\compare.py --help +& "$env:LOCALAPPDATA\Programs\Python\Python312\python.exe" D:\conform\tools\conformance\compare.py --help ``` Elsewhere, `python compare.py --help` is enough. @@ -185,14 +187,17 @@ same size as the candidate: `(255, 0, 0)`, and the ramp passes through purple. Alpha differences count. Heatmaps are written for passing scenes too, so a clean run leaves a complete -visual record. Existing files are overwritten. The tool is deterministic: the -same inputs produce byte-identical heatmaps (verified with SHA-256 over two -runs). +visual record. Each heatmap replaces any existing file at its output path if +that path is distinct from all inputs and other outputs. The same inputs +produce byte-identical heatmaps (verified with SHA-256 over two runs). ### diff failures that are not pixel differences - Missing or extra scene names in the candidate manifest: error names them and exits 2. There is nothing meaningful to compare. +- A heatmap path names either manifest, any input image or another heatmap: + error names both paths and exits 2 before writing any heatmaps. Path aliases + such as links count as collisions. - Different image sizes: error names both paths and their sizes and exits 2. - Unreadable or unsupported image: error names the file and exits 2. diff --git a/tools/conformance/compare.py b/tools/conformance/compare.py index 78454e0f4a..1f37726413 100644 --- a/tools/conformance/compare.py +++ b/tools/conformance/compare.py @@ -26,6 +26,10 @@ import zlib from dataclasses import dataclass +# Isolated mode leaves the shared tools directory off sys.path. +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) +from report_paths import find_report_path_collision # noqa: E402 + EXIT_PASSED = 0 EXIT_FAILED = 1 EXIT_ERROR = 2 @@ -1009,6 +1013,17 @@ def match_manifest_scenes(reference, candidate): ) +def check_heatmap_paths(input_paths, heatmap_paths): + """Reject collisions before writing any of the heatmaps.""" + collision = find_report_path_collision(input_paths, heatmap_paths) + if collision is None: + return + output, other, is_input = collision + if is_input: + raise ToolError(f"heatmap '{output}' would overwrite comparison input '{other}'") + raise ToolError(f"heatmap '{output}' shares its destination with heatmap '{other}'") + + def command_diff(arguments): """Run the diff mode: metrics, heatmaps, thresholds and exit code.""" reference = load_manifest(arguments.reference) @@ -1017,6 +1032,18 @@ def command_diff(arguments): candidate_directory = resolve_image_directory(candidate, arguments.candidate_dir) match_manifest_scenes(reference, candidate) + # Each manifest names its own files. Plan every scene's paths before opening any output. + candidate_scenes_by_name = {scene.name: scene for scene in candidate.scenes} + input_paths = [reference.manifest_path, candidate.manifest_path] + scene_paths = [] + for scene in reference.scenes: + reference_path = scene_image_path(reference_directory, scene.png_name) + candidate_path = scene_image_path(candidate_directory, candidate_scenes_by_name[scene.name].png_name) + heatmap_path = os.path.join(candidate_directory, f"{scene.name}.diff.png") + input_paths.extend((reference_path, candidate_path)) + scene_paths.append((scene.name, reference_path, candidate_path, heatmap_path)) + check_heatmap_paths(input_paths, [output for _, _, _, output in scene_paths]) + print(f"reference: {reference.manifest_path}") print(f" renderer '{reference.renderer}', adapter '{reference.adapter}'") print(f"candidate: {candidate.manifest_path}") @@ -1026,31 +1053,24 @@ def command_diff(arguments): # printed above the header it belongs to when output is redirected. sys.stdout.flush() - # Each manifest names its own files, so look up the candidate scene itself - # rather than assuming both renderers wrote the same PNG file name. - candidate_scenes_by_name = {scene.name: scene for scene in candidate.scenes} scene_column_width = max(len(scene.name) for scene in reference.scenes) failing_scenes = [] - for scene in reference.scenes: - candidate_scene = candidate_scenes_by_name[scene.name] - reference_image = read_png(scene_image_path(reference_directory, scene.png_name)) - candidate_image = read_png( - scene_image_path(candidate_directory, candidate_scene.png_name) - ) + for name, reference_path, candidate_path, heatmap_path in scene_paths: + reference_image = read_png(reference_path) + candidate_image = read_png(candidate_path) stats = compare_rasters(reference_image, candidate_image) heatmap = build_heatmap(reference_image, candidate_image) - heatmap_path = os.path.join(candidate_directory, f"{scene.name}.diff.png") write_png(heatmap_path, heatmap) violation = threshold_violation( stats, arguments.max_differing_percent, arguments.max_mean_delta ) - print(format_diff_line(scene.name, stats, scene_column_width, violation)) - whole_frame_note = whole_frame_difference_note(scene.name, stats) + print(format_diff_line(name, stats, scene_column_width, violation)) + whole_frame_note = whole_frame_difference_note(name, stats) if whole_frame_note: print(f" {whole_frame_note}") if violation: - failing_scenes.append(scene.name) + failing_scenes.append(name) print() scene_count = len(reference.scenes) diff --git a/tools/report_paths.py b/tools/report_paths.py index a8b7bd29a0..aa69e22341 100644 --- a/tools/report_paths.py +++ b/tools/report_paths.py @@ -12,8 +12,12 @@ path has to exist: two report paths that don't exist yet still collide when they differ only in case on a volume that ignores case. Where the name rules cannot tell, `same_name_on_folding_volume` asks the volume itself with one scratch folder: a Linux mount that folds case (vfat, exFAT, CIFS) answers neither `normcase` nor `pathconf`. +`find_report_path_collision` indexes possible aliases for a batch of inputs and outputs, then uses the same +pairwise check for the candidates. Standard library only; no game data. """ +from collections import defaultdict +from itertools import chain import os import posixpath import sys @@ -67,12 +71,16 @@ def same_name_on_folding_volume(first, second): return _same_resolved_name(os.path.realpath(first), os.path.realpath(second)) +def _folded_basename(path): + return os.path.basename(path).casefold() + + def _same_resolved_name(first, second): """`same_name_on_folding_volume` for paths `os.path.realpath` has already resolved.""" + if _folded_basename(first) != _folded_basename(second): + return False first_dir, first_name = os.path.split(first) second_dir, second_name = os.path.split(second) - if first_name.casefold() != second_name.casefold(): - return False try: if not os.path.samefile(first_dir, second_dir): return False @@ -98,6 +106,43 @@ def same_report_path(first, second): return _same_resolved_name(first, second) +def _possible_alias_keys(path): + """Each way same_report_path can match must share at least one of these keys.""" + resolved = os.path.realpath(path) + yield "resolved", resolved + yield "normalized", _resolved_key(resolved) + yield "basename", _folded_basename(resolved) + try: + stat = os.stat(resolved) + except OSError: + return + # samefile compares these two stat fields. This also finds hard links with unrelated names. + yield "identity", stat.st_dev, stat.st_ino + + +def find_report_path_collision(input_paths, output_paths): + """Return (output, conflicting path, conflict is an input), or None for distinct destinations. + + Check outputs in order, comparing against inputs first and then earlier outputs. Index path data for this + call only. A shared key makes a pair a candidate, and same_report_path decides whether it really aliases. + """ + inputs = tuple(input_paths) + known_paths = [] + indices_by_key = defaultdict(list) + for index, path in enumerate(chain(inputs, output_paths)): + keys = tuple(_possible_alias_keys(path)) + if index >= len(inputs): + candidates = {i for key in keys for i in indices_by_key.get(key, ())} + for i in sorted(candidates): + other = known_paths[i] + if same_report_path(path, other): + return path, other, i < len(inputs) + known_paths.append(path) + for key in keys: + indices_by_key[key].append(index) + return None + + def _windows_directory_keeps_case(path): """Check the directory that will contain a component, or its nearest existing ancestor.""" while True: