diff --git a/internal/core/external_collision_test.go b/internal/core/external_collision_test.go new file mode 100644 index 0000000..402f014 --- /dev/null +++ b/internal/core/external_collision_test.go @@ -0,0 +1,98 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +// Two library callees can share one @external id. Here, package example.com/dep +// has type Box with method Put, and its sub-package example.com/dep/Box has +// function Put. Both would be example.com/dep/Box/Put. Before the fix, one +// external_symbols entry overwrote the other, so the method's call edge resolved +// to the function's metadata. +// +// Practical shape (the dependency sits outside the project and is replaced in): +// +// dep/dep.go type Box struct{}; func (Box) Put(s string) string +// dep/Box/box.go package box; func Put(s string) string +// proj/main.go dep.Box{}.Put("a") ; box.Put("b") +func TestExternalIDs_TypeMethodAndFunctionKeepSeparateSymbols(t *testing.T) { + base := t.TempDir() + dep := filepath.Join(base, "dep") + proj := filepath.Join(base, "proj") + files := map[string]string{ + filepath.Join(dep, "go.mod"): "module example.com/dep\n\ngo 1.22\n", + filepath.Join(dep, "dep.go"): "package dep\n\ntype Box struct{}\n\nfunc (Box) Put(s string) string { return \"method:\" + s }\n", + filepath.Join(dep, "Box", "box.go"): "package box\n\nfunc Put(s string) string { return \"func:\" + s }\n", + filepath.Join(proj, "go.mod"): "module example.com/proj\n\ngo 1.22\n\nrequire example.com/dep v0.0.0\n\nreplace example.com/dep => " + dep + "\n", + filepath.Join(proj, "main.go"): "package main\n\nimport (\n\t\"fmt\"\n\n\t\"example.com/dep\"\n\tbox \"example.com/dep/Box\"\n)\n\n" + + "func main() {\n\tfmt.Println(dep.Box{}.Put(\"a\"), box.Put(\"b\"))\n}\n", + } + for path, content := range files { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + var doc struct { + Application struct { + ExternalSymbols map[string]struct { + ID string `json:"id"` + Module string `json:"module"` + Signature string `json:"signature"` + } `json:"external_symbols"` + CallGraph []struct { + Src string `json:"src"` + Dst string `json:"dst"` + } `json:"call_graph"` + } `json:"application"` + } + if err := json.Unmarshal(emitCallGraphJSON(t, proj), &doc); err != nil { + t.Fatal(err) + } + + // Each callee needs its own symbol, with its own metadata. + var methodID, funcID string + for id, sym := range doc.Application.ExternalSymbols { + if sym.ID != id { + t.Errorf("symbol keyed %s carries id %s", id, sym.ID) + } + switch { + case sym.Signature == "Box.Put" && sym.Module == "example.com/dep": + methodID = id + case sym.Signature == "Put" && sym.Module == "example.com/dep/Box": + funcID = id + } + } + if methodID == "" { + t.Fatalf("no external symbol for method dep.Box.Put; have %+v", doc.Application.ExternalSymbols) + } + if funcID == "" { + t.Fatalf("no external symbol for function box.Put; have %+v", doc.Application.ExternalSymbols) + } + if methodID == funcID { + t.Fatalf("method and function share id %s", methodID) + } + + // The two calls from main must reach their own symbols. + var toMethod, toFunc bool + for _, e := range doc.Application.CallGraph { + if e.Dst == methodID { + toMethod = true + } + if e.Dst == funcID { + toFunc = true + } + } + if !toMethod { + t.Errorf("no call edge reaches the method symbol %s", methodID) + } + if !toFunc { + t.Errorf("no call edge reaches the function symbol %s", funcID) + } +} diff --git a/internal/schema/v2/ids.go b/internal/schema/v2/ids.go index 2b2cf5f..fefc9f2 100644 --- a/internal/schema/v2/ids.go +++ b/internal/schema/v2/ids.go @@ -1,6 +1,8 @@ package v2 import ( + "crypto/sha256" + "encoding/hex" "fmt" "strings" "unicode" @@ -111,6 +113,31 @@ func ExternalID(appID, importPath, sig string) string { return appID + idSep + "@external" + idSep + importPath + idSep + strings.ReplaceAll(sig, ".", idSep) } +// DisambiguateExternalIDs gives every external callee a distinct id. plain maps a +// callee's full signature to its ExternalID. The dot-to-segment rule is not +// injective: a method Box.Put in package example.com/dep and a function Put in +// package example.com/dep/Box both give example.com/dep/Box/Put. A callee whose +// plain id is unique keeps it, so every id that was already emitted is unchanged. +// Callees that share a plain id each get ":" plus the first 16 hex digits of the +// SHA-256 of their own full signature. That suffix depends only on the callee, not +// on which other callees are present or in what order, so an id is stable while +// the collision lasts and no callee overwrites another. +func DisambiguateExternalIDs(plain map[string]string) map[string]string { + count := make(map[string]int, len(plain)) + for _, id := range plain { + count[id]++ + } + out := make(map[string]string, len(plain)) + for fullSig, id := range plain { + if count[id] > 1 { + sum := sha256.Sum256([]byte(fullSig)) + id += ":" + hex.EncodeToString(sum[:8]) + } + out[fullSig] = id + } + return out +} + // memberName is the member segment a symbol contributes under its parent: the // part of its signature after the last dot. The package import path is always // before that dot and Go identifiers contain no dots, so this strips the path diff --git a/internal/schema/v2/ids_external_test.go b/internal/schema/v2/ids_external_test.go new file mode 100644 index 0000000..10426e4 --- /dev/null +++ b/internal/schema/v2/ids_external_test.go @@ -0,0 +1,63 @@ +package v2 + +import "testing" + +const extApp = "can://ns/app" + +// Unique external ids are returned unchanged: every id already emitted stays valid. +func TestDisambiguateExternalIDs_UniqueIDsUnchanged(t *testing.T) { + plain := map[string]string{ + "fmt.Println": ExternalID(extApp, "fmt", "Println"), + "strings.Builder.WriteString": ExternalID(extApp, "strings", "Builder.WriteString"), + } + got := DisambiguateExternalIDs(plain) + for sig, id := range plain { + if got[sig] != id { + t.Errorf("%s: id changed from %s to %s", sig, id, got[sig]) + } + } +} + +// The motivating case: a method and a function that share a plain id both get +// distinct, suffixed ids, and neither keeps the plain one. +func TestDisambiguateExternalIDs_CollidingCalleesAreDistinct(t *testing.T) { + const method = "example.com/dep.Box.Put" + const function = "example.com/dep/Box.Put" + plainID := ExternalID(extApp, "example.com/dep/Box", "Put") // both map here + plain := map[string]string{ + method: ExternalID(extApp, "example.com/dep", "Box.Put"), + function: plainID, + } + if plain[method] != plain[function] { + t.Fatalf("fixture does not collide: %s vs %s", plain[method], plain[function]) + } + got := DisambiguateExternalIDs(plain) + if got[method] == got[function] { + t.Fatalf("colliding callees still share id %s", got[method]) + } + for sig := range plain { + if got[sig] == plainID { + t.Errorf("%s kept the plain id %s", sig, plainID) + } + } +} + +// The suffix depends only on the callee's own signature, so adding or removing an +// unrelated callee does not change an id, and the order of the set does not matter. +func TestDisambiguateExternalIDs_StableAcrossSets(t *testing.T) { + plainID := ExternalID(extApp, "example.com/dep/Box", "Put") + a := "example.com/dep.Box.Put" + b := "example.com/dep/Box.Put" + c := "example.com/other.Box.Put" + + pair := DisambiguateExternalIDs(map[string]string{a: plainID, b: plainID}) + triple := DisambiguateExternalIDs(map[string]string{ + a: plainID, b: plainID, c: ExternalID(extApp, "example.com/other", "Box.Put"), + }) + if pair[a] != triple[a] || pair[b] != triple[b] { + t.Errorf("an unrelated callee changed a colliding id: pair=%v triple=%v", pair, triple) + } + if triple[c] != ExternalID(extApp, "example.com/other", "Box.Put") { + t.Errorf("a unique callee was renamed: %s", triple[c]) + } +} diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index bad9fda..16dad46 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -254,7 +254,7 @@ func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVers CallGraph: emitCallGraph(app.CallGraph, e.idx), }, } - out.Application.ExternalSymbols = emitExternalSymbols(e.appID, app.Externals, e.sdg.standIns()) + out.Application.ExternalSymbols = emitExternalSymbols(app.Externals, e.idx.externals, e.sdg.standIns()) out.Application.Artifacts, out.Application.Dependencies = emitRepository(e.appID, app.Repository) if e.flow.on { out.KLimit = kLimit @@ -473,19 +473,23 @@ func calleeID(sig *string, idx sigIndex) *string { } // externalIDs maps each library callee's full signature to its @external id. +// +// The result is the single source of external ids: the call-edge index and +// external_symbols both read it, so an edge and its symbol always agree. Ids +// that collide are made distinct (v2.DisambiguateExternalIDs). func externalIDs(appID string, externals map[string]schema.GoExternalCallee) map[string]string { - ids := make(map[string]string, len(externals)) + plain := make(map[string]string, len(externals)) for fullSig, ext := range externals { - ids[fullSig] = v2.ExternalID(appID, ext.ImportPath, ext.Sig) + plain[fullSig] = v2.ExternalID(appID, ext.ImportPath, ext.Sig) } - return ids + return v2.DisambiguateExternalIDs(plain) } // emitExternalSymbols builds application.external_symbols, keyed by @external // id. Nil (omitted from JSON) when no library callee was recorded. At L4 // standIns (by full callee signature) gives each stand-in its body: its // formal vertices, id v2.GlobalOrdinal(external id, key). -func emitExternalSymbols(appID string, externals map[string]schema.GoExternalCallee, standIns map[string][]sdg.Vertex) map[string]v2.ExternalSymbol { +func emitExternalSymbols(externals map[string]schema.GoExternalCallee, ids map[string]string, standIns map[string][]sdg.Vertex) map[string]v2.ExternalSymbol { for _, sig := range slices.Sorted(maps.Keys(standIns)) { if _, ok := externals[sig]; !ok { warnf("L4 emit: stand-in %s is not an external symbol; its body is dropped", sig) @@ -496,7 +500,7 @@ func emitExternalSymbols(appID string, externals map[string]schema.GoExternalCal } out := make(map[string]v2.ExternalSymbol, len(externals)) for fullSig, ext := range externals { - id := v2.ExternalID(appID, ext.ImportPath, ext.Sig) + id := ids[fullSig] params := make([]v2.ExternalParameter, 0, len(ext.Params)) for _, p := range ext.Params { params = append(params, v2.ExternalParameter{Name: p.Name, Type: p.Type, IsVariadic: p.IsVariadic})