Repository navigation
Description
Summary
_rewire_unique_stub_nodes() can turn a valid edge to an unresolved sourceless stub into a false self-loop when the unique same-label candidate is the edge's other endpoint.
This currently happens in at least two independent AST extraction paths:
- A qualified Python decorator whose attribute name equals the decorated function name, such as
@app.list_tools()ondef list_tools(). - A Kotlin anonymous object extending an out-of-corpus class, because the anonymous-object node is labeled after its first supertype.
Both extractors correctly avoid a self-loop at emission time because the unresolved stub and owner are still distinct then. The later corpus-wide stub rewiring collapses the stub onto the owner and creates the loop.
Environment
graphifyy==0.9.32from PyPI- Python 3.12.10
- macOS arm64
- Reproduced through
graphify.extract.extract(..., parallel=False)using only structural/AST extraction - Also present on the current
v8branch at commit00efd6e7969837ae4a9f11d8d504dcd3b20b09df
Minimal reproduction
decorated.py:
class App:
pass
app = App()
@app.list_tools()
async def list_tools():
return []Anonymous.kt:
package demo
import library.ExternalBase
class Factory {
fun make() = object : ExternalBase() {}
}Run:
from pathlib import Path
from graphify.extract import extract
paths = [Path("decorated.py"), Path("Anonymous.kt")]
result = extract(paths, cache_root=Path("."), parallel=False)
for edge in result["edges"]:
if edge.get("source") == edge.get("target"):
print(edge)Actual result
{
"source": "decorated_list_tools",
"target": "decorated_list_tools",
"relation": "references",
"source_file": "decorated.py",
"source_location": "L8",
"context": "decorator",
"_origin": "ast",
}
{
"source": "anonymous_factory_make_object_externalbase_l6",
"target": "anonymous_factory_make_object_externalbase_l6",
"relation": "inherits",
"source_file": "Anonymous.kt",
"source_location": "L6",
"_origin": "ast",
}The complete repro produces 7 nodes, 7 edges, and exactly these 2 self-loop edges.
Expected result
- No remap-created self-loops.
list_tools()should retain areferencesedge to an unresolved decorator stub (or eventually a correctly receiver-resolvedapp.list_toolstarget), not to itself.- The anonymous object should retain an
inheritsedge to an unresolvedExternalBasestub, not to itself. - Existing self-loops already present before rewiring should remain visible to diagnostics; this fix should target only loops introduced by this remap.
Real-world occurrence
After upgrading and rebuilding 30 repositories with 0.9.32, graphify.diagnostics.diagnose_file() found three instances of this exact shape:
- Two Python
referencesself-loops from MCP registration decorators:@app.list_tools()/def list_tools()and@app.call_tool()/def call_tool(). - One Kotlin
inheritsself-loop fromobject : DefaultReactActivityDelegate(...) {}in a React Native Android activity.
There were no dangling endpoints, missing endpoints, or duplicate edges in those graphs. These three loops were the only remaining integrity warnings.
Root cause
Python decorator path
The Python decorated_definition branch in extractors/engine.py obtains only the attribute tail from a qualified decorator (@app.list_tools() becomes list_tools), creates/uses a sourceless stub through ensure_named_node(), and emits:
decorated_list_tools --references(context=decorator)--> list_tools_stub
The emission-time target != owner_nid guard passes because those IDs are distinct at that point.
Later, _rewire_unique_stub_nodes() sees one top-level function candidate with the same normalized label (list_tools()), rewires list_tools_stub to decorated_list_tools, and produces:
decorated_list_tools --references--> decorated_list_tools
Kotlin anonymous-object path
The anonymous-object implementation added for #2347 intentionally labels the object node after its first supertype:
obj_label = lit_bases[0][0] # ExternalBaseThe inheritance edge initially targets a separate sourceless ExternalBase stub. Because the anonymous object is now the only sourced type-like node labeled ExternalBase, _rewire_unique_stub_nodes() selects the object itself as the unique candidate and turns the edge into:
anonymous_object_ExternalBase --inherits--> anonymous_object_ExternalBase
The common failure is therefore not in the individual emission guards. It is the later candidate selection in _rewire_unique_stub_nodes().
Suggested fix
Treat a same-label candidate as unsafe when it is already an incident neighbor of the stub being considered. Resolving the stub to that neighbor necessarily collapses at least one previously non-self edge into a self-loop.
A conservative guard can be built while the function already scans edges for stub provenance:
stub_neighbors: dict[str, set[str]] = {}
for edge in edges:
source = edge.get("source")
target = edge.get("target")
if source in stub_ids and isinstance(target, str):
stub_neighbors.setdefault(str(source), set()).add(target)
if target in stub_ids and isinstance(source, str):
stub_neighbors.setdefault(str(target), set()).add(source)Then, before adding the remap:
target_id = candidates[0].get("id")
if (
isinstance(target_id, str)
and target_id
and target_id != stub_id
and target_id not in stub_neighbors.get(stub_id, set())
):
remap[stub_id] = target_idThis leaves the relationship attached to the unresolved stub instead of asserting a false self-relationship. It also preserves all other edges incident to that stub. That is safer than deleting the resulting edge after remapping, particularly for inherits, where the unresolved base-class relationship remains useful and truthful.
As a defense-in-depth invariant, the remap loop could additionally detect any non-self edge that becomes self-referential after endpoint replacement and keep that edge on its original stub. build.py already has analogous logic for self-loops created by _doc_remap, although dropping is appropriate there because that doc-twin edge is redundant; stub relationships generally should be retained.
Regression tests
Please add both language-level reproductions plus one focused unit test for _rewire_unique_stub_nodes():
-
Python qualified decorator collision
- Extract
@app.list_tools()decoratingdef list_tools(). - Assert no edge has
source == target. - Assert the
references/decoratoredge still exists and targets a sourceless stub.
- Extract
-
Kotlin anonymous-object supertype collision
- Extract
object : ExternalBase() {}without an in-corpusExternalBasedefinition. - Assert no edge has
source == target. - Assert the anonymous object still inherits from the sourceless
ExternalBasestub.
- Extract
-
Generic rewiring invariant
- Given
owner -> stub, whereowneris the only same-label sourced candidate, assert the stub is not remapped toowner. - Keep existing positive tests proving that unrelated cross-file stubs still rewire to unique real definitions.
- Given
Related issues
- Python: applying a decorator creates no edge —
affected <decorator>returns "No affected nodes found" for every function it wraps #2154 introduced Python decorator dependency edges; this is a follow-up collision in their later stub-rewire step. - Kotlin: members of anonymous objects (object_literal) are not extracted #2347 introduced Kotlin anonymous-object extraction; this is a follow-up interaction between the object label and stub rewiring.
- Cross-language stub rewiring: unresolved base-class stub can bind to unrelated node in a different language #2207 is related to
_rewire_unique_stub_nodes(), but its language-family guard would not fix this issue: in both repros the stub and incorrect candidate are in the same language. The distinguishing signal here is that the candidate is already the stub's opposite edge endpoint. - Cross-module references to functions land on a name-only stub node — _rewire_unique_stub_nodes excludes function labels #1781 widened stub rewiring to unique top-level function definitions, which is why the Python decorator case can now bind to the decorated function itself.
Activity