Repository navigation
Harden the shortest-path graph: node accounting, node lookup, and border edges - #239
Merged
Gonzalo-Mier merged 8 commits intoAug 27, 2026
Conversation
Matrices were sized by edges_.size(), which counts only nodes with an outgoing edge, while they are indexed by the node id itself. numNodes() now counts every node, and matrixSize() sizes the matrices.
Graph2D looked the point up with unordered_map::at, so a caller had to guard every query with try/catch. Missing nodes now use the signals the graph already has for unreachable pairs: an empty path and INF. hasNode() tells the two cases apart.
A point produced by decomposition can land a fraction outside the border it belongs to, and touches()/within() then place it in no cell at all.
closestPointOnBorderTo searched every cell, so an end that belongs to no cell of the graph still got an edge, and the shortest path reached it by crossing whatever lay in between. The start/end point keeps its edge: it is allowed to sit outside the field.
The sum ran negative coordinates through an undefined double-to-size_t conversion, and points that compare equal landed in different buckets, so a node lookup could throw for a node the graph holds. Quantizing to the tolerance of operator== keeps equal points together.
Contributor
Author
|
@Gonzalo-Mier is there anything need to change here? |
Member
|
Hi @u33549, no need to change anything. Sorry for the delays. With these kind of PR I like to understand what is happening in the code, so I take longer to review them. Thank you for the PR, it seems great! |
Contributor
Author
|
Hi @Gonzalo-Mier, |
Member
|
I understand that and I thank your reminder. Please, be aware I value your work a lot. |
This was referenced Nov 21, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Motivation
Four independent defects in the shortest-path graph end the same way: a caller gets an
answer it cannot trust, and has no way to tell a real answer from a broken one.
Graphsizes its path matrices byedges_.size()but indexes them by the node id, so agraph whose ids are sparse — or that has a node reachable only by an incoming edge —
writes past the end of the matrix.
Graph2D::shortestPathon a graph built withaddDirectedEdgesegfaults in a plain release build.std::hash<Point>sums the coordinates, which is undefined for negative ones and putspoints that
operator==calls equal into different buckets. The graph then throwsstd::out_of_rangefor a node it actually holds.Graph2Dreports a missing node by throwing out ofunordered_map::at, so every queryhas to be wrapped in
try/catcheven though the graph already has a way to say "nopath": an empty vector, and
INF.createShortestGraphconnects every swath end to the nearest border point of any cellit was given. An end that belongs to none of them still gets an edge, and the shortest
path reaches it by cutting across whatever lies between.
The last one is the reason a caller cannot use the result: the bogus path has two or more
points, so it looks like success.
A comb field, driving from the top of one prong to the top of another, with the graph built
from one prong only. Blue is the field boundary, dark grey the drivable area, green the path
over the full field, red the path the single-prong graph returns.
The red path runs straight across two notches, outside the field, and it is shorter than
the green one — which is why the graph prefers it. Afterwards there is no red path: the
query returns empty and the caller can fall back. The green path is identical in both.
The same thing in isolation: two cells with a corridor along the bottom, and a gap that
cannot be driven.
1. Size the path matrices by node id (
139f888)numNodes()returnededges_.size(), the number of nodes with an outgoing edge, whileshortestPathsAndCosts,initializeMatrices,getPathsandallPathsBetweenused it asthe id space. Three lines are enough to corrupt the heap:
getNodes()is added — the same method thev3.0branch already has, collecting the keysand the targets — and
numNodes()is defined from it. Matrix sizing moves to a newmatrixSize(), the largest id plus one, sogetCosts()andgetPaths()keep being indexedby node id. (
v3.0solves this by remapping to dense indices, which also removes those twoaccessors; the v2 line still exposes them.)
2. Hash a Point from its coordinates (
e568abb)Two problems.
size_t(-1e10)is undefined — the current test suite already triggers it(
Graph2D_test.cpp:11uses{1, -1}); compile with-fsanitize=float-cast-overflowand itreports. And the resolution is finer than
operator=='s tolerance, so two points thatcompare equal land in different buckets, which is what makes
nodes_to_index_.at()throwfor a node the graph holds.
The coordinates are now quantized to that tolerance and hashed. Note this does not make
node identity exact:
operator==is tolerant and therefore not transitive, so no hash canbe fully consistent with it. If tolerant node identity is wanted, it needs a lookup that
knows about
d_tolrather than a hash.std::hash<Point>has exactly one user in the tree,Graph2D::nodes_to_index_.Measured on the decomposed field of
route_planner_base_test, before and after:nodes=74 edges=338 route_len=568.605551— unchanged.3. Report a missing node instead of throwing (
a848232)shortestPath,shortestPathCost,allPathsBetweenandremoveDirectedEdgelooked thepoint up with
at(). They now return an empty path,INF, an empty vector, and nothing.This is not a new convention:
reconstructPathalready returns{}when there is no path,shortestPathCostalready readsINFout of the matrix, and the index form ofremoveDirectedEdgeis already a no-op for an edge that is not there.hasNode()is addedso a caller that needs to tell "not a node" from "no path" still can.
4. A tolerance for
getCellWherePoint(b554a59)touches() || within()is exact, and a point that decomposition placed a fraction outsidethe border it belongs to lands in no cell at all. A
d_toloverload is added; the existingone is untouched.
5. Connect a swath end only to its own cell (
cc49ab3)An end outside every cell of the graph gets no edge, so it is not a node, so the query
returns empty rather than a path across the gap.
The route's start/end point deliberately keeps its unconditional edge: unlike a swath end,
it is allowed to sit outside the field, and connecting it to the nearest border is the
point of it.
Note this is only ever reached with an incomplete set of cells. On a full-field
genRouteevery swath end is inside the cells it was given, and the border point chosen is the same
one as before: for
pinside cellA, any segment frompto another cell's border mustcross
∂A, sodist(p, ∂A) <= dist(p, ∂B)always.One thing that is not this PR
Building with
-fsanitize=addressmakes every test that callsgenRoutesegfault insideor-tools'
RoutingModel::NextVar, reached fromcomputeBestRoute. It happens on anunpatched tree as well, a plain
Debugbuild without sanitizers is fine, and release isfine — so it looks like the prebuilt or-tools binary CMake downloads rather than anything in
Fields2Cover. Flagging it only because anyone reproducing this under ASan will run into it.