inire/plans/routing-simplification.md

96 lines
16 KiB
Markdown
Raw Normal View History

# Routing simplification plan
Reduce the amount of routing state we rebuild and the number of places that define the same policy. Start with three changes that have a small implementation scope and clear parity checks. Prototype the changes that can affect geometry ordering, cost comparisons, or search work. Keep the public routing modes, defaults, and result fields stable through these batches.
The baseline is `6608e18`. Its two regression profiles verified 433 of 437 nets across 67 boards, reached every board's routing bound, and completed Terminal-Bench at 9/9. The earlier refactor covers the existing boundaries for the search, diagnostics, and planners. Use the [historical routing refactor plan](../archive/routing/routing-refactor-plan.md) for the rationale behind those boundaries.
The implementation, parity checks, and decisions on each prototype are recorded in the [simplification results](../archive/routing/simplification-results.md).
## First implementation batch
1. **Reuse the installed paths when the last iteration is already the best.** Skip reinstalling geometry when the live index is known to represent the saved result set. Preserve full restoration after a timeout, when an earlier iteration won, and when an iteration callback is present. Exercise all three cases, including a callback that modifies the result mapping. Start with [best-iteration restoration](../inire/router/_router.py#L403).
An in-memory prototype passed all 134 corpus and 20 diagnostic comparisons after allowing changes in the two path-object counters. It avoided 9,201 removals and 9,201 insertions across the 67 public-default boards.
2. **Use one layout ranking key.** Iteration selection and pair-local repair both prefer more completed nets, then fewer conflict edges, then fewer dynamic collisions. Put those criteria in one comparison key. Preserve the path-length tie-break and its tolerance in pair-local repair. Check all three tie-breaks and the first recorded iteration before comparing the corpus. Start with [iteration selection](../inire/router/_router.py#L395).
3. **Use one stable net ordering helper.** Lattice routing, direct locking, and joint-lane recovery each implement Manhattan-distance ordering for `shortest` and `longest`. Share the sort while preserving input order for equal distances and the subsequent priority pass for direct locks. Focus the initial check on mixed headings, equal-distance nets, and alternate lock order. Compare planner stages as well as paths. Start with the [direct lock planner](../inire/router/_routing_policy.py#L77).
## Small routing and diagnostic cleanups
4. **Represent a pair of conflicting nets as two IDs.** Replace the single-field pair target class and its order helper with the existing pair of IDs. Keep the order in which targets are visited and the forward and reverse attempts. Verify the two-pair limit and disjoint-edge rule in [pair target selection](../inire/router/_router.py#L666).
5. **Restore the incumbent once after a rejected pair replacement.** An unsuccessful pair search runs in a local world. The live-world candidate check already restores the incumbent on rejection. Exercise both failure paths before removing the unconditional final reinstall. Check the live index, reports, and path-object counters after a rejection followed by a second attempt. Start with [pair replacement and rollback](../inire/router/_router.py#L761).
6. **Collect component overlaps when a report consumes them.** Pair-local candidate selection reads net-level conflicts and validity. Check whether its live-world verification can omit component details while leaving the restored and final trace captures intact. Compare exact conflict payloads with each capture flag enabled on its own. Start with [pair candidate verification](../inire/router/_router.py#L761).
7. **Share incumbent guidance in frontier replay.** Frontier replay selects reached paths and computes the same seed and bonus used for reroute guidance. Use the shared helper at that call site once the replay preconditions are confirmed. Compare sampled prune reasons and verify that the diagnostic run still leaves the selected route and production counters intact. Start with [incumbent guidance](../inire/router/_search.py#L18).
8. **Remove the unused visibility wrapper.** Delete `_ensure_current` after checking the named corner-index and corner-graph entry points. Run the visibility tests for exact and tangent modes and preserve the distinction between index-only preparation and graph construction. See the [visibility manager](../inire/router/visibility.py#L49).
## Prototypes for installed geometry and verification
9. **Keep a capped incumbent installed when the next attempt will carry it forward.** The late capped branch removes the old geometry before immediately installing the incumbent again. Prototype moving that decision ahead of index mutation when the installed path is known. Exercise late caps, partial results, caller seeds, and mutable callback results. The fallback counters and per-net trace should still describe the same attempt. Start with [routing one net](../inire/router/_router.py#L831).
10. **Keep unchanged nets in the index during pair repair.** A replacement for two nets currently rebuilds the installed set. Prototype a narrower replace and rollback for the two changed nets. Compare component indices and candidate order in conflict reports, especially with several components per net. Check rejected repairs and a successful repair followed by another pair. Accept the change if the local update stays simpler than managing the full rebuild and measurably reduces work. See [installed-path replacement](../inire/router/_router.py#L359).
11. **Reuse verified reports when the geometry and net set match.** Compare the iteration review, restored review, and final verifier. Identify where the same paths and obstacle state are checked again without an intervening repair or refinement. Preserve the final reports for partial paths and the extra details needed for frontier replay. Measure verification calls and exact checks on a clean worker run and a worker that restores an earlier iteration. Start with the [final verification path](../inire/router/_router.py#L1087).
12. **Skip refinement setup for paths that cannot supply a window.** The driver removes a path before the refiner checks whether it has enough bends. Check eligibility before removing geometry, using the same rule in direct refiner calls. Compare index updates and `refine_path_calls` on straight, S-bend, and bend-heavy fixtures. Preserve the geometry seen by a real refinement attempt. See [refinement eligibility](../inire/router/refiner.py#L317).
## Prototypes for scoring and collision work
13. **Score the changed portion of a refinement window.** Candidate scoring currently walks the prefix, replacement, and suffix for each proposal. Test whether the unchanged portions can be reused for the first cost comparison. Preserve the definitive score after materializing geometry and check floating-point ties near the improvement threshold. Compare candidates built and accepted, path cost, and score calls on long foldbacks and alternating doglegs. Start with [refinement window scoring](../inire/router/refiner.py#L267).
14. **Build the proximity tree only when a worker can use it.** Keep the board bounds check available. Skip boundary sampling when the search objective and any enabled refinement objective both have zero danger weight. For pair-local search, check the objective it actually uses. Exercise a run with zero search danger weight and nonzero refinement danger weight, and verify that custom bends and bounds behave as before. Start with [worker initialization](../inire/router/_stack.py#L34).
15. **Measure reuse of static clearance buffers.** Repeated physical verification buffers component polygons against the same clearance. Profile the buffer calls on a dense static layout and compare a small reuse experiment with its retained memory. Account for clearance, the geometry used for verification, and the exact distance check at mitred corners. Keep boundary touching and custom physical bends in the comparison. See [static path verification](../inire/geometry/collision.py#L659).
16. **Measure overlap between the congestion prechecks.** Count how often grid presence and envelope checks reject a candidate before exact tests, and how much each cached query costs. Test removal or consolidation of one layer on sparse and congested layouts where that layer contributes little. Preserve frozen-net blocking and conflict counts. If pruning pays for the extra state, record the cases that depend on it. Start with [dynamic congestion queries](../inire/geometry/collision.py#L334).
## Worker and planner setup
17. **Prepare the joint-lane residual once.** Joint-lane recovery builds a residual board for corridor planning and reconstructs it for search. Pass the prepared nets and keepouts through both operations. Compare skipped IDs, lock order, topology reports, and stage labels on the joint-lane regression test. Use the same preparation for perimeter recovery only where its inputs and result merge match. Start with [joint-lane recovery](../inire/router/_automatic.py#L538).
18. **Share worker objective initialization where the inputs match.** The ordinary worker and pair-local worker each pass the same objective fields into the evaluator. A shared constructor can lift that mapping out of both paths. Keep each worker's obstacle set explicit, including the distinction between polygons used as locks and polygons used for proximity costs. Preserve the current greedy weight during pair repair. Compare the fan-out callbacks and pair-local traces. See the [pair-local context](../inire/router/_pair_local.py#L21).
19. **Share the physical containment predicate.** Automatic trial selection and explicit bundle routing both check whether the board covers the returned path polygons. Reuse that check while retaining each caller's error or report handling. Verify designs with flush ports, a shape extending beyond the board, and a custom physical bend. Start with [automatic trial validation](../inire/router/_routing_policy.py#L245).
20. **Assemble worker results in one place.** The stack and example trace fixture both read the pathfinder's metrics, traces, and results into `RoutingRunResult`. Reuse the production assembly path and check how topology data is populated. Keep fan-out's iteration callback on its existing worker. Compare example traces and explicit guide and seed results before removing the fixture formatter. Start with [worker result assembly](../inire/router/_stack.py#L94).
## Benchmark and example tooling
21. **Derive the example runs and snapshots from one registry.** Each ordinary scenario has a run wrapper that calls its snapshot and converts the result. Share the fixture names and order between the outcome tests and the snapshot command. Preserve the timing boundaries and check every existing scenario name. Keep the heavier and trace entries available through their current selectors. Start with the [example scenario registry](../inire/tests/example_scenarios.py#L440).
22. **Share snapshot selection between recording and comparison.** Both commands select the same registry, filter by scenario, and run the selected captures. Reuse that selection and execution logic with the existing snapshot objects. Let each command keep its output schema. Check repeated `--scenario`, the working `--include-performance-only` flag, and comparison against older baselines. Start with [performance baseline recording](../scripts/record_performance_baseline.py#L13).
23. **Use the public fixed-route workflow in the locked-path example.** The example script adds a static copy of the first route to a world that still has the path installed. Route the second net with a fresh problem whose keepouts include the first route's physical polygons, as the benchmark fixture now does. Compare exact paths and the rendered plot. Explain any scoring setting needed to reproduce the detour. See the [locked-path example](../examples/03_locked_paths.py).
## Larger changes with a specific trigger
24. **Consolidate residual routing around a new recovery case.** Item 17 addresses one repeated construction. A broader interface pays off when another planner needs shared logic for frozen paths, movable seeds, or joining an unresolved result. First inventory which stages require a complete layout check and how they report skipped and unresolved IDs. Design around a concrete duplicate operation and test it across the affected planners. Use the [residual routing policy](../inire/router/_routing_policy.py#L192) as the starting point.
25. **Split collision queries along a demonstrated boundary.** Use the candidate and exact-test profiles from items 15 and 16 to identify a useful separation between lookup, exact overlap, or ray casting. Keep the hot-path call count, physical clearance, proxy geometry, and cache invalidation visible. Exercise visibility modes, rotated ports, crossing approaches, and custom polygons. Begin with the [collision query code](../inire/geometry/collision.py).
26. **Revisit public option grouping when an API change is warranted.** Consider consolidating legacy bend geometry options and grouping planner-specific fields when a caller-facing change gives that work a purpose. Inventory existing constructors, custom polygon behavior, serialized benchmark options, and documentation. Plan migration before changing defaults or removing names. Start with the [public option definitions](../inire/model.py).
## Verification and sequencing
1. Capture the current corpus with `scripts.routing_benchmark_parity capture` before starting items 1 through 3. Use both `corpus-regression` and `public-defaults`. Add a focused capture with `--callbacks` and `--diagnostics` for Terminal-Bench, obstructed crossings, the mixed port bank, and a fixture with caller seeds. Include the two no-warm-start fan-out seeds for pair repair.
2. Land items 1 through 3 as independently reviewable changes. Then group items 4 through 8 by the behavior they exercise. Tooling items 20 through 23 can proceed on their own because they have focused scenario and script checks.
3. Run the related tests and exact parity for each routing change. Compare verified IDs, paths, native and benchmark costs, selected stage, stage order, bounds, callbacks, traces, and stable counters. List intentional counter differences by name in the comparison. Use `overloaded-gate` and `lidar-clements-8x8` to check that expected geometric bounds still explain incomplete coverage.
4. Prototype items 9 through 16 separately so any route or counter difference has one likely cause. Record the fixture, profile, counts, and result for each trial. For a speed claim, run repeated wall-time measurements with matching options and worker count, and examine both the median and individual slow boards.
5. Run the full test suite and the opt-in example performance tests before combining the routing changes. Refresh an archived example baseline when fixture semantics change. Keep exploratory measurements in scratch output until they support an implementation decision.
For item 1, take the first capture at the baseline revision and the second at the candidate revision.
```sh
python -m scripts.routing_benchmark_parity capture /tmp/inire-simplification-before.json --case corpus --jobs 4
python -m scripts.routing_benchmark_parity capture /tmp/inire-simplification-after.json --case corpus --jobs 4
python -m scripts.routing_benchmark_parity compare \
/tmp/inire-simplification-before.json /tmp/inire-simplification-after.json \
--allow-counter-change dynamic_path_objects_added \
--allow-counter-change dynamic_path_objects_removed
```
For the stable comparison fields and diagnostic capture options, use the [exact parity workflow](../docs/routing-diagnostics.md#reproduce-and-compare).