Merge pull request #4891 from SyedFahad7/fix/4881-keep-weaker-evidence
fix(build): keep a collapsed edge's weaker evidence in also_seen (#4881)
This commit is contained in:
5 files changed
+249
-4
No files matched your search
@@ -97,5 +97,6 @@ Each edge has:
|
||||
- `confidence` — `EXTRACTED`, `INFERRED`, or `AMBIGUOUS`
|
||||
- `confidence_score` — float (INFERRED only)
|
||||
- `source_file` — where the relationship was found
|
||||
- `also_seen` — optional; when the same relation between the same two nodes was found more than once, the edge keeps the highest-confidence copy and lists each other copy's `confidence`, `confidence_score`, `source_file` and `source_location` here, weakest first. `graphify path` shows their tags next to the edge's own (`[AMBIGUOUS/INFERRED]`)
|
||||
|
||||
Hyperedges (group relationships connecting 3+ nodes) live in `G.graph["hyperedges"]`.
|
||||
@@ -189,6 +189,66 @@ _GENERIC_RELATIONS: frozenset[str] = frozenset({"references", "uses", "mentions"
|
||||
# `calls` is not ranked here.
|
||||
_STRUCTURAL_MEMBER_RELATIONS: frozenset[str] = frozenset({"method", "contains"})
|
||||
_CONFIDENCE_RANK: dict[str, int] = {"EXTRACTED": 3, "INFERRED": 2, "AMBIGUOUS": 1}
|
||||
# The fields that say how sure the graph is of an edge and where that came from.
|
||||
# A same-relation collision keeps one edge; the loser's copy of these fields is
|
||||
# folded into the winner's `also_seen` list instead of being discarded (#4881).
|
||||
_EVIDENCE_KEYS: tuple[str, ...] = ("confidence", "confidence_score", "source_file", "source_location")
|
||||
|
||||
|
||||
def _evidence(attrs: dict) -> dict:
|
||||
"""The provenance fields of one edge (or ``also_seen`` entry), scalars only."""
|
||||
out: dict = {}
|
||||
for key in _EVIDENCE_KEYS:
|
||||
val = attrs.get(key)
|
||||
if isinstance(val, bool) or val is None or val == "":
|
||||
continue
|
||||
if key == "confidence_score":
|
||||
try:
|
||||
val = float(val)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if not math.isfinite(val):
|
||||
continue
|
||||
elif not isinstance(val, (str, int, float)):
|
||||
continue
|
||||
out[key] = val
|
||||
return out
|
||||
|
||||
|
||||
def _evidence_sort_key(ev: dict) -> tuple:
|
||||
# Weakest first: lowest confidence tier, then lowest score.
|
||||
score = ev.get("confidence_score")
|
||||
return (
|
||||
_CONFIDENCE_RANK.get(str(ev.get("confidence", "")), 0),
|
||||
score is None,
|
||||
score if score is not None else 0.0,
|
||||
str(ev.get("source_file", "")),
|
||||
str(ev.get("source_location", "")),
|
||||
)
|
||||
|
||||
|
||||
def edge_evidence(d: dict) -> list[dict]:
|
||||
"""Every provenance record an edge carries: its own, then each ``also_seen``."""
|
||||
also = d.get("also_seen")
|
||||
return [d, *(a for a in also if isinstance(a, dict))] if isinstance(also, list) else [d]
|
||||
|
||||
|
||||
def _fold_also_seen(winner: dict, loser: dict) -> None:
|
||||
"""Record ``loser``'s provenance on ``winner`` when the two collapse (#4881).
|
||||
|
||||
Entries that repeat the winner's own provenance, or each other, are dropped,
|
||||
so re-feeding a written graph.json through the build is idempotent.
|
||||
"""
|
||||
own = _evidence(winner)
|
||||
kept: list[dict] = []
|
||||
for raw in (*edge_evidence(winner)[1:], loser, *edge_evidence(loser)[1:]):
|
||||
ev = _evidence(raw)
|
||||
if ev and not ev.items() <= own.items() and ev not in kept:
|
||||
kept.append(ev)
|
||||
if kept:
|
||||
winner["also_seen"] = sorted(kept, key=_evidence_sort_key)
|
||||
else:
|
||||
winner.pop("also_seen", None)
|
||||
|
||||
# Import-family relations whose target may legitimately be a module OUTSIDE the
|
||||
# graph (stdlib, a third-party dependency, another repo). Historically the edge
|
||||
@@ -1782,6 +1842,8 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
if not math.isfinite(_num_val) or _num_val < 0:
|
||||
_num_val = 1.0
|
||||
attrs[_num_key] = _num_val
|
||||
if "also_seen" in attrs:
|
||||
_fold_also_seen(attrs, {})
|
||||
# Backfill source_file from the endpoint nodes (every node carries one).
|
||||
# Semantic/LLM edges occasionally omit it, which downstream validation
|
||||
# flags and leaves query results with no file reference (#1279).
|
||||
@@ -1910,9 +1972,11 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
existing_rank = _CONFIDENCE_RANK.get(existing_conf, 0)
|
||||
incoming_rank = _CONFIDENCE_RANK.get(incoming_conf, 0)
|
||||
if existing_rank > incoming_rank:
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
if existing_rank == incoming_rank:
|
||||
if existing_attrs.get("source_location") and not attrs.get("source_location"):
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
existing_score = existing_attrs.get("confidence_score")
|
||||
incoming_score = attrs.get("confidence_score")
|
||||
@@ -1921,7 +1985,14 @@ def build_from_json(extraction: dict, *, directed: bool = False, root: str | Pat
|
||||
and incoming_score is not None
|
||||
and existing_score > incoming_score
|
||||
):
|
||||
_fold_also_seen(existing_attrs, attrs)
|
||||
continue
|
||||
_fold_also_seen(attrs, existing_attrs)
|
||||
# add_edge merges into the stored dict: a field only the loser
|
||||
# carried (its score, its line) would otherwise stay on the winner.
|
||||
for _key in (*_EVIDENCE_KEYS, "also_seen"):
|
||||
if _key not in attrs:
|
||||
existing_attrs.pop(_key, None)
|
||||
G.add_edge(src, tgt, **attrs)
|
||||
if dropped_schema_edges:
|
||||
print(
|
||||
|
||||
+2
-2
@@ -2097,7 +2097,7 @@ def dispatch_command(cmd: str) -> None:
|
||||
sys.exit(0)
|
||||
hops = len(path_nodes) - 1
|
||||
segments = []
|
||||
from graphify.build import edge_datas
|
||||
from graphify.build import edge_datas, edge_evidence
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
# Report the ACTUAL stored relation(s) of the traversed pair and
|
||||
@@ -2119,7 +2119,7 @@ def dispatch_command(cmd: str) -> None:
|
||||
forward = bool(fwd)
|
||||
rels = sorted({d.get("relation") for d in datas if d.get("relation")})
|
||||
rel = "/".join(rels) if rels else "related"
|
||||
confs = sorted({d.get("confidence") for d in datas if d.get("confidence")})
|
||||
confs = sorted({e["confidence"] for d in datas for e in edge_evidence(d) if e.get("confidence")})
|
||||
conf_str = f" [{'/'.join(confs)}]" if confs else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ from typing import NamedTuple
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from graphify.security import sanitize_label, check_graph_file_size_cap, _CONTROL_CHAR_RE
|
||||
from graphify.build import edge_datas, has_parallel_links
|
||||
from graphify.build import edge_datas, edge_evidence, has_parallel_links
|
||||
from graphify.paths import default_graph_json as _default_graph_json
|
||||
|
||||
try:
|
||||
@@ -2141,7 +2141,7 @@ def _shortest_path_text(G: nx.Graph, arguments: dict) -> str:
|
||||
forward = bool(fwd)
|
||||
rels = sorted({d.get("relation") for d in datas if d.get("relation")})
|
||||
rel = "/".join(rels) if rels else "related"
|
||||
confs = sorted({d.get("confidence") for d in datas if d.get("confidence")})
|
||||
confs = sorted({e["confidence"] for d in datas for e in edge_evidence(d) if e.get("confidence")})
|
||||
conf_str = f" [{'/'.join(confs)}]" if confs else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
"""A same-relation edge collision must not erase the losing edge's provenance (#4881).
|
||||
|
||||
`build_from_json` keeps one edge per pair and relation, and since #3711 the
|
||||
higher-confidence edge wins. The loser used to vanish: an AMBIGUOUS semantic
|
||||
duplicate of an INFERRED dispatch edge left no trace in graph.json. The winner
|
||||
now carries the loser's confidence / score / file / line in `also_seen`, and
|
||||
`path` unions those tags into the hop label the way it already does for
|
||||
parallel edges.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from networkx.readwrite import json_graph
|
||||
|
||||
import graphify.__main__ as mainmod
|
||||
from graphify.build import build_from_json, edge_data
|
||||
from graphify.serve import _shortest_path_text
|
||||
|
||||
REPORT_CS = """\
|
||||
public interface IReport { string Build(); }
|
||||
public class PdfReport : IReport { public string Build() { return "pdf"; } }
|
||||
public class CsvReport : IReport { public string Build() { return "csv"; } }
|
||||
public class Exporter {
|
||||
private readonly IReport _report;
|
||||
public Exporter(IReport report) { _report = report; }
|
||||
public string Run() { return _report.Build(); }
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _node(nid, label):
|
||||
return {"id": nid, "label": label, "file_type": "code", "source_file": "Report.cs"}
|
||||
|
||||
|
||||
def _report_extraction(extra_edges=()):
|
||||
"""The AST extraction of REPORT_CS (call + dispatch edges), plus extras."""
|
||||
return {
|
||||
"nodes": [
|
||||
_node("report_exporter_run", ".Run()"),
|
||||
_node("report_ireport_build", ".Build()"),
|
||||
_node("report_pdfreport_build", ".Build()"),
|
||||
_node("report_csvreport_build", ".Build()"),
|
||||
],
|
||||
"edges": [
|
||||
{"source": "report_exporter_run", "target": "report_ireport_build",
|
||||
"relation": "calls", "confidence": "INFERRED", "confidence_score": 0.85,
|
||||
"source_file": "Report.cs", "source_location": "L7"},
|
||||
{"source": "report_ireport_build", "target": "report_pdfreport_build",
|
||||
"relation": "dispatches_to", "confidence": "INFERRED", "confidence_score": 0.75,
|
||||
"source_file": "Report.cs", "source_location": "L2"},
|
||||
{"source": "report_ireport_build", "target": "report_csvreport_build",
|
||||
"relation": "dispatches_to", "confidence": "INFERRED", "confidence_score": 0.75,
|
||||
"source_file": "Report.cs", "source_location": "L3"},
|
||||
*extra_edges,
|
||||
],
|
||||
"hyperedges": [],
|
||||
}
|
||||
|
||||
|
||||
WEAK_DISPATCH = {
|
||||
"source": "report_ireport_build", "target": "report_pdfreport_build",
|
||||
"relation": "dispatches_to", "confidence": "AMBIGUOUS", "confidence_score": 0.4,
|
||||
"source_file": "notes.md", "source_location": "L12",
|
||||
}
|
||||
WEAK_EVIDENCE = {"confidence": "AMBIGUOUS", "confidence_score": 0.4,
|
||||
"source_file": "notes.md", "source_location": "L12"}
|
||||
|
||||
|
||||
def _dispatch(G):
|
||||
return edge_data(G, "report_ireport_build", "report_pdfreport_build")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("weak_first", [False, True])
|
||||
def test_weaker_duplicate_is_recorded_on_the_winner(weak_first):
|
||||
ext = _report_extraction([dict(WEAK_DISPATCH)])
|
||||
if weak_first:
|
||||
ext["edges"].insert(0, ext["edges"].pop())
|
||||
d = _dispatch(build_from_json(ext))
|
||||
assert d["confidence"] == "INFERRED"
|
||||
assert d["confidence_score"] == 0.75
|
||||
assert d["source_location"] == "L2"
|
||||
assert d["also_seen"] == [WEAK_EVIDENCE]
|
||||
|
||||
|
||||
def test_displaced_winner_is_recorded_and_its_score_does_not_leak():
|
||||
"""A stronger edge with no score replaces a scored INFERRED one."""
|
||||
strong = {"source": "report_ireport_build", "target": "report_pdfreport_build",
|
||||
"relation": "dispatches_to", "confidence": "EXTRACTED",
|
||||
"source_file": "Report.cs", "source_location": "L9"}
|
||||
d = _dispatch(build_from_json(_report_extraction([strong])))
|
||||
assert d["confidence"] == "EXTRACTED"
|
||||
assert d["source_location"] == "L9"
|
||||
assert "confidence_score" not in d
|
||||
assert d["also_seen"] == [{"confidence": "INFERRED", "confidence_score": 0.75,
|
||||
"source_file": "Report.cs", "source_location": "L2"}]
|
||||
|
||||
|
||||
def test_equal_confidence_second_site_is_recorded():
|
||||
other_site = {"source": "report_exporter_run", "target": "report_ireport_build",
|
||||
"relation": "calls", "confidence": "INFERRED", "confidence_score": 0.85,
|
||||
"source_file": "Report.cs", "source_location": "L9"}
|
||||
d = edge_data(build_from_json(_report_extraction([other_site])),
|
||||
"report_exporter_run", "report_ireport_build")
|
||||
sites = {d["source_location"], *(e["source_location"] for e in d["also_seen"])}
|
||||
assert sites == {"L7", "L9"}
|
||||
|
||||
|
||||
def test_identical_duplicate_adds_nothing():
|
||||
same = dict(_report_extraction()["edges"][1])
|
||||
d = _dispatch(build_from_json(_report_extraction([same])))
|
||||
assert "also_seen" not in d
|
||||
|
||||
|
||||
def test_rebuild_from_written_graph_is_idempotent():
|
||||
"""An update re-feeds graph.json links through the build with fresh edges."""
|
||||
G = build_from_json(_report_extraction([dict(WEAK_DISPATCH)]))
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
for link in data["links"]:
|
||||
link.pop("_src", None)
|
||||
link.pop("_tgt", None)
|
||||
again = _report_extraction([dict(WEAK_DISPATCH)])
|
||||
again["edges"] = data["links"] + again["edges"]
|
||||
assert _dispatch(build_from_json(again))["also_seen"] == [WEAK_EVIDENCE]
|
||||
|
||||
|
||||
def test_malformed_also_seen_on_disk_is_sanitized():
|
||||
edge = dict(_report_extraction()["edges"][1])
|
||||
edge["also_seen"] = ["junk", None, {"confidence": "AMBIGUOUS", "confidence_score": "nan",
|
||||
"source_location": ["L1"]}]
|
||||
ext = _report_extraction()
|
||||
ext["edges"][1] = edge
|
||||
assert _dispatch(build_from_json(ext))["also_seen"] == [{"confidence": "AMBIGUOUS"}]
|
||||
|
||||
|
||||
def _path_graph(tmp_path):
|
||||
G = build_from_json(_report_extraction([dict(WEAK_DISPATCH)]))
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(json_graph.node_link_data(G, edges="links")))
|
||||
return p, G
|
||||
|
||||
|
||||
def test_cli_path_surfaces_weakest_tag(monkeypatch, tmp_path, capsys):
|
||||
p, _ = _path_graph(tmp_path)
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(mainmod.sys, "argv", [
|
||||
"graphify", "path", "report_exporter_run", "report_pdfreport_build", "--graph", str(p)])
|
||||
mainmod.main()
|
||||
out = capsys.readouterr().out
|
||||
assert "--dispatches_to [AMBIGUOUS/INFERRED]-->" in out
|
||||
assert "--calls [INFERRED]-->" in out
|
||||
|
||||
|
||||
def test_mcp_path_surfaces_weakest_tag(tmp_path):
|
||||
_, G = _path_graph(tmp_path)
|
||||
out = _shortest_path_text(G, {"source": "report_exporter_run",
|
||||
"target": "report_pdfreport_build"})
|
||||
assert "--dispatches_to [AMBIGUOUS/INFERRED]-->" in out
|
||||
|
||||
|
||||
def test_report_cs_extraction_keeps_semantic_duplicate(tmp_path):
|
||||
"""End to end on the issue's repro: real C# AST edges + a weaker semantic duplicate."""
|
||||
pytest.importorskip("tree_sitter_c_sharp")
|
||||
from graphify.extract import extract
|
||||
|
||||
src = tmp_path / "Report.cs"
|
||||
src.write_text(REPORT_CS)
|
||||
ext = extract([src], cache_root=tmp_path)
|
||||
ext["edges"].append(dict(WEAK_DISPATCH))
|
||||
d = _dispatch(build_from_json(ext, root=tmp_path))
|
||||
assert d["confidence"] == "INFERRED"
|
||||
assert [e["confidence"] for e in d["also_seen"]] == ["AMBIGUOUS"]
|
||||
Reference in new issue
Block a user