Skip to content

_rewire_unique_stub_nodes creates false self-loops for qualified decorators and Kotlin anonymous objects #2374

Open

Description

@Endogen

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:

  1. A qualified Python decorator whose attribute name equals the decorated function name, such as @app.list_tools() on def list_tools().
  2. 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.32 from PyPI
  • Python 3.12.10
  • macOS arm64
  • Reproduced through graphify.extract.extract(..., parallel=False) using only structural/AST extraction
  • Also present on the current v8 branch at commit 00efd6e7969837ae4a9f11d8d504dcd3b20b09df

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 a references edge to an unresolved decorator stub (or eventually a correctly receiver-resolved app.list_tools target), not to itself.
  • The anonymous object should retain an inherits edge to an unresolved ExternalBase stub, 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 references self-loops from MCP registration decorators: @app.list_tools() / def list_tools() and @app.call_tool() / def call_tool().
  • One Kotlin inherits self-loop from object : 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]  # ExternalBase

The 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_id

This 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():

  1. Python qualified decorator collision

    • Extract @app.list_tools() decorating def list_tools().
    • Assert no edge has source == target.
    • Assert the references/decorator edge still exists and targets a sourceless stub.
  2. Kotlin anonymous-object supertype collision

    • Extract object : ExternalBase() {} without an in-corpus ExternalBase definition.
    • Assert no edge has source == target.
    • Assert the anonymous object still inherits from the sourceless ExternalBase stub.
  3. Generic rewiring invariant

    • Given owner -> stub, where owner is the only same-label sourced candidate, assert the stub is not remapped to owner.
    • Keep existing positive tests proving that unrelated cross-file stubs still rewire to unique real definitions.

Related issues

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions