Skip to content

Kotlin: _KOTLIN_CONFIG declares node type import_header, bundled grammar emits import — every Kotlin imports edge is silently dropped (45% -> 95% dep recall with a 2-line fix) #2526

Closed

Description

@spaceBrownie

Environment

  • graphify 0.9.35 (PyPI graphifyy, uv tool install), macOS 15, Python 3.12
  • Bundled grammar: tree_sitter_kotlin as shipped in the 0.9.35 wheel
  • Reproduced via graphify update . and by parsing directly with the bundled grammar

Summary

_KOTLIN_CONFIG declares import_types=frozenset({"import_header"}), but the bundled
tree_sitter_kotlin grammar emits node type import (with a qualified_identifier
child). There is no import_header node anywhere in a parsed Kotlin file, so
_import_kotlin is never invoked and zero imports edges are produced for Kotlin,
silently. _import_kotlin's own fallback would not save it either: it looks for an
identifier child, and the grammar produces qualified_identifier.

This is the Kotlin analogue of #2280 (Python imports dropped) and #2329 (Dart imports
never resolved), but with total loss rather than partial: not a single Kotlin import edge
survives.

Effect on a real repo (Kotlin/Spring modular monolith, 416 Kotlin files): a class whose
only link to its dependency is a constructor-injected property — the dominant shape in
Spring code — ends up completely orphaned in the graph. affected is blind, path
returns "no directed path" for flows that plainly exist, and query traversal cannot
reach the right files.

Reproducer

demo/Money.kt

package demo.model

data class Money(val amount: Long)

demo/Ledger.kt

package demo.service

import demo.model.Money

class Ledger(private val opening: Money)

Control, same shape in TypeScript — demo/Wallet.ts

export class Wallet {}

demo/App.ts

import { Wallet } from "./Wallet";
export const w = new Wallet();
graphify update .

Current behavior (0.9.35)

TypeScript resolves both edges; Kotlin produces none.

EDGES:
  imports_from : App.ts   -> Wallet.ts     <-- TS file-level, correct
  imports      : App.ts   -> Wallet        <-- TS symbol-level, correct
  contains     : Money.kt -> Money
  contains     : Ledger.kt -> Ledger

Ledger.kt has exactly one edge — contains to its own class. There is no edge of any
kind between Ledger.kt and Money.kt, so Money is unreachable from Ledger at any
depth.

Confirming the node type directly with the bundled grammar:

import tree_sitter, tree_sitter_kotlin
lang = tree_sitter.Language(tree_sitter_kotlin.language())
tree = tree_sitter.Parser(lang).parse(open("demo/Ledger.kt","rb").read())
print([c.type for c in tree.root_node.children])
# ['package_header', 'import', 'class_declaration']
#                    ^^^^^^^^ not 'import_header'

imp = tree.root_node.children[1]
print(imp.child_by_field_name("path"), [c.type for c in imp.children])
# None ['import', 'qualified_identifier']
#  ^^^^ no 'path' field either, so the primary branch of _import_kotlin
#       would also miss if the type matched

import_header occurs 0 times in any file of the corpus.

Expected behavior

Kotlin emits imports edges the same way TypeScript, Java, and Scala do.

Suggested fix

