Exercise routing regressions through router entry points

Keep coverage for worker options, locked retries, and route costs independent of the benchmark command-line tools.
This commit is contained in:
Jan Petykiewicz 2026-12-02 20:33:09 -08:00
commit 5c4d32cc3e
3 changed files with 102 additions and 188 deletions

View file

@ -1,39 +1,27 @@
import sys
from dataclasses import asdict, replace
from json import loads
from dataclasses import replace
from functools import partial
import pytest
from shapely.geometry import box, shape
from shapely.geometry import box
from inire import (
Bend90Seed, CongestionOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions, RoutingOptions, RoutingProblem,
RoutingResult, RoutingRunResult, SBendSeed,
SearchOptions, StraightSeed, TopologyOptions, route,
SearchOptions, StraightSeed, TopologyOptions, _dispatch_route, _route, route,
)
from inire.router import _automatic, _compact
from inire.router._astar_types import AStarMetrics
from inire.router._automatic import _AutomaticRun
from inire.router._capacity import port_conflicts
from inire.router._routing_policy import _disconnected_nets
from inire.router._routing_policy import LockPlan, _disconnected_nets, _plan_locks, _residual_problem, _route_residual
from inire.router.cost import weighted_path_length
from inire.tests.routing_benchmark_case import BenchmarkCase
from inire.tests.routing_benchmarks import (
BENCHMARK_CASES,
CROSSING_BENCHMARK_CASES,
)
from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, profile_options
from inire.tests.routing_corpus import CASE_GROUPS, automatic_options, benchmark_weighted_length, native_verified_costs, profile_options
from inire.tests.routing_expanded_benchmarks import _on_grid
from scripts.benchmark_retry_order import _measure as _measure_retry
from scripts.compare_topological_routing import (
_direct_trials,
_measure as _measure_selected_mode,
_mode_options,
main as run_benchmarks,
)
def _measure(case, options, strategy):
return _measure_selected_mode(case, _mode_options(options, strategy), strategy)
@pytest.mark.routing_corpus
@ -125,129 +113,63 @@ def test_automatic_skips_identical_guide_retry_on_staggered_grid() -> None:
assert len(guided[0].valid_net_ids) < len(problem.nets)
def test_benchmark_profile_records_effective_options(tmp_path, monkeypatch) -> None:
def test_automatic_fallback_passes_fixture_geometry_to_worker() -> None:
(fixture,) = CASE_GROUPS["fallback-custom-physical"]
search = replace(fixture.options.search, bend_physical_length=25)
case = replace(fixture, options=replace(fixture.options, search=search))
monkeypatch.setitem(CASE_GROUPS, case.name, (case,))
defaults = RoutingOptions()
output = tmp_path / "benchmark.json"
monkeypatch.setattr(
sys, "argv",
["bench", "--profile", "public-defaults", "--case", case.name, "--refinement", "on", "--refinement-windows", "1", "--json", str(output)],
)
case = replace(fixture, options=replace(fixture.options, search=replace(fixture.options.search, bend_physical_length=25)))
options = profile_options(case, "public-defaults")
options = replace(options, refinement=replace(options.refinement, enabled=True, max_windows_per_net=1))
attempts = []
run_benchmarks()
run = _route(case.problem, options=options, run_router=partial(_dispatch_route, attempt_callback=attempts.append))
payload = loads(output.read_text())
[run] = payload["runs"]
assert payload["profile"] == "public-defaults"
assert run["requested_mode"] == "automatic"
options = run["options"]
geometry = case.options.search
assert options["search"]["bend_radii"] == list(geometry.bend_radii)
assert shape(options["search"]["bend_physical_geometry"]).equals(geometry.bend_physical_geometry)
assert options["search"]["bend_physical_length"] == geometry.bend_physical_length
[sample] = run["samples"]
assert payload["cost_metrics"] == {"valid_costs": "benchmark_weighted_length", "native_valid_costs": "native_objective"}
assert sample["native_valid_costs"].keys() == sample["valid_costs"].keys()
stage = sample["stages"][sample["selected_stage"]]
assert stage["planner"] == "lattice"
assert stage["mode"] == "off"
assert stage["operation"] == "search"
operations = {timing["operation"] for timing in sample["timings"]}
expected_refinement = replace(defaults.refinement, enabled=True, max_windows_per_net=1)
assert options["refinement"] == asdict(expected_refinement)
assert operations == {"search", "verify", "refine"}
assert options["search"]["node_limit"] == defaults.search.node_limit
assert options["objective"] == asdict(defaults.objective)
assert options["congestion"] == asdict(defaults.congestion)
assert options["topology"]["automatic_length_weights"] is None
[attempt] = sample["attempt_options"]
assert attempt == {**options, "topology": {**options["topology"], "mode": "off"}}
assert run.automatic is not None
stage = run.automatic.stages[run.automatic.selected_stage]
assert (stage.planner, stage.mode, stage.operation) == ("lattice", "off", "search")
assert {timing.operation for timing in run.automatic.timings} == {"search", "verify", "refine"}
[attempt] = attempts
assert attempt == replace(options, topology=replace(options.topology, mode="off"))
assert attempt.search.bend_physical_length == 25
assert attempt.search.bend_physical_geometry == fixture.options.search.bend_physical_geometry
def test_retry_experiment_records_worker_expansions() -> None:
(case,) = CASE_GROUPS["retry-holdout-floor-pocket"]
sample = _measure_retry(case, "public-defaults", "lattice-500")
[attempt] = sample["retry_attempts"]
stage_work = sum(stage["nodes_expanded"] for stage in sample["stages"] if stage["policy"] == "early-bounded-lattice")
assert attempt["policy"] == "bounded-lattice"
assert 0 < attempt["nodes_expanded"] == stage_work <= sample["nodes_expanded"]
assert len(sample["verified"]) == case.routing_bound
def test_retry_experiment_preserves_public_input_handling() -> None:
port = Port(10, 5, 0)
problem = RoutingProblem(
bounds=(0, 0, 100, 40),
nets=(NetSpec("coincident", port, port), NetSpec("straight", Port(10, 15, 0), Port(90, 15, 0))),
)
case = BenchmarkCase("coincident-control", "Coincident ports beside a straight route", problem, RoutingOptions())
baseline = _measure_retry(case, "matched-budget", "baseline")
experiment = _measure_retry(case, "matched-budget", "probe-iterations-2")
assert baseline["verified"] == experiment["verified"] == ["straight"]
assert baseline["routing_bound"] == experiment["routing_bound"] == 1
assert baseline["nodes_expanded"] == experiment["nodes_expanded"] == 0
assert baseline["stages"] == experiment["stages"]
assert baseline["placements"] == experiment["placements"]
coincident, straight = problem.nets
moved = replace(straight, start=straight.start.translate(dy=5), target=straight.target.translate(dy=5))
moved_case = replace(case, problem=replace(problem, nets=(coincident, moved)))
shifted = _measure_retry(moved_case, "matched-budget", "baseline")
assert shifted["seeds"] == baseline["seeds"]
original_placement = baseline["placements"]["straight"]
moved_placement = shifted["placements"]["straight"]
assert moved_placement["effective_net"]["start"]["y"] == 20
assert moved_placement["physical_polygon_hashes"] != original_placement["physical_polygon_hashes"]
def test_direct_benchmarks_validate_inputs_before_locking_routes() -> None:
def test_automatic_handles_invalid_inputs_before_trying_direct_routes() -> None:
port = Port(10, 5, 0)
problem = RoutingProblem(
bounds=(0, 0, 100, 40),
nets=(NetSpec("coincident", port, port), NetSpec("straight", Port(10, 15, 0), Port(90, 15, 0))),
)
options = RoutingOptions(search=SearchOptions(node_limit=20))
case = BenchmarkCase("direct-inputs", "Coincident ports beside a straight route", problem, options)
bad_seed = replace(problem, initial_paths={"unknown": PathSeed((StraightSeed(20),))})
for strategy in ("direct-guide", "direct-probe-near-port", "bundle-first"):
with pytest.raises(ValueError, match="Initial path provided for unknown net: unknown"):
_measure(replace(case, problem=bad_seed), options, strategy)
route(bad_seed, options=options)
sample = _measure(case, options, strategy)
assert sample.net_outcomes == {"coincident": "unroutable", "straight": "completed"}
assert sample.stages[sample.selected_stage].direct_net_ids == ("straight",)
run = route(problem, options=options)
assert run.results_by_net["coincident"].outcome == "unroutable"
assert run.results_by_net["straight"].is_valid
assert run.automatic is not None
assert run.automatic.verified_net_ids == ("straight",)
def test_seed_order_locked_rejects_touching_routes_at_zero_clearance() -> None:
def test_locked_seed_retry_rejects_touching_routes_at_zero_clearance() -> None:
problem = RoutingProblem(
bounds=(0, 0, 100, 40),
nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)), NetSpec("b", Port(10, 12, 0), Port(90, 12, 0))),
clearance=0,
)
options = RoutingOptions(
search=SearchOptions(node_limit=60, bend_radii=(), sbend_radii=()),
search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()),
congestion=CongestionOptions(max_iterations=1),
topology=TopologyOptions(mode="seed"),
)
case = BenchmarkCase("touching-routes", "Two straight routes sharing an edge", problem, options)
first = route(problem, options=options)
assert first.results_by_net["a"].is_valid
assert not first.results_by_net["b"].is_valid
sample = _measure(case, options, "seed-order-locked")
first, retry = sample.stages
assert first.valid_net_ids == ("a",)
assert retry.incumbent_net_ids == first.valid_net_ids
assert retry.valid_net_ids == first.valid_net_ids
assert sample.valid_costs.keys() == {"a"}
assert [(attempt.topology.mode, attempt.search.node_limit, attempt.congestion.net_order) for attempt in sample.attempt_options] == [
("seed", 30, "user"), ("seed", 30, "longest"),
]
residual = _residual_problem(problem, LockPlan({"a": first.results_by_net["a"]}))
retry = route(residual, options=replace(options, congestion=replace(options.congestion, net_order="longest")))
assert retry.results_by_net.keys() == {"b"}
assert not retry.results_by_net["b"].is_valid
def test_benchmark_native_cost_uses_configured_proximity_range() -> None:
@ -256,15 +178,20 @@ def test_benchmark_native_cost_uses_configured_proximity_range() -> None:
nets=(NetSpec("a", Port(10, 10, 0), Port(90, 10, 0)),),
static_obstacles=(box(0, 28, 100, 30),),
)
options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()))
options = RoutingOptions(search=SearchOptions(node_limit=30, bend_radii=(), sbend_radii=()), topology=TopologyOptions(mode="off"))
case = BenchmarkCase("proximity-cost", "Straight route near one keepout", problem, options)
default = _measure(case, options, "off")
wider = _measure(case, replace(options, search=replace(options.search, proximity_range=40)), "off")
assert default.valid_costs == wider.valid_costs == {"a": 80.0}
assert default.native_valid_costs == {"a": 80.0}
assert wider.native_valid_costs["a"] > default.native_valid_costs["a"]
wider_options = replace(options, search=replace(options.search, proximity_range=40))
default = route(problem, options=options)
wider = route(problem, options=wider_options)
for run in (default, wider):
result = run.results_by_net["a"]
assert result.is_valid
assert benchmark_weighted_length(result) == 80.0
default_cost = native_verified_costs(case, options, default.results_by_net, ("a",))["a"]
wider_cost = native_verified_costs(case, wider_options, wider.results_by_net, ("a",))["a"]
assert default_cost == 80.0
assert wider_cost > default_cost
def test_benchmark_native_cost_scales_with_grid_for_straights_and_bends() -> None:
@ -273,6 +200,7 @@ def test_benchmark_native_cost_scales_with_grid_for_straights_and_bends() -> Non
search=SearchOptions(node_limit=0, bend_radii=(10,), sbend_radii=(10,)),
objective=ObjectiveWeights(danger_weight=0),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
seed = PathSeed((StraightSeed(20), Bend90Seed(10, "CCW"), SBendSeed(8, 10)))
case = BenchmarkCase("grid-cost", "Straight, quarter-turn, and S-bend", problem, options, reference_paths=(("a", seed),))
@ -280,8 +208,10 @@ def test_benchmark_native_cost_scales_with_grid_for_straights_and_bends() -> Non
for nm in (1000, 500, 250, 100, 10):
scaled = _on_grid(case, nm)
replay = replace(scaled, problem=replace(scaled.problem, initial_paths=dict(scaled.reference_paths)))
sample = _measure(replay, replay.options, "off")
normalized.append(sample.native_valid_costs["a"] * nm / 1000)
run = route(replay.problem, options=replay.options)
assert run.results_by_net["a"].is_valid
cost = native_verified_costs(replay, replay.options, run.results_by_net, ("a",))["a"]
normalized.append(cost * nm / 1000)
assert normalized == pytest.approx([normalized[0]] * len(normalized))
@ -304,12 +234,12 @@ def test_budgeted_retry_shares_the_cap_when_both_lock_orders_leave_connected_spa
case = next(case for case in BENCHMARK_CASES if case.name == "blocking-turn-room")
options = replace(case.options, search=replace(case.options.search, node_limit=101))
result = _measure(case, options, "direct-lookahead-retry")
trials = _AutomaticRun(case.problem, options, None)._direct(options, "direct-lookahead-retry")
assert [stage.node_limit for stage in result.stages] == [50, 51]
assert [stage.direct_net_ids for stage in result.stages] == [("horizontal",), ("vertical",)]
assert all(not stage.skipped_net_ids for stage in result.stages)
assert result.nodes_expanded == sum(stage.nodes_expanded for stage in result.stages)
assert [trial.stage.node_limit for trial in trials] == [50, 51]
assert [trial.stage.direct_net_ids for trial in trials] == [("horizontal",), ("vertical",)]
assert all(not trial.stage.skipped_net_ids for trial in trials)
assert all(trial.stage.nodes_expanded == trial.run.metrics.nodes_expanded for trial in trials)
def test_automatic_recovers_a_complex_board_after_rejecting_a_hint() -> None:
@ -350,53 +280,34 @@ def test_point_terminal_replay_preserves_the_selected_port_headings() -> None:
assert all(result.is_valid and result.locked_geometry == paths[net_id].locked_geometry for net_id, result in replay.results_by_net.items())
def test_bundle_first_reports_effective_settings_and_capacity_fallback(tmp_path, monkeypatch) -> None:
original = next(case for case in BENCHMARK_CASES if case.name == "terminal-bench-point-terminals")
output = tmp_path / "benchmark.json"
monkeypatch.setattr(sys, "argv", [
"bench", "--case", original.name, "--policy", "bundle-first", "--iterations", "4", "--refinement", "on", "--json", str(output),
])
run_benchmarks()
@pytest.mark.parametrize(
("clearance", "rejection"), [(7, "insufficient track capacity"), (15, "The short route must leave through the first gap")],
)
def test_automatic_can_continue_after_bundle_rejection(clearance, rejection) -> None:
(case,) = CASE_GROUPS["complex-routing-example-1-point-terminals"]
problem = replace(case.problem, clearance=clearance)
options = replace(case.options, search=replace(case.options.search, node_limit=20))
bundle = replace(options, topology=replace(options.topology, mode="bundle"))
with pytest.raises(ValueError, match=rejection):
route(problem, options=bundle)
[record] = loads(output.read_text())["runs"]
[success] = record["samples"]
[bundle] = success["attempt_options"]
assert record["requested_mode"] is None
assert record["options"]["congestion"]["max_iterations"] == 4
assert record["options"]["refinement"]["enabled"]
assert bundle["topology"]["mode"] == "bundle"
assert bundle["congestion"]["max_iterations"] == 1
assert not bundle["refinement"]["enabled"]
assert len(success["valid_costs"]) == len(original.problem.nets)
options = replace(original.options, search=replace(original.options.search, node_limit=20))
for clearance, rejection in ((7, "insufficient track capacity"), (15, "The short route must leave through the first gap")):
case = replace(original, problem=replace(original.problem, clearance=clearance))
if clearance == 15:
assert case.fixed_headings_problem() == case.problem
fallback = _measure(case, options, "direct-probe-near-port")
sample = _measure(case, options, "bundle-first")
assert sample.bundle_rejection is not None
assert rejection in sample.bundle_rejection
assert sample.bundle_duration_s is not None
assert sample.stages == fallback.stages
assert sample.net_outcomes == fallback.net_outcomes
assert sample.net_outcomes.keys() == {net.net_id for net in case.problem.nets}
assert sample.valid_costs == fallback.valid_costs
assert sample.attempt_options[0].topology.mode == "bundle"
assert sample.attempt_options[1:] == fallback.attempt_options
automatic = replace(options, topology=replace(options.topology, mode="automatic"))
run = route(problem, options=automatic)
assert run.automatic is not None
assert run.results_by_net.keys() == {net.net_id for net in problem.nets}
assert run.automatic.selected_planner != "bundle"
def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() -> None:
case = next(case for case in BENCHMARK_CASES if case.name == "blocking-straight")
board = box(*case.problem.bounds)
options = replace(case.options, search=replace(case.options.search, node_limit=100), topology=TopologyOptions(mode="seed"))
first = _direct_trials(case.problem, board, options, "direct-guide")[0]
planner = _AutomaticRun(case.problem, options, None)
locks = _plan_locks(case.problem, board, options, check_connectivity=False)
first = planner._trial(*_route_residual(case.problem, options, locks, residual_mode="guide"))
assert tuple(first.valid_costs) == ("horizontal",)
[retry] = _AutomaticRun(case.problem, options, None)._incumbent_trials(options, first, len(case.problem.nets))
[retry] = planner._incumbent_trials(options, first, len(case.problem.nets))
assert retry.stage.kind == "incumbent-retry"
assert retry.stage.incumbent_net_ids == ("horizontal",)
@ -405,15 +316,19 @@ def test_automatic_retry_releases_a_lock_that_disconnects_the_remaining_net() ->
def test_automatic_weighted_scoring_preserves_coverage_and_reduces_cost() -> None:
case = next(case for case in BENCHMARK_CASES if case.name == "bypass-interleaved-directions")
baseline = _measure(case, case.options, "automatic-span")
weighted = _measure(case, case.options, "automatic")
baseline = route(case.problem, options=automatic_options(case.options, "matched-budget", "automatic-span"))
weighted = route(case.problem, options=automatic_options(case.options, "matched-budget"))
assert len(weighted.valid_costs) == len(case.problem.nets)
assert weighted.valid_costs.keys() == baseline.valid_costs.keys()
assert sum(weighted.valid_costs.values()) < sum(baseline.valid_costs.values())
assert weighted.nodes_expanded == baseline.nodes_expanded == 0
assert weighted.cost_pass_performed
assert not baseline.cost_pass_performed
assert baseline.automatic is not None
assert weighted.automatic is not None
assert len(weighted.automatic.verified_net_ids) == len(case.problem.nets)
assert set(weighted.automatic.verified_net_ids) == set(baseline.automatic.verified_net_ids)
assert sum(map(benchmark_weighted_length, weighted.results_by_net.values())) < sum(
map(benchmark_weighted_length, baseline.results_by_net.values()),
)
assert weighted.metrics.nodes_expanded == baseline.metrics.nodes_expanded == 0
assert weighted.automatic.cost_pass_performed
assert not baseline.automatic.cost_pass_performed
def test_automatic_can_force_weighted_scoring_when_the_selective_pass_is_skipped() -> None:

