fix(affected): resolve the reference forms explain already accepts
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python name
(`pkg.mod.func`, #4366) to a single node. `affected` and `query --seed` answered
"No unique node match" for the very same string, so following the README's own
advice ("use the precise ID returned by the graph") forced a caller through
`explain` first merely to obtain an id.
`affected` also exited 0 on an ambiguous or unmatched seed, so a script could
not branch on the outcome the README documents (3 = ambiguous name, 4 = no
matching node) even though `explain` already follows it.
Both commands share `resolve_seed`, so the fix is one resolution path:
- `resolve_seed` now tries the qualified forms first, by delegating to the
tiered matcher `explain` uses (`serve._find_node_tiers`). Only the two
path-qualified forms are delegated: they carry their own disambiguating
context, so a match is never a guess. A bare name keeps going through the
existing tiers, where an exact-name tie must stay unresolved rather than be
broken by graph-iteration order (test_resolve_seed_bare_name_tie_still_returns_none).
- New `resolve_seed_outcome` reports whether a failure was ambiguity or a miss,
so the CLI can pick the documented exit code. The ambiguous case reuses
`serve._ambiguity_message`, so the same name reads identically in `explain`
and `affected`.
- `format_affected` takes an optional pre-resolved `seed`, so the CLI does not
resolve the same query twice.
Tests: new tests/test_affected_seed_reference_forms.py (8 tests) covers both
resolved forms, the bare-name tie that must stay unresolved, and the three exit
codes. I verified the resolution assertions fail on unmodified v8. One existing
test asserted the old exit 0 for an unmatched absolute seed; its intent (#2706:
never resolve to a wrong node) is preserved and only the exit-code assertion
changed.
Fixes #4792
Co-Authored-By: Claude <noreply@anthropic.com>
(cherry picked from commit 8537a59402)
This commit is contained in:
1 parent
992428e6d8
commit
35bf28a14f
4 files changed
+243
-3
No files matched your search
+59
-1
@@ -171,6 +171,36 @@ def _prefer_file_node(
|
||||
return None
|
||||
|
||||
|
||||
def resolve_reference_forms(graph: nx.Graph, query: str) -> str | None:
|
||||
"""Resolve the reference forms `explain` accepts but `resolve_seed` did not.
|
||||
|
||||
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python
|
||||
name (`pkg.mod.func` / `pkg.mod:func`, #4366) to a single node; `affected` and
|
||||
`query --seed` rejected both with "No unique node match" even when `explain`
|
||||
resolved the very same string. Following the README's own advice ("use the
|
||||
precise ID returned by the graph") therefore forced a caller through
|
||||
`explain` first just to obtain an id (#4792).
|
||||
|
||||
Only the two path-qualified forms are handled here — they carry their own
|
||||
disambiguating context, so a match is never a guess. A bare name keeps going
|
||||
through `resolve_seed`'s existing tiers, where an exact-name tie must stay
|
||||
unresolved rather than be broken by graph-iteration order.
|
||||
|
||||
Returns the unique node id, or None to fall through to the ordinary tiers.
|
||||
"""
|
||||
from graphify.serve import _find_node_tiers
|
||||
|
||||
source_exact, exact, _prefix, _substring = _find_node_tiers(graph, query)
|
||||
for tier in (source_exact, exact):
|
||||
if len(tier) == 1:
|
||||
return str(tier[0])
|
||||
if tier:
|
||||
# Several nodes in the winning tier is ambiguity, not precedence;
|
||||
# do not fall back to a looser tier and pick one arbitrarily.
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str | None:
|
||||
# A trailing path separator must not change a source-file match — serve's
|
||||
# _find_node tokenizes the path (which drops it), so strip it here for parity
|
||||
@@ -178,6 +208,11 @@ def resolve_seed(graph: nx.Graph, query: str, root: Path | None = None) -> str |
|
||||
query = query.rstrip("/\\") or query
|
||||
if query in graph:
|
||||
return query
|
||||
# `path::Symbol` and dotted Python names resolve exactly as `explain` does
|
||||
# (#4792); checked before the label tiers, which cannot express them.
|
||||
qualified = resolve_reference_forms(graph, query)
|
||||
if qualified is not None:
|
||||
return qualified
|
||||
query_lower = _normalize_label(query)
|
||||
exact_label_matches = [
|
||||
str(node_id)
|
||||
@@ -353,6 +388,27 @@ def affected_nodes(
|
||||
return hits
|
||||
|
||||
|
||||
def resolve_seed_outcome(
|
||||
graph: nx.Graph, query: str, root: Path | None = None
|
||||
) -> tuple[str | None, list[str]]:
|
||||
"""Resolve a seed and report why it failed, so the CLI can set an exit code.
|
||||
|
||||
`affected` printed "No unique node match" and still exited 0, so a script
|
||||
could not branch on the outcome the README documents (3 = ambiguous,
|
||||
4 = no match) while `explain` already follows it (#4792). Returns
|
||||
``(node_id, [])`` on success, ``(None, rivals)`` when the query is the
|
||||
ambiguous name of several nodes, and ``(None, [])`` when nothing matched.
|
||||
"""
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is not None:
|
||||
return seed, []
|
||||
from graphify.serve import find_node_ambiguity
|
||||
|
||||
normalized = query.rstrip("/\\") or query
|
||||
rivals = find_node_ambiguity(graph, normalized)
|
||||
return None, [str(node_id) for node_id in rivals]
|
||||
|
||||
|
||||
def format_affected(
|
||||
graph: nx.Graph,
|
||||
query: str,
|
||||
@@ -360,9 +416,11 @@ def format_affected(
|
||||
relations: Iterable[str] = DEFAULT_AFFECTED_RELATIONS,
|
||||
depth: int = 2,
|
||||
root: Path | None = None,
|
||||
seed: str | None = None,
|
||||
) -> str:
|
||||
relation_list = tuple(relations)
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is None:
|
||||
seed = resolve_seed(graph, query, root)
|
||||
if seed is None:
|
||||
return f"No unique node match for {query}"
|
||||
|
||||
|
||||
+21
-1
@@ -1735,7 +1735,12 @@ def dispatch_command(cmd: str) -> None:
|
||||
if len(sys.argv) < 3:
|
||||
print("Usage: graphify affected \"<node-or-label>\" [--relation R] [--depth N] [--graph path]", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
from graphify.affected import DEFAULT_AFFECTED_RELATIONS, format_affected, load_graph
|
||||
from graphify.affected import (
|
||||
DEFAULT_AFFECTED_RELATIONS,
|
||||
format_affected,
|
||||
load_graph,
|
||||
resolve_seed_outcome,
|
||||
)
|
||||
query = sys.argv[2]
|
||||
graph_path = _default_graph_path()
|
||||
depth = 2
|
||||
@@ -1790,6 +1795,20 @@ def dispatch_command(cmd: str) -> None:
|
||||
# --graph falls back to its own directory.
|
||||
from graphify.paths import GRAPHIFY_OUT_NAME
|
||||
graph_root = gp.parent.parent if gp.parent.name == GRAPHIFY_OUT_NAME else gp.parent
|
||||
# Resolve once so an unresolvable seed can set the documented exit code
|
||||
# (3 = ambiguous name, 4 = no matching node), matching `explain`; a
|
||||
# script could not branch on `affected` while it always exited 0 (#4792).
|
||||
seed, rivals = resolve_seed_outcome(graph, query, graph_root)
|
||||
if seed is None:
|
||||
if rivals:
|
||||
# Share `explain`'s refusal wording so the same ambiguous name
|
||||
# reads identically in both commands.
|
||||
from graphify.serve import _ambiguity_message
|
||||
|
||||
print(_ambiguity_message(graph, query, rivals), file=sys.stderr)
|
||||
sys.exit(EXIT_AMBIGUOUS)
|
||||
print(f"No unique node match for {query}", file=sys.stderr)
|
||||
sys.exit(EXIT_NOT_FOUND)
|
||||
print(
|
||||
format_affected(
|
||||
graph,
|
||||
@@ -1797,6 +1816,7 @@ def dispatch_command(cmd: str) -> None:
|
||||
relations=relations or DEFAULT_AFFECTED_RELATIONS,
|
||||
depth=depth,
|
||||
root=graph_root,
|
||||
seed=seed,
|
||||
)
|
||||
)
|
||||
elif cmd in ("god-nodes", "god_nodes"):
|
||||
|
||||
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import json
|
||||
|
||||
import networkx as nx
|
||||
import pytest
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
import graphify.__main__ as mainmod
|
||||
@@ -392,7 +393,12 @@ def test_affected_absolute_seed_outside_root_misses_cleanly(tmp_path, monkeypatc
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(mainmod.sys, "argv",
|
||||
["graphify", "affected", outside_seed, "--graph", str(gp)])
|
||||
mainmod.main()
|
||||
# An unmatched seed now exits EXIT_NOT_FOUND instead of 0 (#4792).
|
||||
with pytest.raises(SystemExit) as excinfo:
|
||||
mainmod.main()
|
||||
from graphify.cli import EXIT_NOT_FOUND
|
||||
|
||||
assert excinfo.value.code == EXIT_NOT_FOUND
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert "Affected nodes for Foo" not in out # must NOT resolve to the in-root Foo
|
||||
|
||||
@@ -0,0 +1,156 @@
|
||||
"""#4792 — `affected` and `query --seed` rejected the reference forms `explain`
|
||||
already resolved, and `affected` exited 0 on an ambiguous or unmatched seed.
|
||||
|
||||
`explain` resolves a `path::Symbol` reference (#3485) and a dotted Python name
|
||||
(`pkg.mod.func`, #4366) to a single node. `affected` and `query --seed` answered
|
||||
"No unique node match" for the very same string, so following the README's own
|
||||
advice ("use the precise ID returned by the graph") forced a caller through
|
||||
`explain` first merely to obtain an id. `affected` also exited 0 when the query
|
||||
was ambiguous or matched nothing, so a script could not branch on the outcome
|
||||
the README documents (3 = ambiguous, 4 = no match).
|
||||
|
||||
Regression shape: every assertion below fails on v8, where `resolve_seed`
|
||||
returns None for the qualified forms and the CLI always exits 0.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import networkx as nx
|
||||
import pytest
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
import graphify.__main__ as mainmod
|
||||
from graphify.affected import resolve_seed, resolve_seed_outcome
|
||||
|
||||
|
||||
def _two_same_named_functions() -> nx.DiGraph:
|
||||
"""Two `state` functions in different modules, plus one caller.
|
||||
|
||||
The layout from the issue: a path-qualified seed must single one out, while
|
||||
the bare name is genuinely ambiguous and must stay unresolved.
|
||||
"""
|
||||
g = nx.DiGraph()
|
||||
g.add_node("pkg", label="pkg", source_file="pkg/__init__.py", source_location="L1")
|
||||
g.add_node(
|
||||
"pkg_auth_mfa_state",
|
||||
label="state()",
|
||||
norm_label="state()",
|
||||
source_file="pkg/auth/mfa.py",
|
||||
source_location="L1",
|
||||
)
|
||||
g.add_node(
|
||||
"pkg_other_flow_state",
|
||||
label="state()",
|
||||
norm_label="state()",
|
||||
source_file="pkg/other/flow.py",
|
||||
source_location="L1",
|
||||
)
|
||||
g.add_node(
|
||||
"pkg_user_use",
|
||||
label="use()",
|
||||
norm_label="use()",
|
||||
source_file="pkg/user.py",
|
||||
source_location="L3",
|
||||
)
|
||||
g.add_edge("pkg_user_use", "pkg_auth_mfa_state", relation="calls",
|
||||
source_file="pkg/user.py", source_location="L4")
|
||||
return g
|
||||
|
||||
|
||||
def test_resolve_seed_accepts_path_scoped_symbol():
|
||||
"""`path::Symbol` resolves as it does in `explain` (#3485)."""
|
||||
g = _two_same_named_functions()
|
||||
assert resolve_seed(g, "pkg/auth/mfa.py::state") == "pkg_auth_mfa_state"
|
||||
|
||||
|
||||
def test_resolve_seed_accepts_dotted_python_name():
|
||||
"""`pkg.mod.func` resolves as it does in `explain` (#4366)."""
|
||||
g = _two_same_named_functions()
|
||||
assert resolve_seed(g, "pkg.auth.mfa.state") == "pkg_auth_mfa_state"
|
||||
|
||||
|
||||
def test_resolve_seed_bare_ambiguous_name_still_returns_none():
|
||||
"""A bare name shared by two modules stays unresolved — it must not guess."""
|
||||
g = _two_same_named_functions()
|
||||
assert resolve_seed(g, "state") is None
|
||||
|
||||
|
||||
def test_resolve_seed_outcome_reports_rivals_for_ambiguous_name():
|
||||
"""The ambiguity is reported so the CLI can exit 3 rather than 0."""
|
||||
g = _two_same_named_functions()
|
||||
seed, rivals = resolve_seed_outcome(g, "state")
|
||||
assert seed is None
|
||||
assert set(rivals) == {"pkg_auth_mfa_state", "pkg_other_flow_state"}
|
||||
|
||||
|
||||
def test_resolve_seed_outcome_reports_no_rivals_for_a_miss():
|
||||
"""A query that matches nothing is a miss (exit 4), not an ambiguity (exit 3)."""
|
||||
g = _two_same_named_functions()
|
||||
seed, rivals = resolve_seed_outcome(g, "nothing_like_this")
|
||||
assert seed is None
|
||||
assert rivals == []
|
||||
|
||||
|
||||
def _write_graph(tmp_path, graph: nx.Graph) -> str:
|
||||
from graphify.paths import GRAPHIFY_OUT_NAME
|
||||
|
||||
out_dir = tmp_path / "repo" / GRAPHIFY_OUT_NAME
|
||||
out_dir.mkdir(parents=True)
|
||||
gp = out_dir / "graph.json"
|
||||
gp.write_text(json.dumps(json_graph.node_link_data(graph, edges="links")), encoding="utf-8")
|
||||
return str(gp)
|
||||
|
||||
|
||||
def _run_affected(monkeypatch, graph_path: str, query: str) -> int:
|
||||
"""Run `graphify affected <query>` and return its exit code (0 when it returns)."""
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(
|
||||
mainmod.sys, "argv", ["graphify", "affected", query, "--graph", graph_path]
|
||||
)
|
||||
try:
|
||||
mainmod.main()
|
||||
except SystemExit as exc: # only the failure paths exit explicitly
|
||||
return int(exc.code or 0)
|
||||
return 0
|
||||
|
||||
|
||||
def test_affected_cli_resolves_path_scoped_symbol(tmp_path, monkeypatch, capsys):
|
||||
"""The exact repro from the issue: affected now resolves what explain resolves."""
|
||||
graph_path = _write_graph(tmp_path, _two_same_named_functions())
|
||||
|
||||
code = _run_affected(monkeypatch, graph_path, "pkg/auth/mfa.py::state")
|
||||
|
||||
out = capsys.readouterr().out
|
||||
assert code == 0
|
||||
assert "Affected nodes for state()" in out
|
||||
assert "use()" in out
|
||||
|
||||
|
||||
def test_affected_cli_exits_3_on_ambiguous_seed(tmp_path, monkeypatch, capsys):
|
||||
"""README documents exit 3 for an ambiguous name; affected used to exit 0."""
|
||||
from graphify.cli import EXIT_AMBIGUOUS
|
||||
|
||||
graph_path = _write_graph(tmp_path, _two_same_named_functions())
|
||||
|
||||
code = _run_affected(monkeypatch, graph_path, "state")
|
||||
|
||||
err = capsys.readouterr().err
|
||||
assert code == EXIT_AMBIGUOUS
|
||||
assert err.startswith("Ambiguous:")
|
||||
# Both candidates must be named so the caller can pick one.
|
||||
assert "pkg/auth/mfa.py" in err
|
||||
assert "pkg/other/flow.py" in err
|
||||
|
||||
|
||||
def test_affected_cli_exits_4_on_unmatched_seed(tmp_path, monkeypatch, capsys):
|
||||
"""README documents exit 4 for no matching node; affected used to exit 0."""
|
||||
from graphify.cli import EXIT_NOT_FOUND
|
||||
|
||||
graph_path = _write_graph(tmp_path, _two_same_named_functions())
|
||||
|
||||
code = _run_affected(monkeypatch, graph_path, "nothing_like_this")
|
||||
|
||||
err = capsys.readouterr().err
|
||||
assert code == EXIT_NOT_FOUND
|
||||
assert "No unique node match" in err
|
||||
Reference in new issue
Block a user