diff --git a/docs/routing-diagnostics.md b/docs/routing-diagnostics.md index c11f31a..db8ff2f 100644 --- a/docs/routing-diagnostics.md +++ b/docs/routing-diagnostics.md @@ -77,7 +77,7 @@ Use the returned result to count final successes. For live progress during routi ## Reproduce and compare -1. Start with a fixture that shows the symptom. Capture the same options at both revisions. For a behavior-preserving change, exact parity checks paths, scores, stage metadata, stable counters, and coverage. Add `--callbacks` and `--diagnostics` to both captures when changing callback or trace behavior. +1. Start with a fixture that shows the symptom. Capture the same options at both revisions. For a behavior-preserving change, exact parity checks move sequences, effective ports, physical polygon hashes, scores, stage metadata, stable counters, and coverage. Add `--callbacks` and `--diagnostics` to both captures when changing callback or trace behavior. 2. For a policy change, check verified IDs, paths, and per-net costs first. Advance to the full corpus and relevant holdouts once the focused case behaves as intended. Use interleaved repeats for timing and name the boards that get slower. Time inside failed retries can explain a tail regression that the median obscures. 3. If the run gets slower without more expansions, check the operation timings and use the counters above to pick a narrower trace or profile. @@ -89,6 +89,8 @@ python -m scripts.routing_benchmark_parity capture /tmp/routing-after.json --cas python -m scripts.routing_benchmark_parity compare /tmp/routing-before.json /tmp/routing-after.json ``` +Use capture scripts with the same snapshot schema on both revisions. Version 1 snapshots still compare with each other. Version 2 adds effective port and polygon data. + Select a built-in trace case by name with `--scenario`. Use `--output-dir` to write the capture in a scratch directory. ### Check timing and counters diff --git a/inire/tests/test_routing_benchmark_parity.py b/inire/tests/test_routing_benchmark_parity.py index 010cf7f..8ce1506 100644 --- a/inire/tests/test_routing_benchmark_parity.py +++ b/inire/tests/test_routing_benchmark_parity.py @@ -1,31 +1,54 @@ import json import sys +from dataclasses import replace +from inire import NetSpec, Port, RoutingOptions, RoutingProblem +from inire.tests.routing_benchmark_case import BenchmarkCase +from inire.tests.routing_corpus import CASE_GROUPS from scripts.routing_benchmark_parity import main def test_parity_command_reports_the_first_net_difference(tmp_path, monkeypatch, capsys) -> None: + net = NetSpec("lane", Port(10, 20, 0), Port(90, 20, 0)) + problem = RoutingProblem((0, 0, 100, 60), (net,)) + case = BenchmarkCase("placement-control", "Straight lane", problem, RoutingOptions()) + monkeypatch.setitem(CASE_GROUPS, case.name, (case,)) before = tmp_path / "before.json" after = tmp_path / "after.json" - monkeypatch.setattr(sys, "argv", [ - "parity", "capture", str(before), "--case", "reversed-heading", "--profile", "corpus-regression", "--callbacks", - ]) + capture_settings = ["--case", case.name, "--profile", "corpus-regression", "--callbacks"] + compare = ["parity", "compare", str(before), str(after)] + monkeypatch.setattr(sys, "argv", ["parity", "capture", str(before), *capture_settings]) assert main() == 0 payload = json.loads(before.read_text()) ordinary, with_callback = payload["runs"] assert ordinary["stable"]["callbacks"] == [] assert with_callback["stable"]["callbacks"] - assert "native" in ordinary["stable"]["costs"]["return"] + assert "native" in ordinary["stable"]["costs"][net.net_id] + original = ordinary["stable"]["nets"][net.net_id] + assert with_callback["stable"]["callbacks"][0]["nets"][net.net_id] == original ordinary["elapsed_s"] += 5 after.write_text(json.dumps(payload)) - monkeypatch.setattr(sys, "argv", ["parity", "compare", str(before), str(after)]) + monkeypatch.setattr(sys, "argv", compare) assert main() == 0 assert "2 runs match." in capsys.readouterr().out - ordinary["stable"]["nets"]["return"]["seed"][0]["kind"] = "DifferentMove" + original["seed"][0]["kind"] = "DifferentMove" after.write_text(json.dumps(payload)) assert main() == 1 message = capsys.readouterr().out - assert "reversed-heading / corpus-regression" in message - assert "nets.return.seed[0].kind" in message + assert "placement-control / corpus-regression" in message + assert "nets.lane.seed[0].kind" in message + + moved = replace(net, start=net.start.translate(dy=20), target=net.target.translate(dy=20)) + monkeypatch.setitem(CASE_GROUPS, case.name, (replace(case, problem=replace(problem, nets=(moved,))),)) + monkeypatch.setattr(sys, "argv", ["parity", "capture", str(after), *capture_settings]) + assert main() == 0 + original = json.loads(before.read_text())["runs"][0]["stable"]["nets"][net.net_id] + shifted = json.loads(after.read_text())["runs"][0]["stable"]["nets"][net.net_id] + assert original["seed"] == shifted["seed"] + assert original["report"] == shifted["report"] + assert original["physical_polygon_hashes"] != shifted["physical_polygon_hashes"] + monkeypatch.setattr(sys, "argv", compare) + assert main() == 1 + assert "nets.lane.effective_net.start.y" in capsys.readouterr().out diff --git a/scripts/routing_benchmark_parity.py b/scripts/routing_benchmark_parity.py index 2f2a8fc..8c152c0 100644 --- a/scripts/routing_benchmark_parity.py +++ b/scripts/routing_benchmark_parity.py @@ -5,11 +5,14 @@ from __future__ import annotations from argparse import ArgumentParser from concurrent.futures import ProcessPoolExecutor from dataclasses import asdict, replace +from hashlib import sha256 from json import dumps, loads from pathlib import Path from time import perf_counter from typing import TYPE_CHECKING +from shapely import to_wkb + from inire import DiagnosticsOptions, route from inire.results import RouteMetrics from inire.tests.routing_corpus import ( @@ -27,7 +30,7 @@ if TYPE_CHECKING: from inire import RoutingResult -SCHEMA_VERSION = 1 +SCHEMA_VERSION = 2 STABLE_COUNTERS = tuple(name for name in RouteMetrics.__dataclass_fields__ if not name.endswith("_ns")) @@ -39,6 +42,8 @@ def _paths(results: dict[str, RoutingResult]) -> dict: "outcome": result.outcome, "reached_target": result.reached_target, "seed": [{"kind": type(move).__name__, **asdict(move)} for move in result.as_seed().segments], + "effective_net": asdict(result.effective_net) if result.effective_net is not None else None, + "physical_polygon_hashes": [sha256(wkb).hexdigest() for wkb in to_wkb(result.locked_geometry, byte_order=1)], "report": asdict(result.report), } for net_id, result in results.items() @@ -119,19 +124,24 @@ def _first_difference(expected: object, actual: object, field: str = "") -> str return f"{field} is {expected!r} before and {actual!r} after" -def _read(path: Path) -> dict: +def _read(path: Path) -> tuple[int, dict]: payload = loads(path.read_text(encoding="utf-8")) - if payload["schema_version"] != SCHEMA_VERSION: + version = payload["schema_version"] + if version not in (1, SCHEMA_VERSION): raise ValueError(f"Unsupported parity schema in {path}") rows = payload["runs"] by_key = {(row["case"], row["profile"], row["with_callback"], row["with_diagnostics"]): row for row in rows} if len(by_key) != len(rows): raise ValueError(f"Duplicate parity run in {path}") - return by_key + return version, by_key def _compare(before: Path, after: Path, allowed_counters: list[str]) -> int: - baseline, current = _read(before), _read(after) + before_version, baseline = _read(before) + after_version, current = _read(after) + if before_version != after_version: + print(f"Parity schema mismatch ({before_version} and {after_version}). Capture both revisions with the same script version.") + return 1 for key in sorted(baseline.keys() | current.keys()): label = f"{key[0]} / {key[1]} (callback={key[2]}, diagnostics={key[3]})" if key not in baseline or key not in current: