fix(go): an interface links the interfaces it embeds

Merged
CO
2mo ago
+583-49

Problem

A Go interface that embeds another produced no extends reference in either extraction engine:

type IRouter interface {   // gin-gonic/gin: no IRouter -> IRoutes edge
	IRoutes
	Group(string, ...HandlerFunc) *RouterGroup
}

extractInheritance (TS) and extract_inheritance (kernel, go.rs) look for a constraint_elem. That node type exists in neither the vendored tree-sitter-go.wasm nor the kernel's tree-sitter-go 0.23 crate (checked: 0 occurrences in both), so the branch has been dead since it was added. Both grammars parse an embedded interface as interface_type > type_elem > type_identifier, or type_elem > qualified_type for io.Closer. Nothing matched type_elem, so every embedding was dropped.

Repro from the report (extractFromSource('p.go', …), Querier { Queryable; io.Closer; Close() error }):

wasm (CODEGRAPH_KERNEL=0)kernel
main[][]
this PRQuerier extends Queryable, Querier extends Closersame

I searched open issues and PRs for this symptom (constraint_elem, type_elem, IRouter, interface/Go embedding) and found nothing overlapping.

What changed

Extraction, both engines (tree-sitter.ts + languages/go.ts, codegraph-kernel/src/go.rs)

  • A type_elem holding exactly one named type (comments ignored) is an embedded interface, recorded as extends. A union (float32 | float64), an underlying-type term (~int) or a lone predeclared type (interface{ int64 }) is a type-set constraint and records nothing.
  • One helper, goEmbeddedTypeName (Rust: embedded_type_name), now reads an embedded type for both interfaces and structs: T, *T, pkg.T and T[X] all embed T.
  • The dead constraint_elem branch is gone.

The qualified-embedding decision (io.Closer, sync.Mutex)

A qualified embedding is recorded as its bare name at the name's own position, the convention Go type annotations already use. The resolver reads the package qualifier back from the source at that position (#2322), so:

  • a project package's type (storage.LabelQuerier, *refresh.Discovery) resolves through the import to that package's type (resolvedBy: import, 0.9);
  • a stdlib or third-party type (io.Closer, sync.Mutex, zap.Logger) is rejected by the existing external-qualifier check and stays an unresolved ref. It never lands on a project type that shares its name.

To keep interfaces and structs consistent, struct embedding changes the same way. It used to match only a direct type_identifier child, which silently skipped qualified embeddings (sync.Mutex, *refresh.Discovery) and generic ones (baseBucketIterator[float64, float64]). Those now emit too.

Go's predeclared types are never recorded, in either position. int64 in an interface is a constraint's term, and error, any and comparable exist in no graph. So struct { error }, which used to leave an unresolvable ref, now records nothing.

Resolution, two guards found during validation

  1. frameworks/go.ts: the naming heuristics no longer take extends/implements refs, following #1827's gate for the Spring heuristics. Pattern 4 ("PascalCase → model struct") sees structs only and outranked name matching, so an embedded interface went to another package's same-named struct. With this PR's new edges, 6 of prometheus's interface embeddings went wrong this way (parser.Expr extends Node → discovery/kubernetes's struct Node, instead of the Node interface in the same file). On main it already misbound 3 of 19 struct embeddings:
    • etcd clientv3.Client → server/lease's Lease struct, instead of its own Lease interface
    • prometheus fakeChunk → prompb.Chunk
    • prometheus seriesToChunkEncoder → promql.Series
  2. gateTargetKind: a Go supertype written through a package that is none of the file's imports as indexed stays unresolved, via the new isGoUnknownQualified. Unaliased versioned imports are registered under their last path element (go.yaml.in/yaml/v3 → v3), so yaml in prometheus's RuleGroupNode { yaml.Node } matched no import. The ref then fell back to a bare-name match: the discovery/kubernetes Node struct. The guard fires only when a qualifier is written and matches no import, so it can only remove guesses. It changed nothing on gin or etcd and removed exactly that one edge on prometheus.

Validation

