feat(path): report the weakest of several equal-length routes (#4881)

Second half of #4881. 'path'/shortest_path returned an arbitrary route
among equal-length shortest paths (nx.shortest_path), so the reported
confidence could reflect a strong route while a weaker route of the same
length existed. Among all shortest paths (bounded at 256 to avoid
exponential enumeration), choose the one whose weakest hop is weakest and
note it was the weakest of N equal-length routes, so the confidence never
overstates the connection.

Factors _path_weakest out of _path_confidence_line and adds
_path_hop_datas / _path_confidence_key / _weakest_shortest_path in
serve.py, used by both the CLI path command and the MCP tool. No cache
bump (path rendering is post-extraction).

Refs #4881. Idea/report by @SyedFahad7.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
safishamsiandClaude Opus 4.8 committed 2026-10-30 23:06:18 +00:00
1 parent 26818d0857
commit 193c9f36b3
4 files changed
+129 -12

No files matched your search

+4
View File
@@ -2,6 +2,10 @@
Full release notes with details on each version: [GitHub Releases](https://github.com/Graphify-Labs/graphify/releases)
## 0.9.99 (unreleased)
- Feat: **path** when several routes tie on length, `graphify path` and the MCP `shortest_path` tool report the most conservative one: among all shortest paths, the route whose weakest hop is weakest is chosen, and the summary notes it was the weakest of N equal-length routes. Previously an arbitrary equal-length route was returned, so the confidence could overstate how sure the connection is. This is the second half of #4881 (the first half, keeping a collapsed edge's weaker evidence in `also_seen`, shipped in 0.9.98 via #4891, thanks @SyedFahad7).
## 0.9.98 (2026-10-30)
- Fix: **build** when duplicate same-relation edges collapse, the losing (weaker-confidence) copy's provenance is kept in an `also_seen` list on the surviving edge instead of being discarded, so the weaker evidence is not silently lost; the field is serialized to graph.json and is idempotent across rebuilds (#4881, #4891, thanks @SyedFahad7).
+9 -2
View File
@@ -2054,12 +2054,14 @@ def dispatch_command(cmd: str) -> None:
# returned an arbitrary route among equal-length paths that varied per
# process. Build a sorted, materialized graph so neighbor order — and
# thus the chosen path — is canonical for a given graph.json.
from graphify.serve import _weakest_shortest_path
try:
if undirected:
_und = _nx.Graph()
_und.add_nodes_from(sorted(G.nodes))
_und.add_edges_from(sorted((min(u, v), max(u, v)) for u, v in G.edges()))
path_nodes = _nx.shortest_path(_und, src_nid, tgt_nid)
path_nodes, _n_routes, _routes_capped = _weakest_shortest_path(
_und, G, src_nid, tgt_nid)
else:
# Directed by default (#2487). True direction is NOT raw arc
# order: legacy canonicalized files persist a flipped arc with
@@ -2084,7 +2086,8 @@ def dispatch_command(cmd: str) -> None:
for u, v, d in G.edges(data=True)
if d.get("relation") == "contains"
))
path_nodes = _nx.shortest_path(_dg, src_nid, tgt_nid)
path_nodes, _n_routes, _routes_capped = _weakest_shortest_path(
_dg, G, src_nid, tgt_nid)
except (_nx.NetworkXNoPath, _nx.NodeNotFound):
if undirected:
print(f"No path found between '{source_label}' and '{target_label}'.")
@@ -2132,6 +2135,10 @@ def dispatch_command(cmd: str) -> None:
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
print(f"Shortest path ({hops} hops):\n " + " ".join(segments))
_summary = _path_confidence_line(hop_datas)
if _summary and _n_routes > 1:
# Several routes tie on length; report the weakest's confidence so it
# never overstates how sure the connection is (#4881).
_summary += f" (weakest of {'256+' if _routes_capped else _n_routes} equal-length routes)"
if _summary:
print(_summary)
from graphify import querylog
+74 -10
View File
@@ -2259,16 +2259,14 @@ def _path_search_graph(G: nx.Graph, undirected: bool) -> nx.Graph:
return H
def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
"""Overall confidence of a path: its weakest hop (#4885).
def _path_weakest(hop_datas: list[list[dict]]):
"""The weakest hop of a path, or None when no hop carries confidence.
A path is only as sure as its least certain hop. Each hop is ranked by
the weakest evidence it carries (`_CONFIDENCE_RANK`, then the lowest
`confidence_score`; a missing score never counts as weaker than a present
one), and the first weakest hop is named. A hop with no recognised
confidence tag ranks below AMBIGUOUS and makes the whole path unknown.
EXTRACTED is 1.0 by definition, so its score is neither ranked nor
printed, matching the per-hop tags.
Each hop is ranked by the weakest evidence it carries (`_CONFIDENCE_RANK`,
then the lowest `confidence_score`; a missing score never counts as weaker
than a present one). EXTRACTED is 1.0 by definition, so its score is neither
ranked nor printed, matching the per-hop tags. Returns
`(key, hop, rel, conf, score)` where `key` sorts weakest-first.
"""
weakest = None
for hop, datas in enumerate(hop_datas, 1):
@@ -2287,6 +2285,17 @@ def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
key = (rank, score is None, score or 0.0, hop)
if weakest is None or key < weakest[0]:
weakest = (key, hop, d.get("relation") or "related", conf if rank else None, score)
return weakest
def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
"""Overall confidence of a path: its weakest hop (#4885).
A path is only as sure as its least certain hop (see `_path_weakest`). A hop
with no recognised confidence tag ranks below AMBIGUOUS and makes the whole
path unknown.
"""
weakest = _path_weakest(hop_datas)
if weakest is None:
return ""
_, hop, rel, conf, score = weakest
@@ -2296,6 +2305,55 @@ def _path_confidence_line(hop_datas: list[list[dict]]) -> str:
return f"Path confidence: {conf} (weakest hop {hop}: {rel}{score_str})"
# Enough equal-length routes to find the weakest among them without letting a
# pathological graph enumerate an exponential number of shortest paths (#4881).
_MAX_SHORTEST_PATHS = 256
def _path_hop_datas(G: nx.Graph, path_nodes: list[str]) -> list[list[dict]]:
"""Per-hop edge-data lists for a node path, honouring `_src` direction
markers (#2309) the same way the path renderer does."""
hop_datas: list[list[dict]] = []
for i in range(len(path_nodes) - 1):
u, v = path_nodes[i], path_nodes[i + 1]
fwd, bwd = [], []
for a, b in ((u, v), (v, u)):
if G.has_edge(a, b):
for d in edge_datas(G, a, b):
(fwd if d.get("_src", a) == u else bwd).append(d)
hop_datas.append(fwd or bwd)
return hop_datas
def _path_confidence_key(hop_datas: list[list[dict]]):
"""Sortable, weakest-first key for a whole path. A path that carries no
confidence evidence at all is 'unknown' and sorts below any tagged path."""
weakest = _path_weakest(hop_datas)
return weakest[0] if weakest is not None else (-1, True, 0.0, 0)
def _weakest_shortest_path(search_graph: nx.Graph, G: nx.Graph, src_nid: str, tgt_nid: str):
"""Among all shortest paths `src_nid` -> `tgt_nid`, the most conservative one.
A path is only as sure as its weakest hop, so when several routes tie on
length the reported confidence should reflect the weakest of them, not an
arbitrary route networkx happens to return first (#4881). Enumeration is
bounded by `_MAX_SHORTEST_PATHS`. Raises `nx.NetworkXNoPath` /
`nx.NodeNotFound` exactly like `nx.shortest_path`, so callers keep their
existing error handling. Returns `(path_nodes, n_routes, capped)`.
"""
paths: list[list[str]] = []
for p in nx.all_shortest_paths(search_graph, src_nid, tgt_nid):
paths.append(p)
if len(paths) > _MAX_SHORTEST_PATHS:
break
capped = len(paths) > _MAX_SHORTEST_PATHS
if capped:
paths = paths[:_MAX_SHORTEST_PATHS]
chosen = min(paths, key=lambda p: _path_confidence_key(_path_hop_datas(G, p)))
return chosen, len(paths), capped
def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
"""Body of the `shortest_path` MCP tool (module-level so tests can call it
without an mcp install).
@@ -2338,7 +2396,9 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
max_hops = int(arguments.get("max_hops", 8))
undirected = bool(arguments.get("undirected", False))
try:
path_nodes = nx.shortest_path(_path_search_graph(G, undirected), src_nid, tgt_nid)
path_nodes, n_routes, routes_capped = _weakest_shortest_path(
_path_search_graph(G, undirected), G, src_nid, tgt_nid
)
except (nx.NetworkXNoPath, nx.NodeNotFound):
src_label = G.nodes[src_nid].get("label", src_nid)
tgt_label = G.nodes[tgt_nid].get("label", tgt_nid)
@@ -2380,6 +2440,10 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
prefix = ("\n".join(warnings) + "\n") if warnings else ""
summary = _path_confidence_line(hop_datas)
if n_routes > 1 and summary:
# Several routes tie on length; the confidence shown is the weakest of
# them (#4881), so it never overstates how sure the connection is.
summary += f" (weakest of {'256+' if routes_capped else n_routes} equal-length routes)"
return (
prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
+ (f"\n{summary}" if summary else "")
+42
View File
@@ -119,3 +119,45 @@ def test_parallel_edges_and_also_seen_count_toward_their_hop():
def test_hop_without_confidence_makes_path_unknown():
hops = [[_e("calls", "EXTRACTED")], [_e("calls")]]
assert _path_confidence_line(hops) == "Path confidence: unknown (hop 2: calls has no confidence tag)"
def _two_route_graph():
"""Two equal-length (2-hop) routes A -> C: a strong one via B1 (all
EXTRACTED) and a weak one via B2 (an AMBIGUOUS hop). #4881 second half:
the reported confidence must reflect the weakest route, not whichever one
networkx returns first."""
def n(nid):
return {"id": nid, "label": nid, "file_type": "code", "source_file": "m.py"}
return build_from_json({
"nodes": [n("A"), n("B1"), n("C"), n("B2")],
"edges": [
{"source": "A", "target": "B1", "relation": "calls",
"confidence": "EXTRACTED", "source_file": "m.py", "source_location": "L1"},
{"source": "B1", "target": "C", "relation": "calls",
"confidence": "EXTRACTED", "source_file": "m.py", "source_location": "L2"},
{"source": "A", "target": "B2", "relation": "calls",
"confidence": "EXTRACTED", "source_file": "m.py", "source_location": "L3"},
{"source": "B2", "target": "C", "relation": "dispatches_to",
"confidence": "AMBIGUOUS", "confidence_score": 0.3,
"source_file": "m.py", "source_location": "L4"},
],
"hyperedges": [],
})
def test_multiple_routes_report_the_weakest_route():
"""Among equal-length routes, the weakest route's confidence is surfaced."""
G = _two_route_graph()
out = _shortest_path_text(G, {"source": "A", "target": "C"})
last = out.splitlines()[-1]
# Must report the AMBIGUOUS (weak) route, not the EXTRACTED (strong) one,
# and say it chose the weakest of the equal-length routes.
assert "AMBIGUOUS" in last, out
assert "weakest of 2 equal-length routes" in last, out
def test_single_route_has_no_equal_length_note():
"""A unique shortest path must not carry the multi-route suffix."""
G = _report_graph()
out = _shortest_path_text(G, {"source": "report_exporter_run", "target": "report_pdfreport_build"})
assert "equal-length routes" not in out, out