Skip to content

Cross-language stub rewiring: unresolved base-class stub can bind to unrelated node in a different language #2207

Closed

Description

@nhan303i

Summary

_rewire_unique_stub_nodes in extract.py can silently rewire an unresolved-symbol "stub" node (e.g. an inheritance target with no local definition) onto a completely unrelated node in a different language, as long as the label happens to match and there's exactly one other "real" candidate anywhere in the whole corpus. This produces false cross-language edges and can turn an unrelated variable into an artificial "god node" bridging communities that have nothing to do with each other.

Repro

repo/
  backend/models.py
  frontend/widget.test.tsx

backend/models.py:

from sqlalchemy.orm import declarative_base

Base = declarative_base()  # not a `class` statement, so it's never registered as a "real" definition

class User(Base):
    __tablename__ = "users"

frontend/widget.test.tsx:

const base = { id: 1, name: "test" };

test("renders", () => {
  render(<Widget item={base} />);
});

Run:

from graphify.extract import extract
from pathlib import Path

result = extract([Path("backend/models.py"), Path("frontend/widget.test.tsx")], cache_root=Path("."))
print([e for e in result["edges"] if e["source"] == "backend_models_user" and e["relation"] == "inherits"])

Expected: an inherits edge from User to some Python-only placeholder for the unresolved Base symbol (or at minimum, not to a TS variable).

Actual:

[{'source': 'backend_models_user', 'target': 'frontend_widget_test_base', 'relation': 'inherits', ...}]

User now appears to "inherit" from a local test fixture object in a .tsx file. Extracting backend/models.py alone (without the .tsx file present) correctly produces target base (a bare, unresolved placeholder) — the bug only manifests when both files are extracted together, because _rewire_unique_stub_nodes runs once over the whole corpus.

On a real ~530-file mixed Python/TypeScript monolith, this exact pattern turned into a reported "god node" / cross-community bridge: ~90 unrelated SQLAlchemy ORM model classes all appeared to inherit from one frontend Jest/Vitest test's local const base = {...} fixture, purely because that fixture was the only other node in the whole corpus with the label base and Base (SQLAlchemy's declarative_base() return value) has no class statement anywhere for the extractor to resolve it against.

Root cause

extract.py, _rewire_unique_stub_nodes (around L7070 as of graphifyy 0.8.38):

def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
    """Map unresolved no-source stubs to a unique real definition with the same label."""
    real_by_label: dict[str, list[dict]] = {}
    stubs: list[dict] = []

    for node in nodes:
        key = _node_label_key(node)
        if not key:
            continue
        if node.get("source_file"):
            if _is_type_like_definition(node):
                real_by_label.setdefault(key, []).append(node)
            continue
        stubs.append(node)

    remap: dict[str, str] = {}
    drop_ids: set[str] = set()
    for stub in stubs:
        stub_id = str(stub.get("id", ""))
        if not stub_id:
            continue
        candidates = real_by_label.get(_node_label_key(stub), [])
        if len(candidates) != 1:
            continue
        target_id = candidates[0].get("id")
        if isinstance(target_id, str) and target_id and target_id != stub_id:
            remap[stub_id] = target_id
            drop_ids.add(stub_id)
    ...

Stub nodes (created e.g. around L2300-2320 for Python's class X(Base): when Base has no local class definition) carry source_file: "" and no language tag at all. The rewire step matches candidates purely by normalized label (_node_label_key) and _is_type_like_definition (which only checks the label doesn't look like a call/member access — it happily accepts a plain JS/TS const variable declaration). There is no check that the stub and the candidate come from the same language or even related file types. If exactly one same-labeled "real" node exists anywhere in the whole multi-language corpus, it wins by default, regardless of language.

This is easy to trigger in any polyglot repo where a common short identifier (Base, Client, Config, Handler, etc.) is:

  1. assigned via a factory call rather than a class/interface statement in one language (so it never becomes a "real" _is_type_like_definition node), and
  2. also happens to be used as a local variable/const name in a completely unrelated file in another language.

Suggested fix

Infer the stub's language from the edges that reference it (each edge carries source_file, i.e. the file that created the reference), and only allow rewiring onto a candidate from the same "extension family". JS/TS variants (.ts/.tsx/.js/.jsx/.mjs/.cjs) can stay grouped since they legitimately share one class hierarchy; everything else defaults to its own singleton family so unrelated languages never match:

_STUB_EXT_FAMILIES: dict[str, str] = {
    ".ts": "js", ".tsx": "js", ".js": "js", ".jsx": "js", ".mjs": "js", ".cjs": "js",
}


def _stub_ext_family(suffix: str) -> str:
    return _STUB_EXT_FAMILIES.get(suffix.lower(), suffix.lower())


