diff --git a/cmd/orchestratorvet/README.md b/cmd/orchestratorvet/README.md index a4abd519..567d1b5b 100644 --- a/cmd/orchestratorvet/README.md +++ b/cmd/orchestratorvet/README.md @@ -38,8 +38,8 @@ the package under analysis passes it to one of - `(*task.TaskRegistry).AddOrchestratorVersion` - `(*task.TaskRegistry).AddOrchestratorNVersion` -From each of those roots it follows the whole-package call graph through -same-package named functions, methods, function variables whose target can be +From each of those roots it follows the call graph through named functions, +concrete methods, function variables whose target can be proven, and the nested function literals whose bodies are proven to execute -- through a direct call, a call through a single-assignment function variable, a raw `go` or `defer` call, @@ -51,6 +51,11 @@ terminates because each function is visited once, and a helper reached from several orchestrators is reported once. Activity bodies, entity bodies, and any function not reachable from a registered orchestrator are never reported. +The handler itself or a helper it calls can live in another package in the +same Go module. An imported hazard is reported at the local registration or +call site, with a representative call path and no automatic fix. Dependencies +provide summaries even when only the registration package is named in `go vet`. + ## Checks ### Wall clock @@ -224,14 +229,19 @@ The analyzer reports only what it can prove, and stays silent otherwise. - A random generator is only reported when its seed provably reaches a source that varies between runs. A constant seed, a seed taken from orchestration input, and a seed the analyzer cannot follow are all left alone. -- Every diagnostic is deduplicated by source position and category, so a shared - helper is reported once no matter how many orchestrators reach it. +- Diagnostics are deduplicated by source position and category. For an imported + call, the analyzer shows one witness per hazard category at that call site. ## Limitations -- The analyzer runs one package at a time. Helpers, activity registrations, and - orchestrator bodies in other packages are invisible to it, so hazards there - are not reported. +- Imported bodies are summarized through Go analysis facts. The analyzer does + not follow bodies across module boundaries, inside the standard library or + the SDK's `task` package, or when module metadata is unavailable. Known + hazardous APIs are still checked at their call sites. Summaries do not trust + the initial value of an exported package variable, which an importer can + reassign. +- Registry-name completeness and proofs about non-progressing loops do not + use imported summaries. - Calls through interface values, struct fields, and function parameters cannot be resolved to a body and are not followed. - Version-aware name resolution is approximated: a task name is considered @@ -261,7 +271,7 @@ cd cmd/orchestratorvet && go test ./... cd cmd/orchestratorvet && go test -run '^$' -bench . ./analysis/orchestratorgo/... ``` -The benchmarks measure orchestrator-count scaling, call-graph depth, and the -early exit taken by the overwhelming majority of packages, which register no +The benchmarks measure orchestrator-count scaling, call-graph depth, and +summary construction for packages that register no orchestrators at all. They type-check against the same durable task stub the fixtures use, so the two cannot drift apart. diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/analyzer.go b/cmd/orchestratorvet/analysis/orchestratorgo/analyzer.go index 4696234a..a61b64b0 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/analyzer.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/analyzer.go @@ -2,8 +2,8 @@ // package registers with task.TaskRegistry. // // The analyzer starts from every proven registration in the package under -// analysis, follows the call graph through same-package named functions, -// methods, resolvable function variables, and the nested function literals +// analysis, follows the call graph through named functions, methods, +// resolvable function variables, and the nested function literals // whose bodies are proven to execute -- through a direct call whose callee // resolves to the literal, a call through a single-assignment variable, a raw go or // defer call, or the callback argument of an explicitly modeled invoker such @@ -32,13 +32,15 @@ // - registration forms that task.TaskRegistry rejects or that derive unstable // names, and registered orchestrators invoked as plain Go calls. // -// The analyzer stays silent whenever proof is unavailable. Dynamic registration, -// wildcard registration, cross-package registration, functions reached only -// through values it cannot resolve, and code outside orchestrator reachability -// are all left alone. +// Same-module imports contribute replay-hazard summaries via analysis facts. +// These summaries do not establish registry completeness or loop progress. +// The analyzer stays silent when it cannot resolve a call or registration to +// a body or a known hazard, and outside registered orchestrator reachability. package orchestratorgo import ( + "go/token" + "golang.org/x/tools/go/analysis" ) @@ -46,10 +48,11 @@ var includeTestFiles bool // Analyzer reports replay hazards in registered durable task orchestrators. var Analyzer = &analysis.Analyzer{ - Name: "orchestratorgo", - Doc: "report nondeterministic and replay-unsafe code in durable task orchestrators", - URL: "https://github.com/microsoft/durabletask-go/tree/main/cmd/orchestratorvet/analysis/orchestratorgo", - Run: run, + Name: "orchestratorgo", + Doc: "report nondeterministic and replay-unsafe code in durable task orchestrators", + URL: "https://github.com/microsoft/durabletask-go/tree/main/cmd/orchestratorvet/analysis/orchestratorgo", + Run: run, + FactTypes: []analysis.Fact{new(hazardFact)}, } func init() { @@ -63,8 +66,12 @@ func init() { func run(pass *analysis.Pass) (any, error) { index := newPackageIndex(pass) + facts := newHazardFacts(index) + if facts != nil { + facts.export() + } registry := collectRegistrations(pass, index) - if len(registry.roots) == 0 { + if len(registry.roots) == 0 && len(registry.importedRoots) == 0 { return nil, nil } reach := reachableFunctions(index, registry.roots) @@ -75,8 +82,18 @@ func run(pass *analysis.Pass) (any, error) { registry: registry, reported: make(map[reportKey]bool), } + if facts != nil { + for _, root := range registry.importedRoots { + facts.report(check, root.pos, root.function) + } + } for _, node := range reach.order { check.checkFunction(node) + if facts != nil { + index.forEachTarget(node, func(pos token.Pos, target functionTarget) { + facts.report(check, pos, target.imported) + }) + } } check.reportClockDiagnostics() return nil, nil diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/bench_test.go b/cmd/orchestratorvet/analysis/orchestratorgo/bench_test.go index 5492edf5..0ad84993 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/bench_test.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/bench_test.go @@ -2,6 +2,7 @@ package orchestratorgo_test import ( "fmt" + "go/types" "os" "path/filepath" "strings" @@ -85,6 +86,13 @@ func helper%d_%d(value int) int { } } builder.WriteString("}\n") + if !register { + builder.WriteString("\nfunc Exported(ctx *task.OrchestrationContext) {\n") + for i := 0; i < orchestrators; i++ { + fmt.Fprintf(&builder, "\t_, _ = orchestrator%d(ctx)\n", i) + } + builder.WriteString("}\n") + } return builder.String() } @@ -115,14 +123,17 @@ func loadBenchmarkPass(b *testing.B, source string) *analysis.Pass { } pkg := loaded[0] return &analysis.Pass{ - Analyzer: orchestratorgo.Analyzer, - Fset: pkg.Fset, - Files: pkg.Syntax, - Pkg: pkg.Types, - TypesInfo: pkg.TypesInfo, - TypesSizes: pkg.TypesSizes, - Report: func(analysis.Diagnostic) {}, - ResultOf: map[*analysis.Analyzer]any{}, + Analyzer: orchestratorgo.Analyzer, + Fset: pkg.Fset, + Files: pkg.Syntax, + Pkg: pkg.Types, + TypesInfo: pkg.TypesInfo, + TypesSizes: pkg.TypesSizes, + Report: func(analysis.Diagnostic) {}, + ResultOf: map[*analysis.Analyzer]any{}, + Module: &analysis.Module{Path: "bench"}, + ImportObjectFact: func(types.Object, analysis.Fact) bool { return false }, + ExportObjectFact: func(types.Object, analysis.Fact) {}, } } @@ -157,8 +168,8 @@ func BenchmarkAnalyzerCallGraphDepth(b *testing.B) { } } -// BenchmarkAnalyzerNoOrchestrators measures the cost of the early exit taken by -// the overwhelming majority of packages, which register nothing at all. +// BenchmarkAnalyzerNoOrchestrators measures summary construction without +// registrations. func BenchmarkAnalyzerNoOrchestrators(b *testing.B) { runAnalyzerBenchmark(b, generateBenchmarkPackage(8, 4, false)) } diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/checks.go b/cmd/orchestratorvet/analysis/orchestratorgo/checks.go index ec7861ee..3251f387 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/checks.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/checks.go @@ -36,6 +36,9 @@ type checker struct { registry *registrySet reported map[reportKey]bool + // In summary mode the checker collects only hazards proved within a body. + collectHazard func(category, message string) + // Clock fixes are reported after all reachable functions have been checked, // so each file's replacements and import cleanup form one atomic fix. clockDiagnostics []analysis.Diagnostic @@ -48,6 +51,10 @@ func (c *checker) report( format string, args ...any, ) { + if c.collectHazard != nil { + c.collectHazard(category, fmt.Sprintf(format, args...)) + return + } key := reportKey{pos: pos, category: category} if c.reported[key] { return @@ -134,17 +141,23 @@ func (c *checker) inspect(node ast.Node, stack []ast.Node, file *ast.File) { ) } case *ast.ForStmt: - c.checkUnboundedLoop(node) + if c.registry != nil { + c.checkUnboundedLoop(node) + } case *ast.CallExpr: c.checkCall(node, stack, file) } } func (c *checker) checkGoStmt(node *ast.GoStmt, stack []ast.Node, file *ast.File) { + var fixes []analysis.SuggestedFix + if c.collectHazard == nil { + fixes = c.goStatementFix(node, contextParameter(c.pass, stack), file) + } c.report( node.Go, categoryGoroutine, - c.goStatementFix(node, contextParameter(c.pass, stack), file), + fixes, "raw go statement is not deterministic in an orchestrator; "+ "use (*task.OrchestrationContext).Go", ) @@ -158,7 +171,9 @@ func (c *checker) checkCall(call *ast.CallExpr, stack []ast.Node, file *ast.File if function == nil { return } - c.checkDirectOrchestratorCall(call, function) + if c.registry != nil { + c.checkDirectOrchestratorCall(call, function) + } if owner, name, ok := methodOwner(function); ok { c.checkMethodCall(call, function, owner, name) return @@ -215,10 +230,14 @@ func (c *checker) checkPackageCall( switch path { case "time": if replacement, ok := wallClockFunctions[name]; ok { + var fixes []analysis.SuggestedFix + if c.collectHazard == nil { + fixes = c.currentTimeFix(call, name, stack, file) + } c.report( call.Lparen, categoryWallClock, - c.currentTimeFix(call, name, stack, file), + fixes, "time.%s is not deterministic in an orchestrator; "+ "use (*task.OrchestrationContext).%s", name, @@ -334,7 +353,7 @@ func (c *checker) checkMethodCall( name := function.Name() switch ownerPath { case taskPackagePath: - if ownerName == "OrchestrationContext" { + if ownerName == "OrchestrationContext" && c.registry != nil { c.checkOrchestrationContextCall(call, name) } return diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/facts.go b/cmd/orchestratorvet/analysis/orchestratorgo/facts.go new file mode 100644 index 00000000..42e918d0 --- /dev/null +++ b/cmd/orchestratorvet/analysis/orchestratorgo/facts.go @@ -0,0 +1,154 @@ +package orchestratorgo + +import ( + "cmp" + "go/ast" + "go/token" + "go/types" + "slices" + "strings" +) + +// A fact carries positive evidence only, with one witness per hazard category. +// Positions and suggested fixes belong to the declaring package's analysis pass. +type hazardFact struct { + Module string + Witnesses []hazardWitness +} + +func (*hazardFact) AFact() {} + +type hazardWitness struct { + Category string + Path []string + Message string +} + +type hazardFacts struct { + index *packageIndex + module string + cache map[*types.Func][]hazardWitness +} + +func newHazardFacts(index *packageIndex) *hazardFacts { + pass := index.pass + if pass.Module == nil || pass.Module.Path == "" || pass.Pkg.Path() == taskPackagePath { + return nil + } + return &hazardFacts{ + index: index, module: pass.Module.Path, cache: make(map[*types.Func][]hazardWitness), + } +} + +func (f *hazardFacts) imported(function *types.Func) []hazardWitness { + if function == nil || function.Pkg().Path() == taskPackagePath { + return nil + } + if witnesses, ok := f.cache[function]; ok { + return witnesses + } + var fact hazardFact + var witnesses []hazardWitness + if f.index.pass.ImportObjectFact(function, &fact) && fact.Module == f.module { + witnesses = fact.Witnesses + } + f.cache[function] = witnesses + return witnesses +} + +func (f *hazardFacts) report(c *checker, pos token.Pos, function *types.Func) { + for _, w := range f.imported(function) { + c.report(pos, w.Category, nil, "%s: %s", strings.Join(w.Path, " -> "), w.Message) + } +} + +func (f *hazardFacts) export() { + index := f.index + index.summarizing = true + defer func() { index.summarizing = false }() + + var bodies []ast.Node + names := make(map[ast.Node]*types.Func, len(index.functions)) + for function, decl := range index.functions { + names[decl] = function + if function.Exported() && decl.Body != nil { + bodies = append(bodies, decl) + } + } + slices.SortFunc(bodies, func(a, b ast.Node) int { return cmp.Compare(a.Pos(), b.Pos()) }) + exports := len(bodies) + seen := make(map[ast.Node]bool, exports) + for _, body := range bodies { + seen[body] = true + } + + // Build reverse edges, then propagate evidence back to callers. Each body + // is checked once, and receives each category at most once even in a cycle. + parents := make(map[ast.Node][]ast.Node) + known := make(map[ast.Node][]hazardWitness) + type finding struct { + body ast.Node + hazardWitness + } + var findings []finding + add := func(body ast.Node, w hazardWitness) { + for _, previous := range known[body] { + if previous.Category == w.Category { + return + } + } + label := "func literal" + if function := names[body]; function != nil { + label = function.FullName() + } + w.Path = prependWitness(label, w.Path) + known[body] = append(known[body], w) + findings = append(findings, finding{body, w}) + } + + c := &checker{pass: index.pass, index: index} + for i := 0; i < len(bodies); i++ { + body := bodies[i] + c.collectHazard = func(category, message string) { + add(body, hazardWitness{Category: category, Message: message}) + } + c.checkFunction(body) + index.forEachTarget(body, func(_ token.Pos, target functionTarget) { + if target.local != nil { + parents[target.local] = append(parents[target.local], body) + if !seen[target.local] { + seen[target.local] = true + bodies = append(bodies, target.local) + } + } + for _, w := range f.imported(target.imported) { + add(body, w) + } + }) + } + + for i := 0; i < len(findings); i++ { + hit := findings[i] + for _, parent := range parents[hit.body] { + add(parent, hit.hazardWitness) + } + } + for _, body := range bodies[:exports] { + if witnesses := known[body]; len(witnesses) != 0 { + index.pass.ExportObjectFact(names[body], &hazardFact{Module: f.module, Witnesses: witnesses}) + } + } +} + +// Bound the witness size while retaining both ends of a long path. +func prependWitness(label string, path []string) []string { + const maxSteps = 8 + if len(path) >= maxSteps { + result := make([]string, maxSteps) + result[0] = label + copy(result[1:maxSteps-2], path) + result[maxSteps-2], result[maxSteps-1] = "...", path[len(path)-1] + return result + } + return append([]string{label}, path...) +} diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/facts_test.go b/cmd/orchestratorvet/analysis/orchestratorgo/facts_test.go new file mode 100644 index 00000000..d232685b --- /dev/null +++ b/cmd/orchestratorvet/analysis/orchestratorgo/facts_test.go @@ -0,0 +1,159 @@ +package orchestratorgo_test + +import ( + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestCrossPackageVet(t *testing.T) { + stub, err := os.ReadFile(taskStubPath) + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + for name, contents := range map[string]string{ + `go.mod`: `module example.com/workflows +go 1.26.0 +require ( + github.com/microsoft/durabletask-go v0.0.0 + example.com/workflows/external v0.0.0 +) +replace github.com/microsoft/durabletask-go => ./sdk +replace example.com/workflows/external => ./external +`, + `sdk/go.mod`: "module github.com/microsoft/durabletask-go\ngo 1.26.0\n", + `sdk/task/task.go`: string(stub), + `external/go.mod`: "module example.com/workflows/external\ngo 1.26.0\n", + `external/clock.go`: "package external\nimport \"time\"\nfunc Clock() { _ = time.Now() }\n", + `billing/billing.go`: `package billing +import ( + "math/rand" + "os" + "time" + "github.com/microsoft/durabletask-go/task" +) +func Cutoff() { first(0) } +func first(depth int) { second(depth) } +func second(depth int) { + if depth > 0 { first(depth - 1) } + _ = time.Now() +} +type Ledger[T any] struct{} +func (Ledger[T]) Read() { _ = os.Getenv("REGION") } +func Callback(*task.OrchestrationContext) { _ = time.Now() } +func Clean() { _ = time.Unix(0, 0) } +type Hook func() +func (f Hook) RunAndNext() Hook { + f() + f = Cutoff + return f +} +var Seed = time.Now().UnixNano() +func Sample() int { + r := rand.New(rand.NewSource(Seed)) + return r.Int() +} +var Clock = Cutoff +func Stamp() { Clock() } +`, + `orders/orders.go`: `package orders +import ( + "example.com/workflows/billing" + "github.com/microsoft/durabletask-go/task" +) +func Fulfill(*task.OrchestrationContext) (any, error) { + billing.Cutoff() + return nil, nil +} +func Activity(task.ActivityContext) (any, error) { + billing.Cutoff() + return nil, nil +} +`, + `worker/worker.go`: `package worker +import ( + "example.com/workflows/billing" + "example.com/workflows/external" + "example.com/workflows/orders" + "github.com/microsoft/durabletask-go/task" +) +func register(r *task.TaskRegistry) { + _ = r.AddOrchestrator(orders.Fulfill) + _ = r.AddOrchestrator(local) + _ = r.AddActivity(orders.Activity) +} +type reader interface{ Read() } +var Handler = billing.Cutoff +func local(ctx *task.OrchestrationContext) (any, error) { + read := billing.Ledger[int]{}.Read + read() + ctx.Go(billing.Callback) + billing.Clean() + external.Clock() + ignore(func() { billing.Cutoff() }) + dynamic(billing.Ledger[int]{}) + Handler() + fn := billing.Cutoff + p := &fn + *p = billing.Clean + fn() + billing.Hook(func() {}).RunAndNext() + _ = billing.Sample() + billing.Stamp() + return nil, nil +} +func init() { billing.Seed, billing.Clock = 1, billing.Clean } +func ignore(func()) {} +func dynamic(r reader) { r.Read() } +`, + } { + path := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(contents), 0600); err != nil { + t.Fatal(err) + } + } + + tool := filepath.Join(dir, "orchestratorvet") + if runtime.GOOS == "windows" { + tool += ".exe" + } + env := append(os.Environ(), "GOWORK=off", "GO111MODULE=on") + build := exec.CommandContext(t.Context(), "go", "build", "-o", tool, ".") + build.Dir = filepath.Join("..", "..") + build.Env = env + if output, err := build.CombinedOutput(); err != nil { + t.Fatalf("build orchestratorvet: %v\n%s", err, output) + } + + for _, target := range []string{"./worker", "./..."} { + t.Run(target, func(t *testing.T) { + vet := exec.CommandContext(t.Context(), "go", "vet", "-vettool="+tool, target) + vet.Dir, vet.Env = dir, env + output, err := vet.CombinedOutput() + if err == nil { + t.Fatalf("expected replay hazards from %s", target) + } + got := string(output) + for _, want := range []string{ + "worker.go:9:24: example.com/workflows/orders.Fulfill -> example.com/workflows/billing.Cutoff -> example.com/workflows/billing.first -> example.com/workflows/billing.second: time.Now", + "worker.go:17:2: (example.com/workflows/billing.Ledger[T]).Read: os.Getenv", + "worker.go:18:9: example.com/workflows/billing.Callback: time.Now", + "worker.go:23:2: example.com/workflows/billing.Cutoff -> example.com/workflows/billing.first -> example.com/workflows/billing.second: time.Now", + } { + if !strings.Contains(got, want) { + t.Errorf("missing diagnostic %q in:\n%s", want, got) + } + } + if count := strings.Count(got, ".go:"); count != 4 { + t.Errorf("got %d diagnostic locations; want exactly 4:\n%s", count, got) + } + }) + } +} diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/index.go b/cmd/orchestratorvet/analysis/orchestratorgo/index.go index 3cf7eb07..a678c347 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/index.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/index.go @@ -11,14 +11,13 @@ import ( ) // packageIndex holds the whole-package declaration information the analyzer -// needs to follow call graphs without loading other packages. Everything it -// records is derived from the syntax and type information of a single -// [analysis.Pass], so the analyzer never depends on facts from dependencies. +// needs to follow calls without loading other packages. The index itself only +// uses the syntax and type information of a single [analysis.Pass]. type packageIndex struct { pass *analysis.Pass // functions maps a declared function or method object to its declaration. - functions map[types.Object]*ast.FuncDecl + functions map[*types.Func]*ast.FuncDecl // functionValues maps a variable or constant object to the expressions it is // initialized or assigned with. Objects with more than one recorded @@ -54,12 +53,16 @@ type packageIndex struct { // Reuse the ancestor stack across bodies rather than allocating per function. stack []ast.Node + + // summarizing is set while building facts for importers, which can + // reassign exported package variables before calling into this package. + summarizing bool } func newPackageIndex(pass *analysis.Pass) *packageIndex { index := &packageIndex{ pass: pass, - functions: make(map[types.Object]*ast.FuncDecl), + functions: make(map[*types.Func]*ast.FuncDecl), functionValues: make(map[types.Object][]ast.Expr), fileOf: make(map[ast.Node]*ast.File), enclosingFunc: make(map[ast.Node]ast.Node), @@ -79,7 +82,7 @@ func newPackageIndex(pass *analysis.Pass) *packageIndex { switch node := node.(type) { case *ast.FuncDecl: index.fileOf[node] = file - if object := pass.TypesInfo.Defs[node.Name]; object != nil { + if object, ok := pass.TypesInfo.Defs[node.Name].(*types.Func); ok { index.functions[object] = node } index.walkFunction(node, file, node.Body) @@ -108,14 +111,9 @@ func (index *packageIndex) walkFunction(owner ast.Node, file *ast.File, body *as if body == nil { return } - if parameters := funcType(owner).Params; parameters != nil { - for _, field := range parameters.List { - if isTaskRegistry(index.pass.TypesInfo.TypeOf(field.Type)) { - for _, name := range field.Names { - index.recordValue(index.pass.TypesInfo.Defs[name], nil) - } - } - } + index.recordUnknownInputs(funcType(owner).Params) + if decl, ok := owner.(*ast.FuncDecl); ok { + index.recordUnknownInputs(decl.Recv) } var registrations []*ast.CallExpr hasGoto := false @@ -152,6 +150,20 @@ func (index *packageIndex) walkFunction(owner ast.Node, file *ast.File, body *as } } +func (index *packageIndex) recordUnknownInputs(fields *ast.FieldList) { + if fields == nil { + return + } + for _, field := range fields.List { + typ := index.pass.TypesInfo.TypeOf(field.Type) + if mayHoldFunction(typ) || isTaskRegistry(typ) { + for _, name := range field.Names { + index.recordValue(index.pass.TypesInfo.Defs[name], nil) + } + } + } +} + // record captures the declaration facts the analyzer needs from one node. func (index *packageIndex) record(node ast.Node) { pass := index.pass @@ -217,6 +229,13 @@ func (index *packageIndex) record(node ast.Node) { } case *ast.UnaryExpr: if node.Op == token.AND { + if id, ok := ast.Unparen(node.X).(*ast.Ident); ok { + if variable, ok := pass.TypesInfo.ObjectOf(id).(*types.Var); ok { + if mayHoldFunction(variable.Type()) { + index.recordValue(variable, nil) + } + } + } index.recordRegistryEscape(node.X) } case *ast.ReturnStmt: @@ -266,6 +285,15 @@ func (index *packageIndex) recordRegistryEscape(expression ast.Expr) { } } +func mayHoldFunction(t types.Type) bool { + if t == nil { + return false + } + _, isFunction := t.Underlying().(*types.Signature) + _, isTypeParameter := types.Unalias(t).(*types.TypeParam) + return isFunction || isTypeParameter +} + // registrationScope accepts only an entire expression/assignment statement in // a sequential statement list. In particular, nearest-block matching would // conflate separate switch/select clauses and short-circuit operands. @@ -296,6 +324,11 @@ func (index *packageIndex) singleValue(object types.Object) ast.Expr { if object == nil { return nil } + if index.summarizing && index.isExportedPackageVar(object) { + // Importers can reassign an exported variable before calling a + // summarized function, without an assignment in this package. + return nil + } values := index.functionValues[object] if len(values) != 1 { return nil @@ -303,6 +336,11 @@ func (index *packageIndex) singleValue(object types.Object) ast.Expr { return values[0] } +func (index *packageIndex) isExportedPackageVar(object types.Object) bool { + v, ok := object.(*types.Var) + return ok && v.Exported() && v.Parent() == index.pass.Pkg.Scope() +} + // enclosingFunctionStack preserves captured context bindings when a reached // literal is checked separately from its enclosing functions. func (index *packageIndex) enclosingFunctionStack(node ast.Node) []ast.Node { @@ -316,12 +354,21 @@ func (index *packageIndex) enclosingFunctionStack(node ast.Node) []ast.Node { // resolveFunction returns the function declaration or literal that expression // evaluates to, or nil when the target cannot be proven statically. -func (index *packageIndex) resolveFunction(expression ast.Expr, seen map[types.Object]struct{}) ast.Node { +func (index *packageIndex) resolveFunction(expression ast.Expr) ast.Node { + return index.resolveTarget(expression, nil).local +} + +type functionTarget struct { + local ast.Node + imported *types.Func +} + +func (index *packageIndex) resolveTarget(expression ast.Expr, seen map[types.Object]struct{}) functionTarget { switch expression := expression.(type) { case *ast.FuncLit: - return expression + return functionTarget{local: expression} case *ast.ParenExpr: - return index.resolveFunction(expression.X, seen) + return index.resolveTarget(expression.X, seen) case *ast.Ident: return index.resolveObject(index.pass.TypesInfo.ObjectOf(expression), seen) case *ast.SelectorExpr: @@ -331,40 +378,46 @@ func (index *packageIndex) resolveFunction(expression ast.Expr, seen map[types.O return index.resolveObject(index.pass.TypesInfo.ObjectOf(expression.Sel), seen) case *ast.IndexExpr: // Instantiation of a generic function, such as helper[int]. - return index.resolveFunction(expression.X, seen) + return index.resolveTarget(expression.X, seen) case *ast.IndexListExpr: - return index.resolveFunction(expression.X, seen) + return index.resolveTarget(expression.X, seen) case *ast.CallExpr: // Conversions such as task.Orchestrator(fn) forward to their operand. if typeInfo, ok := index.pass.TypesInfo.Types[expression.Fun]; ok && typeInfo.IsType() && len(expression.Args) == 1 { - return index.resolveFunction(expression.Args[0], seen) + return index.resolveTarget(expression.Args[0], seen) } } - return nil + return functionTarget{} } -func (index *packageIndex) resolveObject(object types.Object, seen map[types.Object]struct{}) ast.Node { +func (index *packageIndex) resolveObject(object types.Object, seen map[types.Object]struct{}) functionTarget { if object == nil { - return nil + return functionTarget{} } - if function := index.functions[object]; function != nil { - return function + if function, ok := object.(*types.Func); ok { + if declaration := index.functions[function.Origin()]; declaration != nil { + return functionTarget{local: declaration} + } + if function.Pkg() != nil && function.Pkg() != index.pass.Pkg && function.Exported() { + return functionTarget{imported: function.Origin()} + } + return functionTarget{} } if seen == nil { seen = make(map[types.Object]struct{}) } if _, ok := seen[object]; ok { - return nil + return functionTarget{} } seen[object] = struct{}{} value := index.singleValue(object) if value == nil { // Unset, or reassigned more than once: the target is ambiguous. - return nil + return functionTarget{} } - return index.resolveFunction(value, seen) + return index.resolveTarget(value, seen) } // callee returns the function declaration or literal invoked by call when that @@ -381,7 +434,7 @@ func (index *packageIndex) callee(call *ast.CallExpr) ast.Node { return nil } } - return index.resolveFunction(call.Fun, nil) + return index.resolveFunction(call.Fun) } // staticFunc returns the function object an expression denotes, which may be a diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/reach.go b/cmd/orchestratorvet/analysis/orchestratorgo/reach.go index d78cb939..279a967e 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/reach.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/reach.go @@ -2,6 +2,7 @@ package orchestratorgo import ( "go/ast" + "go/token" "golang.org/x/tools/go/analysis" ) @@ -43,12 +44,24 @@ func reachableFunctions(index *packageIndex, roots []ast.Node) *reachSet { current := reach.order[next] forEachOwnedCall(current, func(call *ast.CallExpr) { add(index.callee(call)) - add(index.resolveFunction(orchestrationGoCallback(index.pass, call), nil)) + add(index.resolveFunction(orchestrationGoCallback(index.pass, call))) }) } return reach } +func (index *packageIndex) forEachTarget(node ast.Node, visit func(token.Pos, functionTarget)) { + forEachOwnedCall(node, func(call *ast.CallExpr) { + if target := index.resolveTarget(call.Fun, nil); target.local != nil || target.imported != nil { + visit(call.Fun.Pos(), target) + } + if callback := orchestrationGoCallback(index.pass, call); callback != nil { + target := index.resolveTarget(callback, nil) + visit(callback.Pos(), target) + } + }) +} + // forEachOwnedCall visits every call expression lexically contained in the // current function's own body, including calls in raw go and defer statements // but NOT calls written inside a nested function literal. Those literals are diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/registration.go b/cmd/orchestratorvet/analysis/orchestratorgo/registration.go index bb2ea74d..f62cc332 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/registration.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/registration.go @@ -3,6 +3,7 @@ package orchestratorgo import ( "go/ast" "go/constant" + "go/token" "go/types" "strings" @@ -61,7 +62,13 @@ type registrySet struct { // declarations, used to detect direct orchestrator invocation. orchestratorObjects map[types.Object]string // roots holds every function node registered as an orchestrator. - roots []ast.Node + roots []ast.Node + importedRoots []importedRoot +} + +type importedRoot struct { + pos token.Pos + function *types.Func } func (set *registrySet) registered(kind registrationKind, name string) bool { @@ -123,7 +130,8 @@ func collectRegistrations(pass *analysis.Pass, index *packageIndex) *registrySet ) continue } - handlerNode := index.resolveFunction(handler, nil) + target := index.resolveTarget(handler, nil) + handlerNode := target.local handlerObj := handlerObject(pass, handler) // rejected records that this call provably fails, so it contributes no @@ -172,6 +180,9 @@ func collectRegistrations(pass *analysis.Pass, index *packageIndex) *registrySet seenRoots[handlerNode] = true set.roots = append(set.roots, handlerNode) } + if shape.kind == orchestratorKind && target.imported != nil && !rejected { + set.importedRoots = append(set.importedRoots, importedRoot{handler.Pos(), target.imported}) + } } return set } diff --git a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/callgraph/callgraph.go b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/callgraph/callgraph.go index a1ac513b..b0c1aa98 100644 --- a/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/callgraph/callgraph.go +++ b/cmd/orchestratorvet/analysis/orchestratorgo/testdata/src/callgraph/callgraph.go @@ -113,6 +113,11 @@ func ambiguousVariable(ctx *task.OrchestrationContext) (any, error) { return reassignedHelper(), nil } +// ExportedOrchestrator is registered from its single package-level value. +var ExportedOrchestrator = func(ctx *task.OrchestrationContext) (any, error) { + return time.Now(), nil // want `time\.Now is not deterministic in an orchestrator` +} + func register() { registry := task.NewTaskRegistry() _ = registry.AddOrchestrator(nestedHelpers) @@ -123,4 +128,5 @@ func register() { _ = registry.AddOrchestrator(firstSharer) _ = registry.AddOrchestrator(secondSharer) _ = registry.AddOrchestrator(ambiguousVariable) + _ = registry.AddOrchestratorN("ExportedOrchestrator", ExportedOrchestrator) }