Skip to content

Harden the shortest-path graph: node accounting, node lookup, and border edges - #239

Merged
Gonzalo-Mier merged 8 commits into
Fields2Cover:mainfrom
u33549:dev/umutc/v2.1.0-devel/border-graph
Aug 27, 2026
Merged

Gonzalo-Mier merged 8 commits into
Fields2Cover:mainfrom
u33549:dev/umutc/v2.1.0-devel/border-graph

Conversation

@u33549

@u33549 u33549 commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

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.

  • Graph sizes its path matrices by edges_.size() but indexes them by the node id, so a
    graph whose ids are sparse — or that has a node reachable only by an incoming edge —
    writes past the end of the matrix. Graph2D::shortestPath on a graph built with
    addDirectedEdge segfaults in a plain release build.
  • std::hash<Point> sums the coordinates, which is undefined for negative ones and puts
    points that operator== calls equal into different buckets. The graph then throws
    std::out_of_range for a node it actually holds.
  • Graph2D reports a missing node by throwing out of unordered_map::at, so every query
    has to be wrapped in try/catch even though the graph already has a way to say "no
    path": an empty vector, and INF.
  • createShortestGraph connects every swath end to the nearest border point of any cell
    it 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.

before after
before after

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.

before after
before after

1. Size the path matrices by node id (139f888)

numNodes() returned edges_.size(), the number of nodes with an outgoing edge, while
shortestPathsAndCosts, initializeMatrices, getPaths and allPathsBetween used it as
the id space. Three lines are enough to corrupt the heap:

f2c::types::Graph g;
g.addEdge(0, 5, 1);   // numNodes() == 2, matrices 2x2
g.shortestPath(0, 5); // dist[0][5]

getNodes() is added — the same method the v3.0 branch already has, collecting the keys
and the targets — and numNodes() is defined from it. Matrix sizing moves to a new
matrixSize(), the largest id plus one, so getCosts() and getPaths() keep being indexed
by node id. (v3.0 solves this by remapping to dense indices, which also removes those two
accessors; the v2 line still exposes them.)

2. Hash a Point from its coordinates (e568abb)

return size_t(p.getX() + p.getY() * 1e10 + p.getZ() * 1e20);

Two problems. size_t(-1e10) is undefined — the current test suite already triggers it
(Graph2D_test.cpp:11 uses {1, -1}); compile with -fsanitize=float-cast-overflow and it
reports. And the resolution is finer than operator=='s tolerance, so two points that
compare equal land in different buckets, which is what makes nodes_to_index_.at() throw
for 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 can
be fully consistent with it. If tolerant node identity is wanted, it needs a lookup that
knows about d_tol rather 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, allPathsBetween and removeDirectedEdge looked the
point up with at(). They now return an empty path, INF, an empty vector, and nothing.

This is not a new convention: reconstructPath already returns {} when there is no path,
shortestPathCost already reads INF out of the matrix, and the index form of
removeDirectedEdge is already a no-op for an edge that is not there. hasNode() is added
so 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 outside
the border it belongs to lands in no cell at all. A d_tol overload is added; the existing
one is untouched.

5. Connect a swath end only to its own cell (cc49ab3)

F2CCell cell = cells.getCellWherePoint(p, d_tol);
if (!cell.isEmpty()) {
  g.addEdge(p, cell.closestPointOnBorderTo(p));
}

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 genRoute
every swath end is inside the cells it was given, and the border point chosen is the same
one as before: for p inside cell A, any segment from p to another cell's border must
cross ∂A, so dist(p, ∂A) <= dist(p, ∂B) always.

One thing that is not this PR

Building with -fsanitize=address makes every test that calls genRoute segfault inside
or-tools' RoutingModel::NextVar, reached from computeBestRoute. It happens on an
unpatched tree as well, a plain Debug build without sanitizers is fine, and release is
fine — 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.

u33549 added 8 commits August 22, 2026 13:54
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.
Copilot AI lite review requested due to automatic review settings August 22, 2026 13:10

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@u33549

u33549 commented Aug 26, 2026

Copy link
Copy Markdown
Contributor Author

@Gonzalo-Mier is there anything need to change here?

@Gonzalo-Mier

Copy link
Copy Markdown
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!

@Gonzalo-Mier
Gonzalo-Mier merged commit 4b479cc into Fields2Cover:main Aug 27, 2026
68 checks passed
@u33549

u33549 commented Aug 27, 2026

Copy link
Copy Markdown
Contributor Author

Hi @Gonzalo-Mier,
I’m sending this message just as a reminder, in case it might have slipped your mind since it took a while. I truly admire your efforts and look to you as a role model.

@Gonzalo-Mier

Copy link
Copy Markdown
Member

I understand that and I thank your reminder. Please, be aware I value your work a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants