Reserve search budget for deferred turns

This commit is contained in:
Jan Petykiewicz 2026-11-29 00:24:00 -08:00
commit 9ba1dc048a
9 changed files with 50 additions and 19 deletions

View file

@ -14,9 +14,9 @@ Follow the left column down while the number of verified nets is below the targe
2. **Try constructive planners.** Bundles assign ordered tracks through barriers. Column schedules place turns between openings. Compact planners fit short connections between constrained ports. Each produces seeds whose physical geometry the worker checks.
3. **Start with a small search budget.** Lock verified straight links and search for the remaining nets. A different lock order or a small unlocked probe can free room for a turn. Promising guide and column attempts can run first.
4. **Decide what to keep fixed.** If the remaining ports are connected, route around the locked geometry. If the locks disconnect them, pass the previously verified paths as seeds that can move. A joint retry can assign different lanes through a shared opening. If recovery stalls, seed and lattice attempts can search the whole layout. The final lattice retry can use the caller's full node limit.
5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L609).
5. **Select a verified layout.** Prefer more verified nets and compare cost when the verified net IDs match. A completed `incumbent-residual` trial or an improving `joint-portal-lanes` trial must pass another check with the original keepouts before it can win. Refinement can replace the selected layout only if it preserves the verified net IDs. See [the refinement handoff](../inire/router/_automatic.py#L610).
The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L508).
The near-port attempt uses up to 100 nodes per search and two congestion iterations with the arc proxy. Alternate proxies use the configured iteration limit because a later shallow iteration can find a cheaper path. Wider lookahead uses up to 500 nodes per search and the configured iteration limit. Follow the caps and early exits in [the initial search trials](../inire/router/_automatic.py#L509).
### Example of a poor lock
@ -26,7 +26,7 @@ The near-port attempt uses up to 100 nodes per search and two congestion iterati
## Detailed search and congestion
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. A long lead can use consecutive straights when a single forward scan cannot cover it. Search can try turns away from a distant target if it exhausts its preferred moves. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py)
- **Build and admit moves.** Weighted A* searches snapped positions and headings. Rays, visible corners, and corridor waypoints propose straight endpoints. If a ray blocks a launch, a flat-ended trace scan checks for room to move. An aligned target goes directly to admission, which checks the straight's rectangular footprint for clearance. A long lead can use consecutive straights when a single forward scan cannot cover it. Search releases turns away from a distant target when preferred moves run out or the reserved share of the expansion budget begins. Searches with up to 16 expansions consider these turns immediately. Larger searches release them with at least one tenth of the budget left, rounded down with a minimum of one expansion. S-bends can follow each other when the configured moves permit it. Admission also checks cost and state dominance. [Move generation](../inire/router/_astar_moves.py)
- **Recheck the installed set.** Paths that reach their targets and pass geometry checks against themselves, the board, and keepouts participate in congestion. Partial and geometrically invalid paths remain available for diagnosis. After an iteration the driver verifies the installed paths, since a later route can collide with one completed earlier. It ranks snapshots by completed nets, then by conflicts and dynamic collisions. A narrowed retry includes every net that still fails verification. [`next_reroute_net_ids()`](../inire/router/_congestion_policy.py#L99)

View file

@ -14,7 +14,7 @@ Origin. The problem uses board 1 from Terminal-Bench pull request 345. [Pinned l
`build_problem()` reads the example entry into a `RoutingProblem` and `RoutingOptions`. The board is 2,500 by 1,000 units with seven rectangular keepouts and nine nets. The guides are 2 units wide, the clearance is 6, and both kinds of bends use radius 50. The fixed-heading case starts with no seeds and requires each net to launch and arrive heading east. [Example inputs](../examples/advanced-layouts.json) · [Problem builder](../examples/advanced_layouts.py#L34)
`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L648) · [Capacity checks](../inire/router/_capacity.py#L28)
`route()` dispatches to automatic routing. The router checks whether any aligned terminal pairs are too close and whether a vertical cut has fewer tracks than nets that need to cross it. The board passes both checks, so automatic asks the constructive planners to verify all nine nets. [Automatic entry point](../inire/router/_automatic.py#L641) · [Capacity checks](../inire/router/_capacity.py#L28)
![The nine input nets surround seven rectangular keepouts. A cut at x = 500 has openings at the bottom, center, and top of the board.](figures/complex-routing-example-1-input.png)
@ -32,7 +32,7 @@ The dots mark waypoints in the proposed seeds. The lower inset shows the two con
## 3. Fit the required eastbound arrival
Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L238) · [Turnaround candidates](../inire/router/_perimeter.py#L103)
Automatic routing compares the bundle's inferred headings with the input. Only `net_08` differs. Its initial bundle arrives from the east heading west. The turnaround planner adjusts the upper shelf route `net_07` and brings `net_08` back below it. Near the target, `net_08` rises west of `x = 1112` and takes a final right turn to arrive heading east. The planner recompiles the two changed seeds and submits the full set for verification. [Constructive planner dispatch](../inire/router/_automatic.py#L228) · [Turnaround candidates](../inire/router/_perimeter.py#L103)
![Two views show the materialized shelf and return paths. In the initial plan net_08 arrives westbound. In the turnaround candidate it passes below the shelf, rises left of the target, and arrives eastbound.](figures/complex-routing-example-1-turnaround.png)
@ -40,13 +40,13 @@ The arrow above each red target square shows the arrival heading.
## 4. Verify the seeds and refine the layout
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one verification pass with a zero-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L183) · [Seed installation](../inire/router/_router.py#L870) · [Physical verification](../inire/geometry/collision.py#L707)
The first `bundle-turnaround` candidate verifies all nine nets. Automatic routing runs a worker in mode `off` for one verification pass with a zero-node search limit and refinement disabled. The worker materializes each seed into physical polygons, installs the paths, and rechecks the installed layout for port joins, board containment, and collisions. The full coverage lets automatic routing skip its search trials. [Seeded worker setup](../inire/router/_automatic.py#L173) · [Seed installation](../inire/router/_router.py#L877) · [Physical verification](../inire/geometry/collision.py#L708)
![The upper panel shows the physical paths of the first four nets in installation order. The lower panel shows all nine paths after verification.](figures/complex-routing-example-1-verification.png)
The upper panel reconstructs the first four installed paths from the worker's verified seeds. The lower panel shows the full set checked together.
Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L617) · [Trial comparison](../inire/router/_routing_policy.py#L45)
Automatic then replays the verified seeds in a worker with refinement enabled. The refiner tries replacing sections with at least four 90-degree bends and verifies the resulting layout. In this run, refinement changes `net_05` and `net_07` and keeps all nine nets verified. The refined layout wins on the configured objective, which includes component penalties as well as length. [Refinement handoff](../inire/router/_automatic.py#L610) · [Trial comparison](../inire/router/_routing_policy.py#L45)
![The refined net_07 stays near the top edge longer and descends close to its target. Its earlier approach is dashed, and the outer return remains visible below it.](figures/complex-routing-example-1-refinement.png)

View file

@ -32,7 +32,7 @@ An authored 286.770 µm path in the Raymond MZI array can be replaced geometrica
## Check the export grid
Use the layout writer's rounding grid in routing units. `verify_export_grid` rounds route vertices while holding the supplied keepouts fixed. Supply the keepout geometry as it will appear in the file and pass all intended routes on the layer in one call so they are checked against each other. The function requires each supplied result to have passed routing verification. Recheck the assembled cell after writing when the writer performs further operations such as path merging or coordinate transforms.
Use the layout writer's rounding grid in routing units. `verify_export_grid` rounds route vertices while holding the supplied keepouts fixed. Supply the keepout geometry as it will appear in the file and pass all intended routes on the layer in one call so they are checked against each other. The function requires each result to match the net’s width and terminal contract and to have passed routing verification. For fixed routes, supply their final layout polygons as described in the [route reuse workflow](route-a-layout.md#reuse-an-existing-route). Recheck the assembled cell after writing when the writer performs further operations such as path merging or coordinate transforms.
```python
from inire.layout import verify_export_grid

View file

@ -14,7 +14,7 @@ from shapely.geometry import box
from inire.constants import TOLERANCE_LINEAR
from inire.geometry.collision import RoutingWorld
from inire.model import resolve_bend_geometry
from inire.model import FixedRoute, resolve_bend_geometry
from inire.results import AutomaticRoutingReport, RoutingStage, RoutingTiming, _planner_for_mode
from inire.router._bundle import ordered_bundle_terminal_headings, plan_ordered_bundle
from inire.router._capacity import cut_capacity, port_conflicts
@ -327,8 +327,9 @@ class _AutomaticRun:
if net.net_id in problem.initial_paths or not links[1 - index]:
continue
peer_link = links[1 - index][0]
obstacles = problem.static_obstacles + tuple(shapely.get_parts(peer_link[1]))
reserved = replace(problem, nets=(net,), initial_paths={}, static_obstacles=obstacles)
peer = problem.nets[1 - index]
fixed = FixedRoute(peer.net_id, tuple(shapely.get_parts(peer_link[1])))
reserved = replace(problem, nets=(net,), initial_paths={}, fixed_routes=(*problem.fixed_routes, fixed))
detours = footprints(net, (seed for _, seed in islice(perimeter_detour_candidates(reserved, options.search), 16)))
reserved_pairs = product(detours, (peer_link,)) if index == 0 else product((peer_link,), detours)
pairs = chain(pairs, reserved_pairs)

View file

@ -26,12 +26,12 @@ def _build_pair_local_context(
) -> AStarContext:
problem = context.problem
live_world = context.cost_evaluator.collision_engine
static_obstacles = tuple(live_world.iter_static_geometries())
static_entries = tuple(live_world.iter_static_entries())
world = RoutingWorld(
clearance=live_world.clearance, safety_zone_radius=live_world.safety_zone_radius, board=live_world.board,
self_clearance=live_world.self_clearance,
)
for obstacle, owner in live_world.iter_static_entries():
for obstacle, owner in static_entries:
world.add_static_obstacle(obstacle, owner=owner)
for net in ordered_nets:
if net.net_id in pair_order:
@ -45,7 +45,7 @@ def _build_pair_local_context(
danger_map = proximity_map(problem, context.options.search.proximity_range)
if context.options.objective.danger_weight:
danger_map.precompute(list(static_obstacles))
danger_map.precompute([obstacle for obstacle, _ in static_entries])
evaluator = CostEvaluator.from_objective(
world,
danger_map,
@ -55,7 +55,10 @@ def _build_pair_local_context(
)
return AStarContext(
evaluator,
replace(problem, nets=ordered_nets, initial_paths={}),
replace(
problem, nets=ordered_nets, initial_paths={},
static_obstacles=tuple(obstacle for obstacle, owner in static_entries if owner is None),
),
context.options,
metrics=AStarMetrics(),
)

View file

@ -67,14 +67,17 @@ def conflict_trace_entry(
def complete_final_conflict_trace(run: RoutingRunResult) -> RoutingRunResult:
"""Include routes supplied by other workers in the selected final trace."""
"""Sync the selected final trace with the assembled results."""
if not run.conflict_trace or run.conflict_trace[-1].stage != "final":
return run
final = run.conflict_trace[-1]
traced = {trace.net_id: trace for trace in final.nets}
for net_id, result in run.results_by_net.items():
if net_id not in traced:
entry = traced.get(net_id)
if entry is None:
traced[net_id] = NetConflictTrace(net_id, result.outcome, result.reached_target, result.report)
elif entry.report != result.report:
traced[net_id] = replace(entry, outcome=result.outcome, reached_target=result.reached_target, report=result.report)
completed = tuple(sorted(net_id for net_id, result in run.results_by_net.items() if result.is_valid))
final = replace(final, completed_net_ids=completed, nets=tuple(traced.values()))
return replace(run, conflict_trace=(*run.conflict_trace[:-1], final))

View file

@ -81,7 +81,11 @@ def route_astar(
# time. Give the preferred frontier more room when long straights are available.
scan_spans = context.options.search.max_straight_length / max(1.0, context.min_bend_radius)
preferred = 2 * min(scan_spans, config.node_limit) ** 2
release_turns_at = min(config.node_limit, max(config.node_limit // 20, preferred))
if config.node_limit <= 16:
release_turns_at = 0
else:
reserved = max(1, config.node_limit // 10)
release_turns_at = min(config.node_limit - reserved, max(config.node_limit // 20, preferred))
while open_set or deferred_turns:
if nodes_expanded >= config.node_limit or (config.expired is not None and nodes_expanded % 32 == 0 and config.expired()):

View file

@ -777,14 +777,17 @@ def test_unsafe_seed_reports_segment_without_allocating_geometry(monkeypatch, mo
search=SearchOptions(node_limit=node_limit, bend_radii=(1e11,), sbend_radii=(1e11,), sbend_offsets=(1e11,)),
topology=TopologyOptions(mode=mode),
refinement=RefinementOptions(enabled=False),
diagnostics=DiagnosticsOptions(capture_conflict_trace=True),
)
result = route(problem, options=options).results_by_net[net.net_id]
run = route(problem, options=options)
result = run.results_by_net[net.net_id]
assert result.is_valid is bool(node_limit)
assert result.report.seed_error == (
f"Initial path for 'track' segment 1 ({type(move).__name__}) exceeds 250,000 subdivisions for one circular arc"
)
assert run.conflict_trace[-1].nets[0].report.seed_error == result.report.seed_error
def test_search_rejects_out_of_board_bends_before_tessellation(monkeypatch) -> None:

View file

@ -86,6 +86,23 @@ def test_bounded_search_revisits_turns_away_from_the_target(reflection) -> None:
assert run.metrics.nodes_expanded <= 500
def test_small_budget_admits_a_turn_away_from_the_target() -> None:
net = NetSpec("detour", Port(503, -65, 270), Port(20, -12, 180))
problem = RoutingProblem((0, -185, 555, 0), (net,), (box(50, -185, 500, -38),), clearance=1)
options = RoutingOptions(
search=SearchOptions(node_limit=10, min_straight_length=2, bend_radii=(10,), sbend_radii=()),
objective=ObjectiveWeights(bend_penalty=10, danger_weight=0),
congestion=CongestionOptions(max_iterations=1, warm_start_enabled=False, use_tiered_strategy=False),
refinement=RefinementOptions(enabled=False),
topology=TopologyOptions(mode="off"),
)
run = route(problem, options=options)
assert run.results_by_net["detour"].is_valid
assert run.metrics.nodes_expanded <= 10
@pytest.mark.parametrize("with_peer", [False, True])
def test_narrow_alternative_remains_available_with_a_shared_guide(with_peer) -> None:
narrow = NetSpec("narrow", Port(60, 110, 0), Port(740, 110, 0))