Two lines, mirroring the grammar-version tolerance the config already documents for
identifiers:

 _KOTLIN_CONFIG = LanguageConfig(
     ts_module="tree_sitter_kotlin",
     class_types=frozenset({"class_declaration", "object_declaration"}),
     function_types=frozenset({"function_declaration"}),
-    import_types=frozenset({"import_header"}),
+    # Grammar generations disagree: PyPI `tree_sitter_kotlin` emits `import`,
+    # older forks emit `import_header`. Accept both.
+    import_types=frozenset({"import_header", "import"}),
 def _import_kotlin(...):
     ...
     # Fallback: find identifier child
     for child in node.children:
-        if child.type == "identifier":
-            raw = _read_text(child, source)
-            tgt_nid = _make_id(raw)
+        if child.type in ("identifier", "qualified_identifier"):
+            raw = _read_text(child, source).split(".")[-1].strip()
+            tgt_nid = _make_id(raw)

Measured impact of the fix

Same 416-file Kotlin/Spring repo, graphify update . before and after, measuring
cross-file dependency edge recall against 512 unambiguous in-repo import statements
(only imports whose last segment resolves to exactly one file in the corpus are counted):

Kotlin imports edges Cross-file dep recall Nodes Edges
0.9.35 stock 0 45.3% (232/512) 8,097 11,193
0.9.35 + patch 1,322 94.7% (485/512) 11,752 16,158

The 45.3% that stock does resolve comes entirely from calls/references heuristics.
The dependencies it misses are the ones that matter most — shared value types (Money,
SkuId, Currency, Percentage) and every constructor-injected repository.

Node growth is from external import targets (Spring, Jackson) materializing as
unresolved stub nodes. If that is unwanted, it seems orthogonal and better handled by the
existing stub-rewire/prune path than by leaving the handler unreachable.

Related, not covered by this fix

Kotlin wildcard imports (import com.autoshipper.catalog.domain.*) take
raw.split(".")[-1] → "*" and resolve to nothing. With the patch applied, a file whose
only reference to a type comes via a wildcard import stays disconnected. Happy to open
that separately if you'd prefer it tracked on its own.

Adjacent open Kotlin issues (different mechanisms, same practical symptom of a
disconnected Kotlin graph): #1698 (cross-file object member calls) and #1699 (member
calls on typed receivers).