View file

@ -185,6 +185,7 @@ def test_complex_benchmarks_are_distinct_unseeded_nine_net_problems() -> None:
def _check_external_fixture(case) -> None:
assert case.grid_nm == 100
problem = case.problem
assert not problem.initial_paths
assert not case.reference_paths

View file

@ -1,4 +1,5 @@
from dataclasses import replace
from functools import partial
import pytest
import shapely
@ -6,15 +7,13 @@ from shapely.geometry import LineString, Polygon, box
from inire import (
CongestionOptions, DiagnosticsOptions, NetSpec, ObjectiveWeights, PathSeed, Port, RefinementOptions,
RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, route,
RoutingOptions, RoutingProblem, SBendSeed, SearchOptions, StraightSeed, TopologyOptions, _dispatch_route, _route, route,
)
from inire.geometry.collision import RoutingWorld
from inire.router import _router, _stack
from inire.router._stack import build_routing_stack
from inire.router._topology import _Assignment, _endpoint_access, _Mesh, _plan_lane_assignments, plan_corridors
from inire.tests.routing_benchmark_case import BenchmarkCase
from inire.tests.routing_benchmarks import DETOUR
from scripts.compare_topological_routing import _measure
def test_seed_mode_recovers_a_corridor_after_an_invalid_hint() -> None:
@ -144,9 +143,12 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(monkeypatch: p
monkeypatch.setattr(_stack, "route_once", limit_guided_attempt)
snapshots = []
run = route(
attempts = []
selected_attempts = []
run = _route(
problem, options=options,
iteration_callback=lambda index, results: snapshots.append((index, sum(result.is_valid for result in results.values()))),
run_router=partial(_dispatch_route, attempt_callback=attempts.append, selected_attempt_callback=selected_attempts.append),
)
assert all(result.is_valid for result in run.results_by_net.values())
@ -155,12 +157,8 @@ def test_guidance_retry_can_change_an_incumbent_in_an_offset_gate(monkeypatch: p
assert [entry.iteration for entry in run.conflict_trace if entry.stage == "iteration"] == [2]
assert run.conflict_trace[-1].iteration is None
case = BenchmarkCase("guidance-retry", "Two offset gates", problem, options)
sample = _measure(case, options, mode)
assert sample.valid_costs.keys() == {"a", "b"}
assert [attempt.topology.guide_strength for attempt in sample.attempt_options] == [0.75, 0.0]
assert sample.selected_attempt == 1
assert [attempt.topology.guide_strength for attempt in attempts] == [0.75, 0.0]
assert selected_attempts == [1]
clock = [0.0]
capture = _router.PathFinder._capture_frontier_trace