| index c38687d0d..3d9bf6d59 100644 |
| --- a/internal/activator/heldlegs_guard_test.go |
| +++ b/internal/activator/heldlegs_guard_test.go |
| @@ -17,23 +17,68 @@ package activator |
| // Stop, and the package's only binding (bindClaimProducer) passes the |
| // pre-stop that cancels the entry's legs (refuseHeldLegsOn). |
| // |
| +// Cancellation counts only as a synchronous statement in an approved |
| +// shape: never deferred, started as a goroutine, wrapped in a function |
| +// literal, or under a condition other than the approved one. Aliases are |
| +// refused: actStopping appears only in comparisons, case clauses and |
| +// beginStopLocked's one assignment; actEntry.state is only ever assigned a |
| +// constant; a.entries is used only by key, range, len, a nil check, its |
| +// make, or the guarded delete. |
| +// |
| // TestHeldLegTransitionSites pins those facts over the package's non-test |
| // files, by type (go/types through loadVerbGuardPackage), so a wake's, |
| -// a member's or a rootfs worker's proc field is not an entry's. The swap |
| -// simulation (TestSwapInvariants, I4) checks the property itself. |
| +// a member's or a rootfs worker's proc field is not an entry's, and |
| +// checks that each refused shape (heldGuardFixtures) is refused. |
| +// TestHeldAdmissionTouchesNoActivity pins that the held admission path |
| +// reaches no activity. The swap simulation (TestSwapInvariants, I4 and I5) |
| +// checks the properties themselves. |
| |
| import ( |
| + "bytes" |
| "fmt" |
| "go/ast" |
| + "go/parser" |
| + "go/printer" |
| "go/token" |
| "go/types" |
| "slices" |
| "strings" |
| "testing" |
| + |
| + "golang.org/x/tools/go/packages" |
| ) |
| |
| const heldGuardSpec = "edge-held streams spec §3.2" |
| |
| +// heldGuardTargets names the functions the guard's per-function rules |
| +// apply to. The real package uses heldGuardReal; a fixture names its own |
| +// function in the slot it exercises. |
| +type heldGuardTargets struct { |
| + beginStop, install, bindProducer, bindClaim, refuse string |
| +} |
| + |
| +var heldGuardReal = heldGuardTargets{ |
| + beginStop: "Service.beginStopLocked", |
| + install: "Service.installProcLocked", |
| + bindProducer: "claimProcess.bindProducer", |
| + bindClaim: "Service.bindClaimProducer", |
| + refuse: "Service.refuseHeldLegsOn", |
| +} |
| + |
| +// The approved control-flow shapes, as go/printer renders them with |
| +// whitespace collapsed. Any other shape is not cancellation evidence. |
| +const ( |
| + // installProcLocked's generation-change cancel (Task 1). |
| + heldShapeInstall = "if e.gen.N != g.N { a.cancelHeldLegsLocked(e, e.gen.N) }" |
| + // bindClaimProducer's beforeStop argument. |
| + heldShapeBindClaimArg = "func() { a.refuseHeldLegsOn(e, p) }" |
| + // refuseHeldLegsOn's cancel of the entries p serves. |
| + heldShapeRefuse = "for _, x := range []*actEntry{e, a.entries[e.host]} { if x != nil && x.proc == Proc(p) { a.cancelHeldLegsLocked(x, 0) } }" |
| +) |
| + |
| +// heldShapePreStop are the statements that run bindProducer's pre-stop. |
| +var heldShapePreStop = []string{"beforeStop()", "if beforeStop != nil { beforeStop() }"} |
| + |
| // heldGuardFunc is one function declaration the guard reads: its name as |
| // "Recv.Name" (or "Name"), and its body. |
| type heldGuardFunc struct { |
| @@ -42,6 +87,34 @@ type heldGuardFunc struct { |
| decl *ast.FuncDecl |
| } |
| |
| +func heldGuardFuncs(fset *token.FileSet, files map[string]*ast.File) []heldGuardFunc { |
| + var funcs []heldGuardFunc |
| + for base, f := range files { |
| + for _, d := range f.Decls { |
| + fd, ok := d.(*ast.FuncDecl) |
| + if !ok || fd.Body == nil { |
| + continue |
| + } |
| + name := fd.Name.Name |
| + if fd.Recv != nil && len(fd.Recv.List) == 1 { |
| + name = receiverTypeName(fd.Recv.List[0].Type) + "." + name |
| + } |
| + funcs = append(funcs, heldGuardFunc{file: base, name: name, decl: fd}) |
| + } |
| + } |
| + slices.SortFunc(funcs, func(x, y heldGuardFunc) int { return strings.Compare(x.file+x.name, y.file+y.name) }) |
| + return funcs |
| +} |
| + |
| +// heldGuardRender is n as go/printer prints it, whitespace collapsed. |
| +func heldGuardRender(fset *token.FileSet, n ast.Node) string { |
| + var b bytes.Buffer |
| + if err := printer.Fprint(&b, fset, n); err != nil { |
| + return "<unprintable>" |
| + } |
| + return strings.Join(strings.Fields(b.String()), " ") |
| +} |
| + |
| // heldGuardCalls reports whether call is a call of a method or function |
| // named name (x.name(…) or name(…)). |
| func heldGuardCalls(call *ast.CallExpr, name string) bool { |
| @@ -54,8 +127,9 @@ func heldGuardCalls(call *ast.CallExpr, name string) bool { |
| return false |
| } |
| |
| -// heldGuardCancelAll reports whether stmt is exactly a statement |
| -// x.cancelHeldLegsLocked(…, 0). |
| +// heldGuardCancelAll reports whether stmt is exactly the synchronous |
| +// statement x.cancelHeldLegsLocked(…, 0): not deferred, not a goroutine, |
| +// not inside a literal or a branch. |
| func heldGuardCancelAll(stmt ast.Stmt) bool { |
| es, ok := stmt.(*ast.ExprStmt) |
| if !ok { |
| @@ -91,6 +165,30 @@ func heldGuardNamed(t types.Type, name string) bool { |
| return ok && n.Obj().Name() == name && n.Obj().Pkg() != nil && n.Obj().Pkg().Name() == "activator" |
| } |
| |
| +// heldGuardField reports whether se selects field of the package's type. |
| +func heldGuardField(info *types.Info, se *ast.SelectorExpr, typ, field string) bool { |
| + if se.Sel.Name != field { |
| + return false |
| + } |
| + sel := info.Selections[se] |
| + return sel != nil && sel.Kind() == types.FieldVal && heldGuardNamed(sel.Recv(), typ) |
| +} |
| + |
| +// heldGuardInspect is ast.Inspect with each node's ancestors (innermost |
| +// last). |
| +func heldGuardInspect(root ast.Node, f func(n ast.Node, stack []ast.Node)) { |
| + var stack []ast.Node |
| + ast.Inspect(root, func(n ast.Node) bool { |
| + if n == nil { |
| + stack = stack[:len(stack)-1] |
| + return false |
| + } |
| + f(n, stack) |
| + stack = append(stack, n) |
| + return true |
| + }) |
| +} |
| + |
| // heldGuardStmtLists is every statement list in body (blocks, case and |
| // select clauses), so a delete's predecessor is read in its own block. |
| func heldGuardStmtLists(body ast.Node) [][]ast.Stmt { |
| @@ -109,34 +207,38 @@ func heldGuardStmtLists(body ast.Node) [][]ast.Stmt { |
| return out |
| } |
| |
| -// heldGuardDeleteEntries reports whether stmt is delete(x.entries, …) with |
| -// x a *Service. |
| -func heldGuardDeleteEntries(info *types.Info, stmt ast.Stmt) bool { |
| - es, ok := stmt.(*ast.ExprStmt) |
| - if !ok { |
| - return false |
| - } |
| - call, ok := es.X.(*ast.CallExpr) |
| - if !ok || len(call.Args) != 2 { |
| +// heldGuardIsDelete reports whether call is the builtin delete. |
| +func heldGuardIsDelete(info *types.Info, call *ast.CallExpr) bool { |
| + id, ok := call.Fun.(*ast.Ident) |
| + if !ok || id.Name != "delete" { |
| return false |
| } |
| - return heldGuardIsDeleteEntries(info, call) |
| + _, builtin := info.Uses[id].(*types.Builtin) |
| + return builtin |
| } |
| |
| -func heldGuardIsDeleteEntries(info *types.Info, call *ast.CallExpr) bool { |
| +// heldGuardIsBuiltin reports whether call is the builtin name. |
| +func heldGuardIsBuiltin(info *types.Info, call *ast.CallExpr, name string) bool { |
| id, ok := call.Fun.(*ast.Ident) |
| - if !ok { |
| + if !ok || id.Name != name { |
| return false |
| } |
| - if _, builtin := info.Uses[id].(*types.Builtin); !builtin || id.Name != "delete" || len(call.Args) != 2 { |
| - return false |
| + _, builtin := info.Uses[id].(*types.Builtin) |
| + return builtin |
| +} |
| + |
| +// heldGuardIsConst reports whether x is an identifier naming a package |
| +// constant, and which. |
| +func heldGuardIsConst(info *types.Info, x ast.Expr) (string, bool) { |
| + id, ok := x.(*ast.Ident) |
| + if !ok { |
| + return "", false |
| } |
| - se, ok := call.Args[0].(*ast.SelectorExpr) |
| - if !ok || se.Sel.Name != "entries" { |
| - return false |
| + c, ok := info.Uses[id].(*types.Const) |
| + if !ok || c.Pkg() == nil || c.Parent() != c.Pkg().Scope() { |
| + return "", false |
| } |
| - sel := info.Selections[se] |
| - return sel != nil && sel.Kind() == types.FieldVal && heldGuardNamed(sel.Recv(), "Service") |
| + return c.Name(), true |
| } |
| |
| // heldGuardReport is the guard's result over a set of functions. |
| @@ -146,128 +248,203 @@ type heldGuardReport struct { |
| stoppingSites, procSites, deleteSites, otherProcSites int |
| otherProcs []string |
| beginStopFirst, installCancelsFirst, producerPreStop bool |
| + bindClaimSeen, refuseSeen bool |
| } |
| |
| -func heldGuardRun(fset *token.FileSet, info *types.Info, funcs []heldGuardFunc) heldGuardReport { |
| +func heldGuardRun(fset *token.FileSet, info *types.Info, funcs []heldGuardFunc, tg heldGuardTargets) heldGuardReport { |
| var r heldGuardReport |
| at := func(fn heldGuardFunc, pos token.Pos, what string) { |
| p := fset.Position(pos) |
| r.violations = append(r.violations, fmt.Sprintf("%s:%d (%s): %s; see %s", fn.file, p.Line, fn.name, what, heldGuardSpec)) |
| } |
| - isStopping := func(x ast.Expr) bool { |
| - id, ok := x.(*ast.Ident) |
| - if !ok { |
| - return false |
| - } |
| - c, ok := info.Uses[id].(*types.Const) |
| - return ok && c.Name() == "actStopping" && c.Parent() == c.Pkg().Scope() |
| - } |
| for _, fn := range funcs { |
| body := fn.decl.Body |
| - calls := 0 |
| - ast.Inspect(body, func(n ast.Node) bool { |
| + topLevel := func(s ast.Stmt) bool { return slices.Contains(body.List, s) } |
| + heldGuardInspect(body, func(n ast.Node, stack []ast.Node) { |
| + var parent ast.Node |
| + if len(stack) > 0 { |
| + parent = stack[len(stack)-1] |
| + } |
| switch v := n.(type) { |
| + case *ast.Ident: |
| + // actStopping: a comparison operand, a case label, or |
| + // beginStopLocked's one assignment. Any other use (an |
| + // alias, a helper's argument, a literal) could move an |
| + // entry to stopping without the cancel. |
| + if name, ok := heldGuardIsConst(info, v); !ok || name != "actStopping" { |
| + return |
| + } |
| + switch p := parent.(type) { |
| + case *ast.BinaryExpr: |
| + if p.Op == token.EQL || p.Op == token.NEQ { |
| + return |
| + } |
| + case *ast.CaseClause: |
| + return |
| + case *ast.AssignStmt: |
| + if fn.name == tg.beginStop && topLevel(p) && p.Tok == token.ASSIGN && len(p.Lhs) == 1 && len(p.Rhs) == 1 && p.Rhs[0] == v { |
| + if se, ok := p.Lhs[0].(*ast.SelectorExpr); ok && heldGuardField(info, se, "actEntry", "state") { |
| + r.stoppingSites++ |
| + return |
| + } |
| + } |
| + } |
| + r.stoppingSites++ |
| + at(fn, v.Pos(), "uses actStopping outside a comparison, a case label or beginStopLocked's assignment (an alias or a helper skips the cancel)") |
| case *ast.AssignStmt: |
| for i, lhs := range v.Lhs { |
| se, ok := lhs.(*ast.SelectorExpr) |
| if !ok { |
| continue |
| } |
| - // actStopping into any .state field. |
| - if se.Sel.Name == "state" && len(v.Rhs) == len(v.Lhs) && isStopping(v.Rhs[i]) { |
| - r.stoppingSites++ |
| - if fn.name != "Service.beginStopLocked" { |
| - at(fn, v.Pos(), "assigns actStopping outside beginStopLocked") |
| + // actEntry.state takes only a named constant, so a |
| + // variable cannot carry actStopping in. |
| + if heldGuardField(info, se, "actEntry", "state") { |
| + if len(v.Rhs) != len(v.Lhs) { |
| + at(fn, v.Pos(), "assigns actEntry.state from a multi-value expression") |
| + } else if _, ok := heldGuardIsConst(info, v.Rhs[i]); !ok { |
| + at(fn, v.Pos(), "assigns actEntry.state something other than a named constant") |
| } |
| } |
| // The proc field of an actEntry; other types' proc |
| // fields (a wake's, a member's, a rootfs worker's) are |
| // not an entry's. |
| - if se.Sel.Name == "proc" && v.Tok != token.DEFINE { |
| - sel := info.Selections[se] |
| - if sel == nil || sel.Kind() != types.FieldVal { |
| - at(fn, v.Pos(), "assigns a .proc the guard cannot resolve by type") |
| - continue |
| - } |
| - if !heldGuardNamed(sel.Recv(), "actEntry") { |
| - r.otherProcSites++ |
| - r.otherProcs = append(r.otherProcs, fmt.Sprintf("%s:%d %s (%s)", fn.file, fset.Position(v.Pos()).Line, fn.name, sel.Recv())) |
| - continue |
| - } |
| - r.procSites++ |
| - if fn.name != "Service.installProcLocked" { |
| - at(fn, v.Pos(), "assigns actEntry.proc outside installProcLocked") |
| - continue |
| - } |
| - // installProcLocked cancels before the assignment: |
| - // a statement of its body ahead of this one calls |
| - // cancelHeldLegsLocked. |
| - cancelled := false |
| - for _, s := range body.List { |
| - if s.Pos() >= v.Pos() { |
| - break |
| - } |
| - if heldGuardContainsCall(s, "cancelHeldLegsLocked") { |
| - cancelled = true |
| - } |
| - } |
| - if cancelled { |
| - r.installCancelsFirst = true |
| - } else { |
| - at(fn, v.Pos(), "installProcLocked assigns actEntry.proc with no cancelHeldLegsLocked call before it") |
| + if se.Sel.Name != "proc" || v.Tok == token.DEFINE { |
| + continue |
| + } |
| + sel := info.Selections[se] |
| + if sel == nil || sel.Kind() != types.FieldVal { |
| + at(fn, v.Pos(), "assigns a .proc the guard cannot resolve by type") |
| + continue |
| + } |
| + if !heldGuardNamed(sel.Recv(), "actEntry") { |
| + r.otherProcSites++ |
| + r.otherProcs = append(r.otherProcs, fmt.Sprintf("%s:%d %s (%s)", fn.file, fset.Position(v.Pos()).Line, fn.name, sel.Recv())) |
| + continue |
| + } |
| + r.procSites++ |
| + if fn.name != tg.install { |
| + at(fn, v.Pos(), "assigns actEntry.proc outside installProcLocked") |
| + continue |
| + } |
| + // installProcLocked: the write is a top-level statement, |
| + // and an earlier top-level statement is exactly the |
| + // approved generation-change cancel. |
| + idx := slices.Index(body.List, ast.Stmt(v)) |
| + ok = false |
| + for _, s := range body.List[:max(idx, 0)] { |
| + if heldGuardRender(fset, s) == heldShapeInstall { |
| + ok = true |
| } |
| } |
| + if idx >= 0 && ok { |
| + r.installCancelsFirst = true |
| + } else { |
| + at(fn, v.Pos(), "installProcLocked writes actEntry.proc without the approved cancel ("+heldShapeInstall+") as an earlier top-level statement") |
| + } |
| } |
| case *ast.CompositeLit: |
| - // An entry built already stopping skips beginStopLocked too. |
| if heldGuardNamed(info.TypeOf(v), "actEntry") { |
| for _, elt := range v.Elts { |
| - if kv, ok := elt.(*ast.KeyValueExpr); ok { |
| - if id, ok := kv.Key.(*ast.Ident); ok && id.Name == "state" && isStopping(kv.Value) { |
| - r.stoppingSites++ |
| - at(fn, v.Pos(), "builds an actEntry in actStopping outside beginStopLocked") |
| + kv, ok := elt.(*ast.KeyValueExpr) |
| + if !ok { |
| + continue |
| + } |
| + if id, ok := kv.Key.(*ast.Ident); ok && id.Name == "state" { |
| + if _, ok := heldGuardIsConst(info, kv.Value); !ok { |
| + at(fn, v.Pos(), "builds an actEntry whose state is not a named constant") |
| } |
| } |
| } |
| } |
| - case *ast.CallExpr: |
| - if heldGuardIsDeleteEntries(info, v) { |
| - r.deleteSites++ |
| - calls++ |
| + case *ast.SelectorExpr: |
| + // a.entries: by key, range, len, a nil check, its make, or |
| + // the guarded delete. Any other use (an alias, a helper's |
| + // argument) can remove an entry without cancelling its legs. |
| + if !heldGuardField(info, v, "Service", "entries") { |
| + return |
| + } |
| + switch p := parent.(type) { |
| + case *ast.IndexExpr: |
| + if p.X == v { |
| + return |
| + } |
| + case *ast.RangeStmt: |
| + if p.X == v { |
| + return |
| + } |
| + case *ast.BinaryExpr: |
| + if p.Op == token.EQL || p.Op == token.NEQ { |
| + other := p.X |
| + if other == v { |
| + other = p.Y |
| + } |
| + if id, ok := other.(*ast.Ident); ok && id.Name == "nil" { |
| + return |
| + } |
| + } |
| + case *ast.AssignStmt: |
| + for i, lhs := range p.Lhs { |
| + if lhs == v && len(p.Rhs) == len(p.Lhs) { |
| + if c, ok := p.Rhs[i].(*ast.CallExpr); ok && heldGuardIsBuiltin(info, c, "make") { |
| + return |
| + } |
| + } |
| + } |
| + case *ast.CallExpr: |
| + if heldGuardIsBuiltin(info, p, "len") { |
| + return |
| + } |
| + if heldGuardIsDelete(info, p) && len(p.Args) == 2 && p.Args[0] == v { |
| + r.deleteSites++ |
| + // The delete is checked below as a statement; one |
| + // that is not a plain statement has no predecessor. |
| + if len(stack) < 2 { |
| + at(fn, p.Pos(), "delete(a.entries, …) is not a plain statement") |
| + return |
| + } |
| + if _, ok := stack[len(stack)-2].(*ast.ExprStmt); !ok { |
| + at(fn, p.Pos(), "delete(a.entries, …) is not a plain statement (deferred or started as a goroutine)") |
| + } |
| + return |
| + } |
| } |
| + at(fn, v.Pos(), "uses a.entries other than by key, range, len, a nil check, its make or the guarded delete (an alias or a helper can remove an entry without cancelling its legs)") |
| } |
| - return true |
| }) |
| // Every delete(a.entries, …) statement is immediately preceded in |
| - // its own block by cancelHeldLegsLocked(…, 0). |
| - seen := 0 |
| + // its own block by the synchronous cancelHeldLegsLocked(…, 0). |
| for _, list := range heldGuardStmtLists(body) { |
| for i, s := range list { |
| - if !heldGuardDeleteEntries(info, s) { |
| + es, ok := s.(*ast.ExprStmt) |
| + if !ok { |
| + continue |
| + } |
| + call, ok := es.X.(*ast.CallExpr) |
| + if !ok || !heldGuardIsDelete(info, call) || len(call.Args) != 2 { |
| + continue |
| + } |
| + se, ok := call.Args[0].(*ast.SelectorExpr) |
| + if !ok || !heldGuardField(info, se, "Service", "entries") { |
| continue |
| } |
| - seen++ |
| if i == 0 || !heldGuardCancelAll(list[i-1]) { |
| - at(fn, s.Pos(), "delete(a.entries, …) not immediately preceded by cancelHeldLegsLocked(…, 0) in the same block") |
| + at(fn, s.Pos(), "delete(a.entries, …) not immediately preceded by a synchronous cancelHeldLegsLocked(…, 0) in the same block") |
| } |
| } |
| } |
| - // A delete(a.entries, …) that is not a plain statement (a deferred |
| - // one, say) has no predecessor to check: refuse it. |
| - if seen != calls { |
| - at(fn, fn.decl.Pos(), fmt.Sprintf("%d delete(a.entries, …) call(s) are not plain statements the guard can check", calls-seen)) |
| - } |
| // beginStopLocked's first statement cancels every leg. |
| - if fn.name == "Service.beginStopLocked" { |
| + if fn.name == tg.beginStop { |
| if len(body.List) == 0 || !heldGuardCancelAll(body.List[0]) { |
| at(fn, fn.decl.Pos(), "beginStopLocked's first statement is not cancelHeldLegsLocked(e, 0)") |
| } else { |
| r.beginStopFirst = true |
| } |
| } |
| - // The claim producer's cleanup: bindProducer's goroutine calls |
| - // beforeStop before its first Stop. |
| - if fn.name == "claimProcess.bindProducer" { |
| + // The claim producer's cleanup: in bindProducer's goroutine, a |
| + // top-level statement that runs beforeStop comes before the first |
| + // top-level statement holding a Stop. |
| + if fn.name == tg.bindProducer { |
| var goLit *ast.FuncLit |
| ast.Inspect(body, func(n ast.Node) bool { |
| if g, ok := n.(*ast.GoStmt); ok { |
| @@ -280,84 +457,79 @@ func heldGuardRun(fset *token.FileSet, info *types.Info, funcs []heldGuardFunc) |
| if goLit == nil { |
| at(fn, fn.decl.Pos(), "bindProducer starts no cleanup goroutine the guard can read") |
| } else { |
| - var pre, stop token.Pos |
| - ast.Inspect(goLit.Body, func(n ast.Node) bool { |
| - c, ok := n.(*ast.CallExpr) |
| - if !ok { |
| - return true |
| - } |
| - if id, ok := c.Fun.(*ast.Ident); ok && id.Name == "beforeStop" && pre == token.NoPos { |
| - pre = c.Pos() |
| + pre, stop := -1, -1 |
| + for i, s := range goLit.Body.List { |
| + if stop < 0 && heldGuardContainsCall(s, "Stop") { |
| + stop = i |
| } |
| - if se, ok := c.Fun.(*ast.SelectorExpr); ok && se.Sel.Name == "Stop" && stop == token.NoPos { |
| - stop = c.Pos() |
| + if pre < 0 && slices.Contains(heldShapePreStop, heldGuardRender(fset, s)) { |
| + pre = i |
| } |
| - return true |
| - }) |
| + } |
| switch { |
| - case stop == token.NoPos: |
| + case stop < 0: |
| at(fn, goLit.Pos(), "bindProducer's cleanup goroutine has no Stop the guard can find") |
| - case pre == token.NoPos || pre > stop: |
| - at(fn, stop, "bindProducer's cleanup goroutine calls Stop before beforeStop (the held-leg pre-stop)") |
| + case pre < 0 || pre > stop: |
| + at(fn, goLit.Body.List[stop].Pos(), "bindProducer's cleanup goroutine reaches Stop with no synchronous beforeStop statement ahead of it") |
| default: |
| r.producerPreStop = true |
| } |
| } |
| } |
| // Every binding of a claim producer goes through bindClaimProducer, |
| - // whose beforeStop is refuseHeldLegsOn. |
| + // whose beforeStop is exactly the refuseHeldLegsOn literal. |
| ast.Inspect(body, func(n ast.Node) bool { |
| c, ok := n.(*ast.CallExpr) |
| if !ok || !heldGuardCalls(c, "bindProducer") { |
| return true |
| } |
| - if fn.name != "Service.bindClaimProducer" { |
| + if fn.name != tg.bindClaim { |
| at(fn, c.Pos(), "binds a claim producer outside bindClaimProducer (no held-leg pre-stop)") |
| - } else if len(c.Args) != 2 || !heldGuardContainsCall(c.Args[1], "refuseHeldLegsOn") { |
| - at(fn, c.Pos(), "bindClaimProducer's beforeStop does not call refuseHeldLegsOn") |
| + } else if len(c.Args) != 2 || heldGuardRender(fset, c.Args[1]) != heldShapeBindClaimArg { |
| + at(fn, c.Pos(), "bindClaimProducer's beforeStop is not exactly "+heldShapeBindClaimArg) |
| + } else { |
| + r.bindClaimSeen = true |
| } |
| return true |
| }) |
| - // refuseHeldLegsOn cancels every leg. |
| - if fn.name == "Service.refuseHeldLegsOn" { |
| + // refuseHeldLegsOn cancels in the approved loop, as a top-level |
| + // statement. |
| + if fn.name == tg.refuse { |
| found := false |
| - ast.Inspect(body, func(n ast.Node) bool { |
| - if es, ok := n.(*ast.ExprStmt); ok && heldGuardCancelAll(es) { |
| + for _, s := range body.List { |
| + if heldGuardRender(fset, s) == heldShapeRefuse { |
| found = true |
| } |
| - return !found |
| - }) |
| - if !found { |
| - at(fn, fn.decl.Pos(), "refuseHeldLegsOn does not call cancelHeldLegsLocked(…, 0)") |
| + } |
| + if found { |
| + r.refuseSeen = true |
| + } else { |
| + at(fn, fn.decl.Pos(), "refuseHeldLegsOn does not cancel in the approved shape ("+heldShapeRefuse+")") |
| } |
| } |
| } |
| return r |
| } |
| |
| -func TestHeldLegTransitionSites(t *testing.T) { |
| - pkg, err := loadVerbGuardPackage() |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| - var funcs []heldGuardFunc |
| +// heldGuardRealFiles is the package's own non-test files, guard fixtures |
| +// left out. |
| +func heldGuardRealFiles(pkg *packages.Package) map[string]*ast.File { |
| + out := map[string]*ast.File{} |
| for base, f := range packageFiles(pkg) { |
| if strings.HasPrefix(base, verbGuardFixturePrefix) || strings.HasSuffix(base, "_test.go") { |
| continue |
| } |
| - for _, d := range f.Decls { |
| - fd, ok := d.(*ast.FuncDecl) |
| - if !ok || fd.Body == nil { |
| - continue |
| - } |
| - name := fd.Name.Name |
| - if fd.Recv != nil && len(fd.Recv.List) == 1 { |
| - name = receiverTypeName(fd.Recv.List[0].Type) + "." + name |
| - } |
| - funcs = append(funcs, heldGuardFunc{file: base, name: name, decl: fd}) |
| - } |
| + out[base] = f |
| + } |
| + return out |
| +} |
| + |
| +func TestHeldLegTransitionSites(t *testing.T) { |
| + pkg, err := loadVerbGuardPackage() |
| + if err != nil { |
| + t.Fatal(err) |
| } |
| - r := heldGuardRun(pkg.Fset, pkg.TypesInfo, funcs) |
| + r := heldGuardRun(pkg.Fset, pkg.TypesInfo, heldGuardFuncs(pkg.Fset, heldGuardRealFiles(pkg)), heldGuardReal) |
| for _, v := range r.violations { |
| t.Error(v) |
| } |
| @@ -371,8 +543,8 @@ func TestHeldLegTransitionSites(t *testing.T) { |
| if r.deleteSites < 4 { |
| t.Errorf("the guard saw %d delete(a.entries, …) sites, want at least the 4 known: it resolves nothing", r.deleteSites) |
| } |
| - if !r.producerPreStop { |
| - t.Error("the guard did not find bindProducer's pre-stop ahead of its Stop: it resolves nothing") |
| + if !r.producerPreStop || !r.bindClaimSeen || !r.refuseSeen { |
| + t.Errorf("the guard did not find the claim producer's pre-stop (goroutine %v, binding %v, refuse %v): it resolves nothing", r.producerPreStop, r.bindClaimSeen, r.refuseSeen) |
| } |
| // Receiver-awareness control: other types' proc fields exist and were |
| // told apart from an entry's. |
| @@ -382,4 +554,392 @@ func TestHeldLegTransitionSites(t *testing.T) { |
| slices.Sort(r.otherProcs) |
| t.Logf("held-leg transition sites: %d actStopping, %d actEntry.proc, %d delete(a.entries); other types' proc writes left alone: %s", |
| r.stoppingSites, r.procSites, r.deleteSites, strings.Join(r.otherProcs, "; ")) |
| + |
| + // The refused shapes: each fixture function, read as the target its |
| + // row names, must be refused with the given text; the clean ones must |
| + // pass. |
| + info, files := heldGuardFixturePackage(t, pkg) |
| + byName := map[string]heldGuardFunc{} |
| + for _, fn := range heldGuardFuncs(pkg.Fset, files) { |
| + byName[fn.name] = fn |
| + } |
| + for _, fx := range heldGuardFixtures { |
| + t.Run(fx.fn, func(t *testing.T) { |
| + fn, ok := byName[fx.fn] |
| + if !ok { |
| + t.Fatalf("fixture function %s not found", fx.fn) |
| + } |
| + got := heldGuardRun(pkg.Fset, info, []heldGuardFunc{fn}, fx.tg).violations |
| + if fx.want == "" { |
| + if len(got) > 0 { |
| + t.Fatalf("the guard refused a clean shape:\n%s", strings.Join(got, "\n")) |
| + } |
| + return |
| + } |
| + if !slices.ContainsFunc(got, func(v string) bool { return strings.Contains(v, fx.want) }) { |
| + t.Fatalf("the guard did not refuse %s with %q; it reported:\n%s", fx.fn, fx.want, strings.Join(got, "\n")) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// heldGuardFixture is one refused (or, with want "", accepted) shape: the |
| +// fixture function, the target slot it is read as, and the text its |
| +// violation must carry. |
| +type heldGuardFixture struct { |
| + fn string |
| + tg heldGuardTargets |
| + want string |
| +} |
| + |
| +func heldGuardAs(slot, name string) heldGuardTargets { |
| + tg := heldGuardReal |
| + switch slot { |
| + case "install": |
| + tg.install = name |
| + case "bindProducer": |
| + tg.bindProducer = name |
| + case "bindClaim": |
| + tg.bindClaim = name |
| + case "beginStop": |
| + tg.beginStop = name |
| + } |
| + return tg |
| +} |
| + |
| +var heldGuardFixtures = []heldGuardFixture{ |
| + // bindProducer's pre-stop: deferred, as a goroutine, in an uncalled |
| + // literal, under a false branch; and the approved shape. |
| + {"claimProcess.heldFixPreStopDefer", heldGuardAs("bindProducer", "claimProcess.heldFixPreStopDefer"), "reaches Stop with no synchronous beforeStop"}, |
| + {"claimProcess.heldFixPreStopGo", heldGuardAs("bindProducer", "claimProcess.heldFixPreStopGo"), "reaches Stop with no synchronous beforeStop"}, |
| + {"claimProcess.heldFixPreStopClosure", heldGuardAs("bindProducer", "claimProcess.heldFixPreStopClosure"), "reaches Stop with no synchronous beforeStop"}, |
| + {"claimProcess.heldFixPreStopFalse", heldGuardAs("bindProducer", "claimProcess.heldFixPreStopFalse"), "reaches Stop with no synchronous beforeStop"}, |
| + {"claimProcess.heldFixPreStopClean", heldGuardAs("bindProducer", "claimProcess.heldFixPreStopClean"), ""}, |
| + // bindClaimProducer's argument: the pre-stop started as a goroutine. |
| + {"Service.heldFixBindGo", heldGuardAs("bindClaim", "Service.heldFixBindGo"), "beforeStop is not exactly"}, |
| + // installProcLocked's cancel: deferred, as a goroutine, in a literal, |
| + // under a false branch, nested with the write; and the approved shape. |
| + {"Service.heldFixInstallDefer", heldGuardAs("install", "Service.heldFixInstallDefer"), "without the approved cancel"}, |
| + {"Service.heldFixInstallGo", heldGuardAs("install", "Service.heldFixInstallGo"), "without the approved cancel"}, |
| + {"Service.heldFixInstallClosure", heldGuardAs("install", "Service.heldFixInstallClosure"), "without the approved cancel"}, |
| + {"Service.heldFixInstallFalse", heldGuardAs("install", "Service.heldFixInstallFalse"), "without the approved cancel"}, |
| + {"Service.heldFixInstallNested", heldGuardAs("install", "Service.heldFixInstallNested"), "without the approved cancel"}, |
| + {"Service.heldFixInstallClean", heldGuardAs("install", "Service.heldFixInstallClean"), ""}, |
| + // Entry removal: the cancel deferred, as a goroutine, in a literal, |
| + // under a false branch; the delete deferred; and the approved shape. |
| + {"Service.heldFixDeleteDefer", heldGuardReal, "not immediately preceded"}, |
| + {"Service.heldFixDeleteGo", heldGuardReal, "not immediately preceded"}, |
| + {"Service.heldFixDeleteClosure", heldGuardReal, "not immediately preceded"}, |
| + {"Service.heldFixDeleteFalse", heldGuardReal, "not immediately preceded"}, |
| + {"Service.heldFixDeleteDeferred", heldGuardReal, "is not a plain statement"}, |
| + {"Service.heldFixDeleteClean", heldGuardReal, ""}, |
| + // Aliases: actStopping through a local, through a helper's argument, |
| + // and a non-constant state write (the helper's body); a.entries |
| + // through a local and through a helper's argument. |
| + {"Service.heldFixStoppingAlias", heldGuardAs("beginStop", "Service.heldFixStoppingAlias"), "uses actStopping outside"}, |
| + {"Service.heldFixStoppingHelper", heldGuardReal, "uses actStopping outside"}, |
| + {"heldFixSetState", heldGuardReal, "assigns actEntry.state something other than a named constant"}, |
| + {"Service.heldFixEntriesAlias", heldGuardReal, "uses a.entries other than"}, |
| + {"Service.heldFixEntriesHelper", heldGuardReal, "uses a.entries other than"}, |
| +} |
| + |
| +// heldGuardFixtureSrc is the fixtures' source, type-checked as a file of |
| +// this package beside its real files. |
| +const heldGuardFixtureSrc = `package activator |
| + |
| +import "context" |
| + |
| +func (p *claimProcess) heldFixPreStopDefer(beforeStop func()) { |
| + go func() { |
| + defer beforeStop() |
| + _ = p.Stop(context.Background()) |
| + }() |
| +} |
| + |
| +func (p *claimProcess) heldFixPreStopGo(beforeStop func()) { |
| + go func() { |
| + go beforeStop() |
| + _ = p.Stop(context.Background()) |
| + }() |
| +} |
| + |
| +func (p *claimProcess) heldFixPreStopClosure(beforeStop func()) { |
| + go func() { |
| + pre := func() { beforeStop() } |
| + _ = pre |
| + _ = p.Stop(context.Background()) |
| + }() |
| +} |
| + |
| +func (p *claimProcess) heldFixPreStopFalse(beforeStop func()) { |
| + go func() { |
| + if false { |
| + beforeStop() |
| + } |
| + _ = p.Stop(context.Background()) |
| + }() |
| +} |
| + |
| +func (p *claimProcess) heldFixPreStopClean(beforeStop func()) { |
| + go func() { |
| + if beforeStop != nil { |
| + beforeStop() |
| + } |
| + _ = p.Stop(context.Background()) |
| + }() |
| +} |
| + |
| +func (a *Service) heldFixBindGo(e *actEntry, p *claimProcess, producer RoleProducer) { |
| + p.bindProducer(producer, func() { go a.refuseHeldLegsOn(e, p) }) |
| +} |
| + |
| +func (a *Service) heldFixInstallDefer(e *actEntry, proc Proc, g Gen) { |
| + defer a.cancelHeldLegsLocked(e, e.gen.N) |
| + e.proc = proc |
| +} |
| + |
| +func (a *Service) heldFixInstallGo(e *actEntry, proc Proc, g Gen) { |
| + go a.cancelHeldLegsLocked(e, e.gen.N) |
| + e.proc = proc |
| +} |
| + |
| +func (a *Service) heldFixInstallClosure(e *actEntry, proc Proc, g Gen) { |
| + cancel := func() { a.cancelHeldLegsLocked(e, e.gen.N) } |
| + _ = cancel |
| + e.proc = proc |
| +} |
| + |
| +func (a *Service) heldFixInstallFalse(e *actEntry, proc Proc, g Gen) { |
| + if false { |
| + a.cancelHeldLegsLocked(e, e.gen.N) |
| + } |
| + e.proc = proc |
| +} |
| + |
| +func (a *Service) heldFixInstallNested(e *actEntry, proc Proc, g Gen) { |
| + if e.gen.N != g.N { |
| + a.cancelHeldLegsLocked(e, e.gen.N) |
| + e.proc = proc |
| + } |
| +} |
| + |
| +func (a *Service) heldFixInstallClean(e *actEntry, proc Proc, g Gen) { |
| + if e.gen.N != g.N { |
| + a.cancelHeldLegsLocked(e, e.gen.N) |
| + } |
| + e.proc = proc |
| +} |
| + |
| +func (a *Service) heldFixDeleteDefer(e *actEntry) { |
| + defer a.cancelHeldLegsLocked(e, 0) |
| + delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixDeleteGo(e *actEntry) { |
| + go a.cancelHeldLegsLocked(e, 0) |
| + delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixDeleteClosure(e *actEntry) { |
| + cancel := func() { a.cancelHeldLegsLocked(e, 0) } |
| + _ = cancel |
| + delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixDeleteFalse(e *actEntry) { |
| + if false { |
| + a.cancelHeldLegsLocked(e, 0) |
| + } |
| + delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixDeleteDeferred(e *actEntry) { |
| + a.cancelHeldLegsLocked(e, 0) |
| + defer delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixDeleteClean(e *actEntry) { |
| + a.cancelHeldLegsLocked(e, 0) |
| + delete(a.entries, e.host) |
| +} |
| + |
| +func (a *Service) heldFixStoppingAlias(e *actEntry) { |
| + state := actStopping |
| + e.state = state |
| +} |
| + |
| +func (a *Service) heldFixStoppingHelper(e *actEntry) { |
| + heldFixSetState(e, actStopping) |
| +} |
| + |
| +func heldFixSetState(e *actEntry, s actState) { |
| + e.state = s |
| +} |
| + |
| +func (a *Service) heldFixEntriesAlias(host string) { |
| + entries := a.entries |
| + delete(entries, host) |
| +} |
| + |
| +func (a *Service) heldFixEntriesHelper(host string) { |
| + heldFixDrop(a.entries, host) |
| +} |
| + |
| +func heldFixDrop(m map[string]*actEntry, host string) { |
| + delete(m, host) |
| +} |
| +` |
| + |
| +// heldGuardFixturePackage type-checks heldGuardFixtureSrc as a file of |
| +// this package beside its real files, so a fixture resolves exactly as |
| +// real code would. It returns the fixture file alone. |
| +func heldGuardFixturePackage(t *testing.T, pkg *packages.Package) (*types.Info, map[string]*ast.File) { |
| + t.Helper() |
| + fix, err := parser.ParseFile(pkg.Fset, "heldlegs_guard_fixture.go", heldGuardFixtureSrc, 0) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var files []*ast.File |
| + for _, f := range heldGuardRealFiles(pkg) { |
| + files = append(files, f) |
| + } |
| + files = append(files, fix) |
| + info := &types.Info{Types: map[ast.Expr]types.TypeAndValue{}, Defs: map[*ast.Ident]types.Object{}, |
| + Uses: map[*ast.Ident]types.Object{}, Selections: map[*ast.SelectorExpr]*types.Selection{}} |
| + conf := types.Config{Importer: heldGuardImporter(pkg.Imports)} |
| + if _, err := conf.Check(pkg.PkgPath, pkg.Fset, files, info); err != nil { |
| + t.Fatalf("type-check the fixtures with the package: %v", err) |
| + } |
| + return info, map[string]*ast.File{"heldlegs_guard_fixture.go": fix} |
| +} |
| + |
| +// heldGuardImporter resolves the package's imports from what go/packages |
| +// already loaded. |
| +type heldGuardImporter map[string]*packages.Package |
| + |
| +func (m heldGuardImporter) Import(path string) (*types.Package, error) { |
| + if p := m[path]; p != nil && p.Types != nil { |
| + return p.Types, nil |
| + } |
| + return nil, fmt.Errorf("import %q not loaded", path) |
| +} |
| + |
| +// heldActivityForbidden are the package's activity functions: a request's |
| +// begin and release (inflight, lastActive), a wake's start and an entry's |
| +// creation, and a worker's activity stamps. The held admission path |
| +// reaches none of them. |
| +var heldActivityForbidden = []string{"begin", "beginRequest", "releaseFunc", "wake", "doWake", "putEntryLocked", "NoteWorkerContact", "NoteWorkerReady"} |
| + |
| +// heldActivityRoots are the held admission path's entry points: the held |
| +// admission and predicate, a leg's end, and the admission loop shared with |
| +// sidecar-marked requests (which must not begin either). |
| +var heldActivityRoots = []string{ |
| + "(*github.com/carlosframework/platform/internal/activator.Service).AdmitHeldLeg", |
| + "(*github.com/carlosframework/platform/internal/activator.Service).HeldAdmissible", |
| + "(*github.com/carlosframework/platform/internal/activator.Service).heldAdmissibleLocked", |
| + "(*github.com/carlosframework/platform/internal/activator.Service).admitPassThrough", |
| + "(*github.com/carlosframework/platform/internal/activator.Service).BeginSidecarRequest", |
| + "(*github.com/carlosframework/platform/internal/activator.heldLeg).Done", |
| +} |
| + |
| +// heldActivityBoundary is not walked into: the stop a dead child or a lost |
| +// lease starts inside the admission loop (spec §3.2: that side effect stays |
| +// in AdmitHeldLeg, outside the predicate). A stop is not activity, and its |
| +// own cancel is pinned by TestHeldLegTransitionSites. |
| +var heldActivityBoundary = []string{"beginStopLocked"} |
| + |
| +// TestHeldAdmissionTouchesNoActivity (#432 review P1): everything the held |
| +// admission path reaches in this package (the package call graph, function |
| +// literals and interface implementations included, through funcGraph) |
| +// calls no activity function and writes no actEntry.inflight or |
| +// actEntry.lastActive. |
| +func TestHeldAdmissionTouchesNoActivity(t *testing.T) { |
| + pkg, err := loadVerbGuardPackage() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + g, byName := funcGraph(pkg, false) |
| + decls := map[*types.Func]*ast.FuncDecl{} |
| + for _, f := range heldGuardRealFiles(pkg) { |
| + for _, d := range f.Decls { |
| + if fd, ok := d.(*ast.FuncDecl); ok && fd.Body != nil { |
| + if fn, ok := pkg.TypesInfo.Defs[fd.Name].(*types.Func); ok { |
| + decls[fn] = fd |
| + } |
| + } |
| + } |
| + } |
| + path := map[*types.Func][]string{} |
| + var queue []*types.Func |
| + for _, name := range heldActivityRoots { |
| + fn := byName[name] |
| + if fn == nil { |
| + t.Fatalf("root %s not resolved: the guard proves nothing", name) |
| + } |
| + path[fn] = []string{fn.Name()} |
| + queue = append(queue, fn) |
| + } |
| + for len(queue) > 0 { |
| + fn := queue[0] |
| + queue = queue[1:] |
| + for _, c := range g[fn] { |
| + if _, seen := path[c]; seen { |
| + continue |
| + } |
| + path[c] = append(slices.Clone(path[fn]), c.Name()) |
| + if slices.Contains(heldActivityBoundary, c.Name()) { |
| + continue |
| + } |
| + queue = append(queue, c) |
| + } |
| + } |
| + var reached []string |
| + for fn, p := range path { |
| + if slices.Contains(heldActivityBoundary, fn.Name()) && len(p) > 1 { |
| + continue // named, not walked |
| + } |
| + reached = append(reached, fn.Name()) |
| + if slices.Contains(heldActivityForbidden, fn.Name()) { |
| + t.Errorf("the held admission path reaches %s: %s; see %s (a held leg is never activity)", fn.Name(), strings.Join(p, " -> "), heldGuardSpec) |
| + } |
| + fd := decls[fn] |
| + if fd == nil { |
| + continue |
| + } |
| + ast.Inspect(fd.Body, func(n ast.Node) bool { |
| + var x ast.Expr |
| + switch v := n.(type) { |
| + case *ast.AssignStmt: |
| + for _, lhs := range v.Lhs { |
| + if se, ok := lhs.(*ast.SelectorExpr); ok && (heldGuardField(pkg.TypesInfo, se, "actEntry", "inflight") || heldGuardField(pkg.TypesInfo, se, "actEntry", "lastActive")) { |
| + x = se |
| + } |
| + } |
| + case *ast.IncDecStmt: |
| + if se, ok := v.X.(*ast.SelectorExpr); ok && heldGuardField(pkg.TypesInfo, se, "actEntry", "inflight") { |
| + x = se |
| + } |
| + } |
| + if x != nil { |
| + pos := pkg.Fset.Position(x.Pos()) |
| + t.Errorf("%s:%d: %s, reached by the held admission path (%s), writes %s; see %s", pos.Filename, pos.Line, fn.Name(), strings.Join(path[fn], " -> "), heldGuardRender(pkg.Fset, x), heldGuardSpec) |
| + } |
| + return true |
| + }) |
| + } |
| + // Control: the walk reached the predicate and the registration. |
| + for _, want := range []string{"passThroughAdmissibleLocked", "registerHeldLegLocked", "startupDone"} { |
| + if !slices.Contains(reached, want) { |
| + t.Fatalf("the walk did not reach %s: it resolves nothing", want) |
| + } |
| + } |
| + boundary := false |
| + for fn := range path { |
| + boundary = boundary || slices.Contains(heldActivityBoundary, fn.Name()) |
| + } |
| + if !boundary { |
| + t.Fatal("the walk never met the admission loop's stop (beginStopLocked): the boundary is stale") |
| + } |
| + slices.Sort(reached) |
| + t.Logf("held admission path reaches %d functions: %s", len(reached), strings.Join(reached, ", ")) |
| } |