Activity

  1. xg-gh-25 commented on Aug 7, 2026

    @xg-gh-25

    The Kotlin import-edge dropout (45% → 95% recall with a 2-line fix) is a schema-grammar mismatch: the config declares node type import_header, but the bundled tree-sitter grammar emits import → every query for import_header returns zero matches → all import edges are silently dropped.

    Why this breaks silently:
    Tree-sitter queries fail gracefully—a query for a nonexistent node type returns an empty result set rather than throwing an error. The extraction pipeline sees "zero imports" and assumes the file has no dependencies, rather than "the query is broken."

    Root cause chain:

    1. _KOTLIN_CONFIG (config file) declares: (import_header) @import
    2. Actual grammar (tree-sitter-kotlin) emits: (import_declaration) or (import_list)
    3. Query engine looks for import_header → finds nothing → returns []
    4. Dependency graph builder sees empty import list → no edges created
    5. Downstream metrics report artificially low recall

    The 2-line fix (pseudo-diff):

    - (import_header) @import
    + (import_declaration) @import

    Or, if the grammar uses import_list as the container:

    - (import_header) @import
    + (import_list (import_declaration) @import)

    Validation:

    # Before fix
    tree-sitter query _KOTLIN_CONFIG "import_header" SomeFile.kt  # → 0 results
    
    # After fix  
    tree-sitter query _KOTLIN_CONFIG "import_declaration" SomeFile.kt  # → N results

    Why this pattern matters:
    This is a vocabulary impedance mismatch between configuration schema and runtime grammar. It happens when:

    • Configs are written against an idealized or documented grammar spec
    • The actual bundled grammar uses different node names (e.g., due to version skew, dialect differences, or underdocumented internals)
    • No integration test validates "config queries × grammar outputs = nonzero results"

    Systematic fix:
    Add a schema-coverage test that asserts every query pattern in _KOTLIN_CONFIG matches at least one node in a corpus of real Kotlin files. This catches vocabulary drift before it ships.

    Audit recommendation:
    Check other language configs (Java, Python, Rust) for similar mismatches. The pattern is:

    1. Grep config files for query patterns: grep -r "@import" configs/
    2. Run each query against a sample file from that language
    3. Assert len(matches) > 0

    Configs that produce zero matches on real-world code are silently broken and need alignment.


    Context: graph extraction and codebase analysis tooling. SwarmAI. Discussion: T-CUL

  2. mustaqeem66 commented on Aug 7, 2026

    @mustaqeem66

    Fix submitted in PR #2531.

    Summary of the fix:

    • now accepts both (older grammar forks) and (current PyPI grammar) node types
    • fallback handles both and children, extracting the last path segment

    Impact measured on 416-file Kotlin/Spring monolith:

    Metric Before After
    Kotlin imports edges 0 1,322
    Cross-file dep recall 45.3% 94.7%
    Nodes 8,097 11,752
    Edges 11,193 16,158

    All 20 Kotlin tests + 318 language tests + 567 cross-language tests pass.

  3. kskchaitanya1993 commented on Aug 8, 2026

    @kskchaitanya1993

    Confirming the grammar mismatch on 0.9.36 — and reporting that the two-line fix is necessary but not sufficient. It restores the edges, but ~88% of them dangle, so affected / path recall does not move.

    1. Grammar mismatch confirmed

    Parsing a .kt file directly with the bundled grammar (tree_sitter_kotlin, 0.9.36 wheel):

    top-level children of root:
       package_header           b'package demo.app'
       import                   b'import demo.service.Ledger'
       import                   b'import demo.model.Money'
    
    any node type containing 'import':
       import                   26
    'import_header' present: False
    

    So import_types=frozenset({"import_header"}) at extract.py:891 never matches, exactly as described.

    2. After the fix, the targets are unresolved

    I applied both halves of the suggested fix locally:

    # extract.py:891
    import_types=frozenset({"import_header", "import"}),
    
    # extract.py:628  (_import_kotlin fallback)
    if child.type in ("identifier", "qualified_identifier"):
        raw = _read_text(child, source).split(".")[-1].strip()

    Minimal repro — three files, no build system:

    // src/Money.kt
    package demo.model
    data class Money(val amount: Long)
    
    // src/Ledger.kt
    package demo.service
    import demo.model.Money
    class Ledger(private val opening: Money) {
        fun total(): Long = opening.amount
    }
    
    // src/Main.kt
    package demo.app
    import demo.service.Ledger
    import demo.model.Money
    fun main() {
        val l = Ledger(Money(5))
        println(l.total())
    }

    graphify extract . --code-only --no-cluster now emits 3 imports edges where 0 existed before — but every target id is absent from the node set:

    imports edges: 3
      Ledger.kt    -> target_id=money    exists=False  src=None
      Main.kt      -> target_id=ledger   exists=False  src=None
      Main.kt      -> target_id=money    exists=False  src=None
    
    all node ids:
      src_ledger_ledger    label=Ledger   src=src/Ledger.kt
      src_money_money      label=Money    src=src/Money.kt
    

    _import_kotlin builds its target with _make_id(module_name) on the last dotted segment, yielding money, while the declaring node is src_money_money. Nothing reconciles the two.

    Consequence — affected is still blind to the constructor-injection shape the issue is about:

    $ graphify affected "Money" --depth 4
    Affected nodes for Money
    - main() [calls] src/Main.kt:L7
    

    Ledger imports Money and takes it as a constructor parameter, and is still absent. Only main() appears, and only because Money(5) produced a calls edge — the import edge contributed nothing.

    3. At scale

    On a private multi-module Kotlin/Swift KMP repo:

    before fix after fix
    Kotlin imports edges 0 4,778
    …target resolves to a node with a source_file — 147 (3%)
    …target id absent from the graph entirely — 4,213 (88%)
    total graph edges 17,345 22,129
    affected result set for a widely-used class 17 files 17 files (byte-identical at depth 2 and depth 6)

    So the headline "45% → 95% dep recall" did not reproduce here. The edge count rises sharply and the traversal results do not change at all, because the new edges terminate on stubs.

    4. Suggestion

    This looks like the same unresolved-target class as #2329 rather than a separate Kotlin bug — the grammar mismatch just hides it. A fix probably wants the import target resolved against declared symbols (last segment → declaring node id, falling back to the file node for a whole-file import) before the edge is appended, applied once in the shared import path rather than per-language. Happy to test a patch against both the repro and the larger repo if that's useful.


    Investigated and written with Claude Code (Claude Opus 5).

  4. safishamsi commented on Aug 8, 2026

    @safishamsi
    Member

    Fixed in v0.9.37. The Kotlin extractor now matches the bundled grammar import node (imports were silently dropped) and resolves each import to the real target node, which also promotes genuine calls to EXTRACTED via import evidence. Thanks for the report (and @mustaqeem66 for #2531).

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