def _rewire_unique_stub_nodes(nodes: list[dict], edges: list[dict]) -> None:
    """Map unresolved no-source stubs to a unique real definition with the same label.

    A stub carries no source_file of its own, so its language is inferred from
    the edges that reference it (each edge's source_file is the file that
    created the reference). Candidates are restricted to that same language
    family — without this, an unresolved Python base class (e.g. `class
    User(Base)` where `Base` isn't locally defined) can be rewired onto an
    unrelated same-named symbol in a completely different language, such as a
    local variable in a JS/TS test file.
    """
    real_by_label: dict[str, list[dict]] = {}
    stubs: list[dict] = []

    for node in nodes:
        key = _node_label_key(node)
        if not key:
            continue
        if node.get("source_file"):
            if _is_type_like_definition(node):
                real_by_label.setdefault(key, []).append(node)
            continue
        stubs.append(node)

    if not stubs:
        return

    stub_ids = {str(s.get("id", "")) for s in stubs if s.get("id")}
    stub_origin_families: dict[str, set[str]] = {}
    for edge in edges:
        sf = edge.get("source_file")
        if not sf:
            continue
        family = _stub_ext_family(Path(sf).suffix)
        src, tgt = str(edge.get("source", "")), str(edge.get("target", ""))
        if src in stub_ids:
            stub_origin_families.setdefault(src, set()).add(family)
        if tgt in stub_ids:
            stub_origin_families.setdefault(tgt, set()).add(family)

    remap: dict[str, str] = {}
    drop_ids: set[str] = set()
    for stub in stubs:
        stub_id = str(stub.get("id", ""))
        if not stub_id:
            continue
        candidates = real_by_label.get(_node_label_key(stub), [])
        origin_families = stub_origin_families.get(stub_id)
        if origin_families:
            candidates = [
                c for c in candidates
                if _stub_ext_family(Path(c.get("source_file", "")).suffix) in origin_families
            ]
        if len(candidates) != 1:
            continue
        target_id = candidates[0].get("id")
        if isinstance(target_id, str) and target_id and target_id != stub_id:
            remap[stub_id] = target_id
            drop_ids.add(stub_id)
    ...  # rest unchanged

