fix(watch): preserve saved semantic evidence on AST id collisions

(cherry picked from commit 6e0de8f9f2)
This commit is contained in:
Andre Brait authored and safishamsi committed 2026-11-02 19:03:50 +00:00
1 parent 7566615de3
commit 19f865361d
4 files changed
+203 -8

No files matched your search

+1
View File
@@ -4,6 +4,7 @@ Full release notes with details on each version: [GitHub Releases](https://githu
## 0.9.101 (unreleased)
- Fix: **watch** AST-only updates preserve cross-file semantic evidence whose node id collides with a code definition. Semantic nodes and their document-owned links use the existing citing-file namespace, keeping both the code definition and semantic provenance in `graph.json`, including with `--no-cluster`. Fresh AST facts remain authoritative for same-source ids; full-build deduplication is unchanged.
- Fix: **python** a bare call inside a method (`do_thing()`) no longer wrongly self-binds to a same-named method on the class; it resolves to the imported or module-level function it actually names, and a bare call with no such target emits no edge (#4933, thanks @nothariharan).
- Fix: **python** imports resolve across PEP 420 namespace packages split over multiple `src/` roots (no `__init__.py`), while a module ambiguously provided by two roots stays unresolved and loose/stdlib-named modules are left alone (#4929, thanks @nothariharan).
- Fix: **go** a method value reached through a receiver field (`m.UseMiddleware(hs.handler.Middleware)`) is linked as an `indirect_call`, extending the method-value-as-argument handling to field chains rooted at the method's own receiver (#1566, #4931, thanks @nothariharan).
+35 -4
View File
@@ -973,9 +973,9 @@ def _is_reference_stub(node: dict) -> bool:
def _namespace_reference_stub_collisions(
nodes: list[dict], edges: list[dict], hyperedges: list[dict] | None,
root: Path | None,
root: Path | None, *, preserve_saved_semantics: bool = False,
) -> tuple[list[dict], list[dict]]:
"""Keep marked cross-document reference stubs distinct (#4738).
"""Keep semantic references distinct from another file's defining node.
Semantic extraction marks a node it emitted solely for a referenced entity
with ``metadata.graphify_reference_stub``. Preserve every marked node under
@@ -986,6 +986,10 @@ def _namespace_reference_stub_collisions(
The marker distinguishes reference stubs from two independent documents
that happen to share an ID. Path specificity cannot make that distinction:
it regresses genuine nested-path definitions.
With preserve_saved_semantics, AST-only updates retain saved semantic
evidence even when it predates the reference-stub marker. A scan root is
required to distinguish source files; full builds keep their definer rules.
"""
def key(source_file: object) -> str:
return _rank_path(source_file, root) if isinstance(source_file, str) else ""
@@ -1001,7 +1005,21 @@ def _namespace_reference_stub_collisions(
for nid, members in by_id.items():
if len({key(node.get("source_file")) for node in members}) < 2:
continue
stubs = [node for node in members if _is_reference_stub(node)]
ast_sources = {
key(node.get("source_file")) for node in members
if node.get("_origin") == "ast"
}
stubs = [
node for node in members
if _is_reference_stub(node) or (
preserve_saved_semantics
and root is not None
and node.get("_origin") == "semantic"
and key(node.get("source_file"))
and ast_sources
and key(node.get("source_file")) not in ast_sources
)
]
if not stubs:
continue
source_keys = {key(node.get("source_file")) for node in stubs}
@@ -1017,7 +1035,18 @@ def _namespace_reference_stub_collisions(
if len(set(candidates.values())) != len(candidates):
continue
if any(candidate in taken for candidate in candidates.values()):
continue
if not preserve_saved_semantics:
continue
reserved = taken | set(candidates.values())
for source_key in sorted(candidates):
base = candidates[source_key]
candidate = base
suffix = 2
while candidate in taken or (candidate != base and candidate in reserved):
candidate = f"{base}__{suffix}"
suffix += 1
candidates[source_key] = candidate
reserved.add(candidate)
renames.update(((nid, source_key), candidate)
for source_key, candidate in candidates.items())
taken.update(candidates.values())
@@ -1034,6 +1063,8 @@ def _namespace_reference_stub_collisions(
for item in collection:
if not isinstance(item, dict):
continue
if preserve_saved_semantics and item.get("_origin") == "ast":
continue
source_key = key(item.get("source_file"))
for endpoint in ("source", "target"):
value = item.get(endpoint)
+20 -4
View File
@@ -1298,7 +1298,8 @@ def _reconcile_existing_graph(
preserved_nodes = [
node
for node in existing.get("nodes", [])
if node["id"] not in new_ast_ids
if (node["id"] not in new_ast_ids
or (node.get("_origin") == "semantic" and node.get("source_file")))
and not (
_is_ast_tier(node)
and (
@@ -1423,10 +1424,25 @@ def _reconcile_existing_graph(
for item in preserved_nodes + preserved_edges + preserved_hyperedges:
source_paths.rebase_preserved(item)
from graphify.dedup import _namespace_reference_stub_collisions
merged_hyperedges = result.get("hyperedges", []) + preserved_hyperedges
merged_nodes, merged_edges = _namespace_reference_stub_collisions(
result["nodes"] + preserved_nodes,
result["edges"] + preserved_edges,
merged_hyperedges,
project_root,
preserve_saved_semantics=True,
)
# Unattributed or same-source copies must not overwrite fresh AST facts.
merged_nodes = [
node for node in merged_nodes
if node["id"] not in new_ast_ids or _is_ast_tier(node)
]
return {
"nodes": result["nodes"] + preserved_nodes,
"edges": result["edges"] + preserved_edges,
"hyperedges": result.get("hyperedges", []) + preserved_hyperedges,
"nodes": merged_nodes,
"edges": merged_edges,
"hyperedges": merged_hyperedges,
"input_tokens": 0,
"output_tokens": 0,
}, existing_graph_data
+147
View File
@@ -140,3 +140,150 @@ def test_a_stamped_document_survives_the_code_files_re_extraction(tmp_path):
stamped = build_merge([re_extraction], graph_with(_line_located_doc_node(_origin="semantic")))
assert "docs_guide_deploy" in stamped.nodes, "the stamped document node must survive"
@pytest.mark.parametrize("no_cluster", [False, True])
def test_update_keeps_semantic_evidence_when_an_ast_id_collides(tmp_path, no_cluster):
from graphify.watch import _rebuild_code
(tmp_path / "sample.py").write_text("def answer():\n return 42\n", encoding="utf-8")
(tmp_path / "design.md").write_text("# Design\nA stable protocol.\n", encoding="utf-8")
out = tmp_path / "graphify-out"
out.mkdir()
graph = out / "graph.json"
graph.write_text(json.dumps({
"nodes": [
{"id": "sample", "label": "Sample protocol", "file_type": "concept",
"source_file": "design.md", "source_location": None, "_origin": "semantic"},
{"id": "sample_answer", "label": "answer()", "file_type": "code",
"source_file": "sample.py", "source_location": "L1", "_origin": "ast"},
],
"links": [
{"source": "sample", "target": "sample_answer", "relation": "motivates",
"source_file": "design.md", "_origin": "semantic",
"confidence": "INFERRED", "confidence_score": 0.9},
],
}), encoding="utf-8")
assert _rebuild_code(tmp_path, no_cluster=no_cluster)
rebuilt = json.loads(graph.read_text(encoding="utf-8"))
evidence = next(n for n in rebuilt["nodes"] if n["label"] == "Sample protocol")
assert evidence["_origin"] == "semantic"
assert evidence["source_file"] == "design.md"
assert any(n["id"] == "sample" and n["source_file"] == "sample.py"
for n in rebuilt["nodes"])
assert any(e["source"] == evidence["id"] and e["target"] == "sample_answer"
and e["relation"] == "motivates" and e["_origin"] == "semantic"
for e in rebuilt["links"])
assert _rebuild_code(tmp_path, no_cluster=no_cluster)
assert json.loads(graph.read_text(encoding="utf-8")) == rebuilt
@pytest.mark.parametrize("no_cluster", [False, True])
@pytest.mark.parametrize("prior", [
{"id": "sample_answer", "label": "Old rationale", "file_type": "concept",
"source_file": "sample.py", "source_location": None, "_origin": "semantic"},
{"id": "sample", "label": "sample", "file_type": "concept", "source_file": ""},
{"id": "sample_answer", "label": "Orphan note", "file_type": "concept",
"source_file": "", "_origin": "semantic"},
], ids=["same-source", "external-stub", "sourceless"])
def test_unattributed_semantics_never_replace_a_fresh_ast_definition(tmp_path, no_cluster, prior):
from graphify.watch import _rebuild_code
(tmp_path / "sample.py").write_text("def answer():\n return 42\n", encoding="utf-8")
out = tmp_path / "graphify-out"
out.mkdir()
graph = out / "graph.json"
graph.write_text(json.dumps({
"nodes": [prior],
"links": [{"source": "sample_answer", "target": "sample", "relation": "imports",
"source_file": "sample.py", "_origin": "ast", "confidence": "EXTRACTED"}],
}), encoding="utf-8")
assert _rebuild_code(tmp_path, no_cluster=no_cluster)
rebuilt = json.loads(graph.read_text(encoding="utf-8"))
node = next(n for n in rebuilt["nodes"] if n["id"] == prior["id"])
assert node["_origin"] == "ast"
assert node["source_file"] == "sample.py"
assert node["source_location"] == "L1"
assert node["label"] == ("sample.py" if prior["id"] == "sample" else "answer()")
@pytest.mark.parametrize("no_cluster", [False, True])
def test_update_keeps_both_semantic_nodes_when_the_reference_namespace_is_taken(tmp_path, no_cluster):
from graphify.watch import _rebuild_code
(tmp_path / "sample.py").write_text("def answer():\n return 42\n", encoding="utf-8")
for name in ("design.md", "notes.md"):
(tmp_path / name).write_text("# Evidence\nA stable protocol.\n", encoding="utf-8")
out = tmp_path / "graphify-out"
out.mkdir()
graph = out / "graph.json"
graph.write_text(json.dumps({
"nodes": [
{"id": "sample", "label": "Sample protocol", "file_type": "concept",
"source_file": "design.md", "_origin": "semantic"},
{"id": "design__ref__sample", "label": "Independent note", "file_type": "concept",
"source_file": "notes.md", "_origin": "semantic"},
{"id": "sample_answer", "label": "answer()", "file_type": "code",
"source_file": "sample.py", "source_location": "L1", "_origin": "ast"},
],
"links": [{"source": "sample", "target": "sample_answer", "relation": "motivates",
"source_file": "design.md", "_origin": "semantic",
"confidence": "INFERRED", "confidence_score": 0.9}],
}), encoding="utf-8")
assert _rebuild_code(tmp_path, no_cluster=no_cluster)
rebuilt = json.loads(graph.read_text(encoding="utf-8"))
protocol = next(n for n in rebuilt["nodes"] if n["label"] == "Sample protocol")
note = next(n for n in rebuilt["nodes"] if n["label"] == "Independent note")
assert protocol["id"] != note["id"]
assert any(n["id"] == "sample" and n["source_file"] == "sample.py"
and n["_origin"] == "ast" for n in rebuilt["nodes"])
assert any(e["source"] == protocol["id"] and e["target"] == "sample_answer"
and e["relation"] == "motivates" and e["confidence_score"] == 0.9
for e in rebuilt["links"])
@pytest.mark.parametrize("no_cluster", [False, True])
def test_semantic_alias_keeps_authored_ast_links_and_document_provenance(tmp_path, no_cluster):
from graphify.watch import _rebuild_code
(tmp_path / "sample.py").write_text("def answer():\n return 42\n", encoding="utf-8")
(tmp_path / "design.md").write_text("# Design\nA stable protocol.\n", encoding="utf-8")
out = tmp_path / "graphify-out"
out.mkdir()
graph = out / "graph.json"
graph.write_text(json.dumps({
"nodes": [
{"id": "sample", "label": "Sample protocol", "file_type": "concept",
"source_file": "design.md", "_origin": "semantic",
"attributes": {"document_version": "v1"}},
{"id": "design", "label": "design.md", "file_type": "document",
"source_file": "design.md", "source_location": "L1", "_origin": "ast"},
{"id": "sample_answer", "label": "answer()", "file_type": "code",
"source_file": "sample.py", "source_location": "L1", "_origin": "ast"},
],
"links": [
{"source": "design", "target": "sample", "relation": "references",
"source_file": "design.md", "_origin": "ast", "confidence": "EXTRACTED"},
{"source": "sample", "target": "sample_answer", "relation": "motivates",
"source_file": "design.md", "_origin": "semantic",
"confidence": "INFERRED", "confidence_score": 0.9},
],
"hyperedges": [{"id": "protocol", "nodes": ["design", "sample", "sample_answer"],
"source_file": "design.md", "relation": "explains"}],
}), encoding="utf-8")
assert _rebuild_code(tmp_path, no_cluster=no_cluster)
rebuilt = json.loads(graph.read_text(encoding="utf-8"))
protocol = next(n for n in rebuilt["nodes"] if n["label"] == "Sample protocol")
assert protocol["attributes"]["document_version"] == "v1"
assert any(e["source"] == "design" and e["target"] == "sample"
and e["_origin"] == "ast" for e in rebuilt["links"])
semantic = next(e for e in rebuilt["links"] if e["relation"] == "motivates")
assert semantic["source"] == protocol["id"]
assert semantic["confidence"] == "INFERRED"
assert semantic["confidence_score"] == 0.9
assert set(rebuilt["hyperedges"][0]["nodes"]) == {"design", protocol["id"], "sample_answer"}