Tests

  • New __tests__/go-interface-embedding.test.ts, 13 tests:
    • extraction on kernel and wasm, each with LF and CRLF;
    • an indexed module with go.mod, covering same-package, project-package, stdlib and versioned-import embeddings, constraints, a self-named Reader { io.Reader }, the promql Node shape, and the type hierarchy.
  • All 13 fail on main. Separate red checks for the resolver guards:
    • without the framework gate: Expr extends Node@other/other.go and exprWrapper extends Node@other/other.go;
    • without the unknown-qualifier guard: RuleGroupNode extends Node@other/other.go.
  • The Go torture fixture gained interface embeddings (unqualified, qualified, generic, error), qualified/pointer/generic struct embeddings and constraints. kernel-tsjs-parity.test.ts passes, LF and CRLF.
  • Full suite (CODEGRAPH_KERNEL_EXPECT=1): 6329 passed, 4 failed. The failures are timeouts in git-index-currency and sync, plus an EBUSY rmdir in index-daemon-rebuild. All 74 tests in those 3 files pass when rerun with --no-file-parallelism.
  • After merging main (#2395): tsc and 17 related suites (Go, frameworks, hierarchy, resolution, extraction, parity) pass, 1312 tests.

Kernel/wasm parity sweep (scripts/kernel-parity.mjs <repo> --lang go), identical before and after:

RepoResult
gin99/99
prometheus715/736
etcd1061/1105, 40 deferred

The remaining diffs are pre-existing function_ref refs named pkg.None (follow-up below). Wasm ref totals grow by exactly the new extends refs (+157 on prometheus, +135 on etcd).

Before/after graphs (full index, kernel path, main@ac1f430d vs this PR; natural-key edge diff):

RepoGo filesedges main → PRaddedremoved
gin997,689 → 7,69230
prometheus73696,401 → 96,5741807
etcd1,10562,657 → 62,77613213

Every added extends/implements edge was checked against the source at its site. A bare name must resolve into its own package's directory. A qualified name must resolve into the directory its file's import of that package names (module path stripped).

  • gin, 3 added: IRouter extends IRoutes, and BindingBody extends Binding in each of the two build-tag variants (binding.go, binding_nomsgpack.go), each pointing at its own file's Binding.
  • prometheus, 128 added:
    • 36 interface→interface extends, 48 struct→struct extends, 44 struct→interface implements;
    • 90 resolved into the import's package, 38 into their own package, none anywhere else;
    • 6 of them re-resolve the removed framework edges: 4 to the same target, 2 corrected (fakeChunk, seriesToChunkEncoder);
    • so 122 are new: 36 interface embeddings, 83 qualified struct embeddings (*refresh.Discovery ×31, storage.Appender …), 3 generic ones.
  • etcd, 103 added:
    • 29 interface→interface, 29 struct→struct, 45 struct→interface;
    • 64 resolved through the import's package, 39 into their own package;
    • 13 re-resolve the removed framework edges (12 same target, 1 corrected: Client → its own Lease);
    • for example ServerV3 extends apply.RaftStatusGetter, Hasher extends mvcc.HashStorage, kvPrefix implements clientv3.KV, quotaKVServer implements pb.KVServer.
  • Removed edges: all are the framework re-resolutions above, plus prometheus's prompb Chunk::Reset → fakeChunk::Reset interface-impl call, which followed the wrong fakeChunk supertype. No correct edge was lost.
  • Other added edges:
    • interface-impl calls: prometheus 51 (17 from interface bases, 34 from struct bases), etcd 29 (24 / 5). These come from the synthesizer's existing rule for embeddings; main already has 79 / 55 struct-based ones from same-package embeddings. Examples: KV::Get → kvPrefix::Get, KVServer::Put → quotaKVServer::Put, UnimplementedAuthServer::Authenticate → mockAuthServer::Authenticate.
    • One newly resolved call: prometheus storage/merge.go:833 ….Iterator(nil) on a ChunkSeries now reaches ChunkIterable::Iterator through the new ChunkSeries extends ChunkIterable edge. On main that ref failed.
  • Unresolved extends refs: gin 0 → 15, prometheus 9 → 44, etcd 1 → 52. All are stdlib/third-party embeddings (http.ResponseWriter, sync.Mutex, io.Closer, grpc.ServerStream, zap.Logger, raft.Node …) plus prometheus's yaml.Node. No project type was left behind.
  • Invariants on all three graphs: 0 supertype self-loops, 0 Go interface→non-interface supertypes, 0 struct extends edges to an interface (all promoted to implements).
  • What users see: codegraph impact IRoutes on gin goes from 197 to 200 affected symbols and now lists IRouter itself.

Go implicit interface satisfaction (#584), before and after

goImplementsEdges builds each interface's method set from its own contains edges only. It ignored embedded interfaces before this PR and still does, so the new edges move none of its output (80 / 1507 / 697 go-implements edges on gin / prometheus / etcd, identical).

That truncation already produces false positives. On etcd, AuthReadTx is UnsafeAuthReader plus Lock/Unlock, so everything with Lock/Unlock "implements" it (RWMutex, lockerMutex, lockServer, readTx …).

I measured what following the new edges would do (on this PR's graphs):

prometheusetcd
interfaces that gain methods from linked embeddings22 (7 pure-embedding)21 (5)
go-implements edges dropped when the interface side is flattened8876
…of which the struct satisfies through promoted methods6511
new implementers of pure-embedding interfaces (counting promoted methods)8912

So the synthesis has to flatten both sides together: the interface's embedded interfaces and the struct's promoted methods. Flattening only the interface side would swap these false positives for false negatives, such as a querier that gets LabelValues/Close from an embedded base. I left that out of this PR; see follow-ups.

Notes and limits

  • A constraint with a single non-basic named term (type C interface{ MyInt }) parses exactly like an embedding and would record extends MyInt. None of the three repos has one (interface→non-interface supertypes: 0).
  • A qualified embedding through an unaliased versioned import (clientv3.KV under a bare "go.etcd.io/etcd/client/v3") now stays unresolved rather than being guessed. etcd aliases these imports, so nothing was lost there.

Follow-ups (not in this PR)

  • #584 synthesis: flatten embedded interfaces' methods and count promoted methods on the struct side, using the edges this PR adds (numbers above).
  • Go framework Pattern 4 for type references: the same struct-only heuristic still outranks name matching for references. On main, prometheus has 29 parameter/result types Node in promql/parser that point at discovery/kubernetes's Node struct instead of the package's own interface.
  • Go import local names for versioned paths: go.yaml.in/yaml/v3 is registered as v3 and gopkg.in/yaml.v3 as yaml.v3, so yaml.X calls and type refs never see their import.
  • Kernel parity: for a selector like raft.None the kernel checks the field name None against the function-ref stoplist, while TS checks the whole name. That gives 202 diffs on prometheus and 6 on etcd, before and after this PR.

🤖 Generated with Claude Code