I patched my local install with exactly this and confirmed it resolves the repro (re-running extract() on the two files above now correctly leaves User's inherits edge pointing at the bare, unresolved base placeholder instead of the .tsx test fixture), without affecting legitimate same-language stub resolution.

Happy to open a PR with this change plus a regression test if that's useful.

Environment

  • graphifyy version: 0.8.38
  • Python 3.12
  • Triggered via the AST-only (--update, code-only fast path) extraction flow on a mixed Python/TypeScript monolith (~530 files)

Activity

  1. irhamumam17 commented on Jul 26, 2026

    @irhamumam17

    Confirming a second real-world occurrence of this exact bug, different language pair: PHP ↔ TSX.

    Repro (PHP/Laravel + React monolith, ~2500 files)

    app/Console/Commands/RetryDeadLetters.php:

    use Illuminate\Console\Command;
    
    class RetryDeadLetters extends Command
    {
        public function handle(): int
        {
            ...
            return $this->retryEntry($entry) ? Command::SUCCESS : Command::FAILURE;
        }
    }

    resources/js/components/ui/command.tsx (a cmdk-style combobox component):

    export function Command({ ... }) { ... }

    Illuminate\Console\Command is a vendor base class imported via use, with no local class Command definition anywhere in the repo — so the Command::SUCCESS/Command::FAILURE constant references become unresolved stubs, same shape as the Base case in the original report. The only other node in the whole corpus with label Command is the unrelated React component.

    Result — 4 separate Artisan commands' handle() methods all produced references_constant edges pointed at the frontend component instead of a PHP-side placeholder:

    {"relation":"references_constant","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"app/Console/Commands/CleanupRateLimitLogs.php","source_location":"L45","source":"app_console_commands_cleanupratelimitlogs_cleanupratelimitlogs_handle","target":"resources_js_components_ui_command_command"}
    {"relation":"references_constant","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"app/Console/Commands/NeoFeeder/NeoFeederSyncReferensiCommand.php","source_location":"L209","source":"app_console_commands_neofeeder_neofeedersyncreferensicommand_neofeedersyncreferensicommand_handle","target":"resources_js_components_ui_command_command"}
    {"relation":"references_constant","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"app/Console/Commands/NeoFeeder/NeoFeederTestCommand.php","source_location":"L44","source":"app_console_commands_neofeeder_neofeedertestcommand_neofeedertestcommand_handle","target":"resources_js_components_ui_command_command"}
    {"relation":"references_constant","confidence":"EXTRACTED","confidence_score":1.0,"source_file":"app/Console/Commands/RetryDeadLetters.php","source_location":"L44","source":"app_console_commands_retrydeadletters_retrydeadletters_handle","target":"resources_js_components_ui_command_command"}

    Downstream effect on our corpus matched the "god node" symptom described above: Command (the React component) surfaced in suggest_questions()/betweenness analysis as a high-betweenness (0.316) bridge supposedly connecting 5 unrelated communities (a UI component community + 4 separate backend command-handler communities) — purely an artifact of this mislabeled rewire, not a real architectural relationship.

    Notably a correct stub for the PHP base class does exist elsewhere in our graph (illuminate_console_command, no source_file), so the extractor clearly has the right building block — it's specifically the per-reference references_constant stub created inline that gets swept into _rewire_unique_stub_nodes and rewired cross-language.

    • graphifyy version: 0.9.x (whatever pip install graphifyy resolved to on 2026-07-26)
    • Triggered via --update incremental AST-only extraction on changed .php files, with an unrelated .tsx file elsewhere in the same corpus supplying the sole same-labeled candidate

    The extension-family fix proposed above (grouping by inferred language via the referencing edge's source_file) would resolve this case too, since .php and .tsx fall into different families under that scheme.

  2. ayushcodes10 commented on Sep 16, 2026

    @ayushcodes10
    Contributor

    Independently reproduced this on current v8 (post 0.9.63), and it is still live — but the fix isn't as simple as it first looks, because of a direct conflict with an existing, intentional test.

    Reproduction on current code

    Both variants from this issue still reproduce, with exact label case (the _rewire_unique_stub_nodes type path matches case sensitively, so Base vs base alone would NOT reproduce it — that part got fixed incidentally by #1581 — the case has to match exactly):

    Variant A, a plain object literal (matches the original repro shape):

    # backend/models.py
    Base = declarative_base()
    class User(Base): ...
    // frontend/widget.test.tsx
    const Base = { id: 1, name: "test" };

    Result: User's inherits edge still resolves to frontend_widget_test_base (the TS const), not a bare placeholder.

    Variant B, a genuine TS class (so it's unambiguously in real_by_label, not just the loose "type-like" fallback):

    export class Base { id: number = 1; }

    Same result — User inherits from the TS Base class.

    Why the proposed language-family fix can't be a blanket gate

    tests/test_extract.py::test_extract_rewires_unique_inheritance_stub_to_real_definition deliberately exercises the exact same shape as Variant B, just with the roles reversed:

    # interfaces.py
    class BookStore: pass
    // services/BookStore.cs
    class SqliteBookStore : BookStore { }

    This asserts the C# stub for BookStore should rewire onto the Python BookStore class — i.e. cross-language single-candidate rewiring is intentional, tested behavior for a polyglot-interface convention (define an interface/base in one language, "implement" it by same name in another). Gating real_by_label by language family (as this issue's suggested fix does) blocks that test's case exactly as much as it blocks the god-node cases — there's no structural difference between "one C# class subclasses one same-named Python class, intentionally" and "one Python class subclasses one same-named TS class, coincidentally." Both are: stub has no same-language real definition, exactly one real definition exists anywhere, different language. The graph alone can't tell intent from coincidence here.

    A heuristic that might actually separate them

    The real-world reports (this issue's PHP follow-up, and the original) both involve a stub referenced by many same-language call sites (~90 SQLAlchemy models via Base, 4 Artisan commands via Command::), while the legitimate BookStore convention is a 1:1 bridge (one implementation, one interface). A guard like "only allow cross-language type rewiring when the stub has at most one referencing edge corpus-wide, otherwise require a same-language real definition" would plausibly fix both real-world cases without touching the existing test — but it's an unvalidated heuristic, changes intentional behavior for an edge case, and needs a maintainer call on whether "referenced once" is the right bar (a real BookStore-style interface could legitimately have more than one implementer).

    Flagging this for maintainer input on the intended precedence rather than opening a PR that either only half-fixes it or risks regressing the documented convention. Happy to implement the referrer-count heuristic (with a regression test covering both this issue's cases and the existing BookStore/SqliteBookStore test) if that's the desired direction.

  3. SrijanSriv commented on Oct 4, 2026

    @SrijanSriv
    Contributor

    still happens on 0.9.75. User(Base) gets tied to a Base in a tsx file, and Command::SUCCESS gets tied to a TS Command class.
    i want that rewire to stay in one language. the BookStore test currently wants the cross-language bind, so i would change it to keep the stub. a same-language match still rewires. working on that
    cc: @safishamsi

  4. added a commit that references this issue on Oct 4, 2026
    ac6ab9f
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