fix(serve): traverse the MCP query_graph undirected so a seed with no outgoing edges reaches its callers
`_load_graph` forces `directed: True` so renderers can recover stored arc
order (#2309), and `_bfs`/`_dfs` expand through `G.neighbors()`, which on a
DiGraph yields successors only. Seeded on a leaf that is only ever called,
imported and contained, the MCP `query_graph` therefore answered with the
seed alone, while the CLI `query` — which loads the same graph.json
undirected on purpose (#2080) — returned the callers, the test and the
neighbouring modules. Same shape as #1174: one read surface missed a fix
the others got.
Add `_traversal_view`: an undirected copy for the traversal with `_src`/
`_tgt` stashed per edge, so `_subgraph_to_text` keeps rendering
caller->callee regardless of the side the traversal reached the edge from.
An undirected input is returned as-is, so the CLI path is unchanged;
`_load_graph` is untouched because `get_neighbors` and `shortest_path`
rely on direction explicitly.
Regression tests seed the same `calls` edge from both endpoints through
`_load_graph`, in both traversal modes, with and without a context filter;
the callee-seeded ones fail on the prior code with `1 nodes found`.
(cherry picked from commit 341aec5286)
This commit is contained in:
1 parent
6e420a0840
commit
29b7a21e98
2 files changed
+143
-1
No files matched your search
+44
-1
@@ -1230,6 +1230,49 @@ def _display_graph_path(graph_path: str) -> str:
|
||||
return str(graph_path)
|
||||
|
||||
|
||||
def _traversal_view(G: nx.Graph) -> nx.Graph:
|
||||
"""Undirected copy of `G` for BFS/DFS, with true direction kept per edge.
|
||||
|
||||
`_load_graph` forces `directed: True` so renderers can recover stored arc
|
||||
order (#2309), and on a DiGraph `G.neighbors()` yields successors only. The
|
||||
query traversals rely on `neighbors()`, so a seed with no outgoing edges — a
|
||||
leaf function that is only ever called, imported and contained — expanded
|
||||
to nothing: `query_graph` over MCP answered with the seed alone while the
|
||||
CLI `query`, which loads the same file undirected, returned the callers,
|
||||
the test and the neighbouring modules. Every other MCP tool was unaffected:
|
||||
`get_neighbors` walks successors and predecessors explicitly, and
|
||||
`shortest_path` builds its own graph from `_src`/`_tgt`.
|
||||
|
||||
Mirrors the CLI loader: traverse undirected, stash `_src`/`_tgt` on each
|
||||
edge so `_subgraph_to_text` still renders caller->callee regardless of the
|
||||
side the traversal reached the edge from. Markers already present on an
|
||||
edge win, for the same reason as in the CLI (#2309). An undirected input is
|
||||
returned as-is, so the CLI path is unchanged.
|
||||
|
||||
Mutual arcs `u->v` and `v->u` (mutual recursion, a circular import) fold
|
||||
into one undirected edge on a plain `DiGraph` input, the later one winning
|
||||
— the same fold the CLI loader performs when `json_graph.node_link_graph`
|
||||
reads the undirected on-disk graph into an `nx.Graph`, which is what keeps
|
||||
the two surfaces' output identical. The renderer shows one edge per pair
|
||||
in any case. On a `MultiDiGraph` input the copy is a `MultiGraph` and the
|
||||
stored keys are not carried over: a key is unique per unordered pair on an
|
||||
undirected multigraph, so mutual arcs that happen to share a key would
|
||||
fold there too; letting networkx assign the keys keeps both, and nothing
|
||||
downstream reads the key.
|
||||
|
||||
A fresh copy per query rather than a cached one: `_filter_graph_by_context`
|
||||
already copies per query when a filter applies, and the copy shares node
|
||||
data dicts with `G`, so only the edge dicts are duplicated.
|
||||
"""
|
||||
if not G.is_directed():
|
||||
return G
|
||||
H = nx.MultiGraph() if G.is_multigraph() else nx.Graph()
|
||||
H.graph.update(G.graph)
|
||||
H.add_nodes_from(G.nodes(data=True))
|
||||
for u, v, d in G.edges(data=True):
|
||||
H.add_edge(u, v, **{**d, "_src": d.get("_src", u), "_tgt": d.get("_tgt", v)})
|
||||
return H
|
||||
|
||||
def _query_graph_text(
|
||||
G: nx.Graph,
|
||||
question: str,
|
||||
@@ -1265,7 +1308,7 @@ def _query_graph_text(
|
||||
if not start_nodes:
|
||||
return "No matching nodes found."
|
||||
resolved_filters, filter_source = _resolve_context_filters(question, context_filters)
|
||||
traversal_graph = _filter_graph_by_context(G, resolved_filters)
|
||||
traversal_graph = _filter_graph_by_context(_traversal_view(G), resolved_filters)
|
||||
nodes, edges = _dfs(traversal_graph, start_nodes, depth) if mode == "dfs" else _bfs(traversal_graph, start_nodes, depth)
|
||||
header_parts = [
|
||||
f"Traversal: {mode.upper()} depth={depth}",
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""`_query_graph_text` on the directed graph `_load_graph` builds (the MCP path).
|
||||
|
||||
The CLI `query` loads graph.json undirected and is covered by
|
||||
tests/test_query_cli.py::test_query_cli_preserves_calls_direction_when_seeded_on_callee.
|
||||
The MCP server loads the same file through `_load_graph`, which forces
|
||||
`directed: True` (#2309), and `_bfs`/`_dfs` expand through `G.neighbors()` —
|
||||
successors only on a DiGraph. Seeded on a node with no outgoing edges the
|
||||
traversal therefore stopped at the seed, and `query_graph` answered with one
|
||||
node where the CLI answered with the callers.
|
||||
"""
|
||||
import json
|
||||
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
from graphify.serve import _load_graph, _query_graph_text
|
||||
|
||||
|
||||
def _write_calls_graph(tmp_path):
|
||||
"""One `calls` edge, on-disk undirected — the `graphify extract` shape."""
|
||||
G = nx.Graph()
|
||||
G.add_node("caller", label="caller_fn", source_file="a.py", source_location="L1", community=0)
|
||||
G.add_node("callee", label="callee_fn", source_file="b.py", source_location="L1", community=1)
|
||||
G.add_edge("caller", "callee", relation="calls", confidence="EXTRACTED", context="call")
|
||||
graph_path = tmp_path / "graph.json"
|
||||
graph_path.write_text(json.dumps(json_graph.node_link_data(G, edges="links")))
|
||||
return graph_path
|
||||
|
||||
|
||||
def test_mcp_query_seeded_on_callee_reaches_the_caller(tmp_path):
|
||||
G = _load_graph(str(tmp_path / "graph.json")) if False else _load_graph(str(_write_calls_graph(tmp_path)))
|
||||
assert G.is_directed() # the precondition the defect depends on
|
||||
for mode in ("bfs", "dfs"):
|
||||
text = _query_graph_text(G, "callee_fn", mode=mode, depth=2)
|
||||
assert "2 nodes found" in text, text
|
||||
assert "NODE caller_fn" in text
|
||||
# Direction is rendered from the stored edge, not from the visit order.
|
||||
assert "caller_fn --calls" in text
|
||||
assert "callee_fn --calls" not in text
|
||||
|
||||
|
||||
def test_mcp_query_seeded_on_caller_is_unchanged(tmp_path):
|
||||
G = _load_graph(str(_write_calls_graph(tmp_path)))
|
||||
text = _query_graph_text(G, "caller_fn", mode="bfs", depth=2)
|
||||
assert "2 nodes found" in text
|
||||
assert "caller_fn --calls" in text
|
||||
assert "callee_fn --calls" not in text
|
||||
|
||||
|
||||
def test_mcp_query_explicit_context_filter_still_applies(tmp_path):
|
||||
G = _load_graph(str(_write_calls_graph(tmp_path)))
|
||||
kept = _query_graph_text(G, "callee_fn", depth=2, context_filters=["call"])
|
||||
assert "Context: call (explicit)" in kept and "NODE caller_fn" in kept
|
||||
dropped = _query_graph_text(G, "callee_fn", depth=2, context_filters=["import"])
|
||||
assert "Context: import (explicit)" in dropped and "NODE caller_fn" not in dropped
|
||||
|
||||
|
||||
def test_traversal_view_keeps_multigraph_parallel_and_mutual_edges():
|
||||
from graphify.serve import _traversal_view
|
||||
G = nx.MultiDiGraph()
|
||||
G.add_node("a", label="a"); G.add_node("b", label="b")
|
||||
G.add_edge("a", "b", relation="calls"); G.add_edge("a", "b", relation="imports")
|
||||
# Mutual arcs get key 0 on both sides of the DiGraph; on an undirected
|
||||
# multigraph that key names one edge per unordered pair, so carrying the
|
||||
# keys over would collapse a<->b into a single edge.
|
||||
G.add_edge("b", "a", relation="calls")
|
||||
H = _traversal_view(G)
|
||||
assert not H.is_directed() and H.is_multigraph()
|
||||
assert H.number_of_edges() == 3
|
||||
assert sorted((d["_src"], d["_tgt"]) for _, _, d in H.edges(data=True)) == [("a", "b"), ("a", "b"), ("b", "a")]
|
||||
|
||||
|
||||
def test_traversal_view_leaves_undirected_graph_alone():
|
||||
from graphify.serve import _traversal_view
|
||||
G = nx.Graph()
|
||||
G.add_edge("a", "b", relation="calls")
|
||||
assert _traversal_view(G) is G
|
||||
|
||||
|
||||
def test_traversal_view_folds_mutual_arcs_like_the_cli_loader(tmp_path):
|
||||
"""On a plain DiGraph, u->v and v->u become one undirected edge — the same
|
||||
fold the CLI's undirected load of graph.json performs, so the two read
|
||||
surfaces keep returning the same subgraph."""
|
||||
from graphify.serve import _traversal_view
|
||||
G = nx.Graph()
|
||||
G.add_node("a", label="a_fn", source_file="a.py", source_location="L1", community=0)
|
||||
G.add_node("b", label="b_fn", source_file="b.py", source_location="L1", community=0)
|
||||
# An undirected on-disk graph can only hold one a-b link; write it as the
|
||||
# links list explicitly so both directions are present on disk.
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
data["links"] = [
|
||||
{"source": "a", "target": "b", "relation": "calls", "confidence": "EXTRACTED", "context": "call"},
|
||||
{"source": "b", "target": "a", "relation": "calls", "confidence": "EXTRACTED", "context": "call"},
|
||||
]
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(data))
|
||||
cli_like = json_graph.node_link_graph(json.loads(p.read_text()), edges="links")
|
||||
mcp_view = _traversal_view(_load_graph(str(p)))
|
||||
assert cli_like.number_of_edges() == mcp_view.number_of_edges() == 1
|
||||
Reference in new issue
Block a user