carlos / platform Public

activator: held-leg guard and sim fixes from task 2 review (#432)

Human

Prompt

fix Astra round 1 findings on 1d0619cf (T2-findings.md) per the
controller's rulings.

From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.

Summary

- P1: TestHeldAdmissionTouchesNoActivity walks the package call graph
  from AdmitHeldLeg, HeldAdmissible, heldAdmissibleLocked, the shared
  admission loop, BeginSidecarRequest and heldLeg.Done (stop boundary:
  beginStopLocked) and refuses any activity function or write of
  inflight/lastActive. Witness: a held leg joining a hold swap's pinned
  wake reads no activity clock, leaves inflight 0 and lastActive at the
  wake's stamp, and starts no wake. The sim's I5 gains the same
  exemption-free clock check.
- P2: cancellation counts only as a synchronous statement in an
  approved shape (installProcLocked's generation-change if, the
  pre-stop statement, the bindClaimProducer literal, refuseHeldLegsOn's
  loop); actStopping only in comparisons, case labels and the one
  beginStopLocked assignment; actEntry.state only takes constants;
  a.entries only by key, range, len, nil check, make or guarded delete.
  23 in-test fixtures for defer, go, closure, false-branch and aliases.
- P2: heldLegRegistered, a test-only hook (nil in production) called
  under a.mu at registration; the sim records legs there.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 21241fbecd460a509fbb69bb6ad452d4e78b0b55 parent 535b75d
4 files changed, +938 −160
  • internal/activator/heldlegs.go +10 −0
  • internal/activator/heldlegs_activity_test.go +173 −0
  • internal/activator/heldlegs_guard_test.go +702 −142
  • internal/activator/swap_sim_test.go +53 −18
diff --git a/internal/activator/heldlegs.go b/internal/activator/heldlegs.go
index ebc8e9985..99c107bd0 100644
--- a/internal/activator/heldlegs.go
+++ b/internal/activator/heldlegs.go
@@ -3,6 +3,7 @@ package activator
import (
"context"
"log"
+ "sync/atomic"
"time"
"github.com/carlosframework/platform/internal/edge"
@@ -189,9 +190,18 @@ func (a *Service) registerHeldLegLocked(e *actEntry, ctx context.Context) *heldL
e.heldLegs = make(map[uint64]*heldLeg)
}
e.heldLegs[l.id] = l
+ if f := heldLegRegistered.Load(); f != nil {
+ (*f)(a, e, l)
+ }
return l
}
+// heldLegRegistered is a test-only observer, nil in production: it is
+// called under a.mu in the critical section that registers a leg, so a
+// test sees the leg (and the process it is on) before anything can stop
+// that process.
+var heldLegRegistered atomic.Pointer[func(a *Service, e *actEntry, l *heldLeg)]
+
// cancelHeldLegsLocked cancels the legs registered on e: every leg when gen
// is 0, otherwise only those admitted on generation gen. It only calls
// cancel functions, so it never blocks; a leg leaves the registry at its
diff --git a/internal/activator/heldlegs_activity_test.go b/internal/activator/heldlegs_activity_test.go
new file mode 100644
index 000000000..c34aec3ca
--- /dev/null
+++ b/internal/activator/heldlegs_activity_test.go
@@ -0,0 +1,173 @@
+package activator
+
+import (
+ "context"
+ "runtime"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+)
+
+// heldAdmissionClockRead reports, when the calling goroutine is inside a
+// held admission (AdmitHeldLeg), the frames that read the Service's clock;
+// "" otherwise. A held admission never reads the activity clock, so it can
+// never stamp lastActive (edge-held streams I5), whatever entry it joins
+// or crosses. The one exception is the stop a dead child or a lost lease
+// starts inside the admission loop (beginStopLocked): a stop, not
+// activity.
+func heldAdmissionClockRead() string {
+ buf := make([]byte, 32<<10)
+ st := string(buf[:runtime.Stack(buf, false)])
+ if !strings.Contains(st, ".(*Service).AdmitHeldLeg(") && !strings.Contains(st, ".(*Service).AdmitHeldLeg.") {
+ return ""
+ }
+ if strings.Contains(st, ".(*Service).beginStopLocked(") {
+ return ""
+ }
+ var frames []string
+ for _, line := range strings.Split(st, "\n") {
+ if line == "" || strings.HasPrefix(line, "\t") || strings.HasPrefix(line, "goroutine ") {
+ continue
+ }
+ if i := strings.LastIndex(line, "/"); i >= 0 {
+ line = line[i+1:]
+ }
+ if i := strings.Index(line, "("); i > 0 && !strings.HasPrefix(line[i:], "(*") {
+ line = line[:i]
+ }
+ frames = append(frames, line)
+ if len(frames) == 8 {
+ break
+ }
+ }
+ return strings.Join(frames, " <- ")
+}
+
+// A held leg admitted while a hold swap's pinned wake is in flight joins
+// that wake, on the entry that replaced the incumbent's, and is admitted
+// once it is awake. The admission contributes no activity (#432 review P1,
+// I5): it never reads the activity clock (so stamps no lastActive), the
+// entry's inflight is 0 when the leg is registered and after, the
+// entry's lastActive is the wake's own stamp, and no live-link wake
+// starts. Not parallel: it sets the package's registration hook.
+func TestHeldAdmissionJoiningAPinnedWakeTouchesNoActivity(t *testing.T) {
+ f := newSwapFixture(t)
+ var mu sync.Mutex
+ var clockReads []string
+ now := f.a.now
+ f.a.now = func() time.Time {
+ if what := heldAdmissionClockRead(); what != "" {
+ mu.Lock()
+ clockReads = append(clockReads, what)
+ mu.Unlock()
+ }
+ return now()
+ }
+ type atReg struct {
+ e *actEntry
+ inflight int
+ lastActive time.Time
+ }
+ var reg []atReg
+ hook := func(sa *Service, e *actEntry, _ *heldLeg) {
+ if sa == f.a {
+ mu.Lock()
+ reg = append(reg, atReg{e, e.inflight, e.lastActive})
+ mu.Unlock()
+ }
+ }
+ heldLegRegistered.Store(&hook)
+ t.Cleanup(func() { heldLegRegistered.Store(nil) })
+
+ f.a.mu.Lock()
+ incumbent := f.a.entries[f.host]
+ f.a.mu.Unlock()
+ gate := make(chan struct{})
+ f.b.gmu.Lock()
+ f.b.genGate = gate // the pinned wake's spawn waits here
+ f.b.gmu.Unlock()
+ results := make(chan SwapResult, 1)
+ go func() { results <- f.a.Swap(context.Background(), f.attempt(ModeHold), f.newest) }()
+ var pinned *actEntry
+ waitFor(t, "the hold's pinned wake", func() bool {
+ f.a.mu.Lock()
+ defer f.a.mu.Unlock()
+ e := f.a.entries[f.host]
+ if e != nil && e != incumbent && e.state == actWaking && e.pin != nil {
+ pinned = e
+ return true
+ }
+ return false
+ })
+ wakesBefore := f.b.startCount()
+
+ type admitted struct {
+ leg *heldLeg
+ err error
+ }
+ got := make(chan admitted, 1)
+ joining := &doneAskedCtx{Context: context.Background(), asked: make(chan struct{})}
+ go func() {
+ leg, err := f.a.AdmitHeldLeg(joining, testRoute(f.host))
+ l, _ := leg.(*heldLeg)
+ got <- admitted{l, err}
+ }()
+ // The admission has reached its wait on the waking entry (the first
+ // place it asks its context's Done).
+ select {
+ case <-joining.asked:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the admission never waited on the pinned wake")
+ }
+ // The wake's stamps land after this, at the new instant.
+ f.clk.advance(time.Minute)
+ close(gate)
+
+ var res admitted
+ select {
+ case res = <-got:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the admission never returned")
+ }
+ select {
+ case sr := <-results:
+ if sr.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v, want done", sr)
+ }
+ case <-time.After(10 * time.Second):
+ t.Fatal("the hold never finished")
+ }
+ if res.err != nil || res.leg == nil {
+ t.Fatalf("AdmitHeldLeg joining the pinned wake = %v, %v; want a leg", res.leg, res.err)
+ }
+ defer res.leg.Done()
+
+ mu.Lock()
+ defer mu.Unlock()
+ if len(clockReads) > 0 {
+ t.Errorf("the held admission read the activity clock %d time(s) (it may stamp lastActive): %s", len(clockReads), strings.Join(clockReads, "\n"))
+ }
+ if len(reg) != 1 || reg[0].e != pinned {
+ t.Fatalf("legs registered = %+v, want one, on the pinned entry %p", reg, pinned)
+ }
+ if reg[0].inflight != 0 {
+ t.Errorf("inflight at the leg's registration = %d, want 0", reg[0].inflight)
+ }
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ inflight, lastActive, spawnedAt := e.inflight, e.lastActive, e.spawnedAt
+ f.a.mu.Unlock()
+ if e != pinned {
+ t.Fatalf("the host's entry changed after the admission")
+ }
+ if inflight != 0 {
+ t.Errorf("inflight after the admission = %d, want 0", inflight)
+ }
+ if !lastActive.Equal(spawnedAt) || !reg[0].lastActive.Equal(lastActive) {
+ t.Errorf("lastActive = %v (at registration %v), want the wake's own stamp %v", lastActive, reg[0].lastActive, spawnedAt)
+ }
+ if n := f.b.startCount(); n != wakesBefore {
+ t.Errorf("live-link wakes = %d, want %d: the held admission started a wake", n, wakesBefore)
+ }
+}
diff --git a/internal/activator/heldlegs_guard_test.go b/internal/activator/heldlegs_guard_test.go
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, ", "))
}
diff --git a/internal/activator/swap_sim_test.go b/internal/activator/swap_sim_test.go
index 8b829ec4c..161bfe3bd 100644
--- a/internal/activator/swap_sim_test.go
+++ b/internal/activator/swap_sim_test.go
@@ -261,10 +261,13 @@ func simObserveHeld(a *Service, sb *simBackend, host string) simHeldObs {
// admitHeld is the "admit a held leg" action, with I5 around it: under
// the host's exclusive lock (no ordinary request on the host meanwhile),
// the admission must not change the entry's in-flight count or last
-// activity, and must start no wake. A waking entry's own wake may stamp
-// lastActive as it completes, so that field is compared only for an entry
-// that was not waking; a different entry after the admission (a hold
-// swap's pinned wake) is not compared at all.
+// activity, and must start no wake. Those reads are coarse: a waking
+// entry's own wake may stamp lastActive as it completes, so that field is
+// compared only for an entry that was not waking, and a different entry
+// after the admission (a hold swap's pinned wake) is not compared at all.
+// The decisive I5 check has no such exemption: the admission's own call
+// stack never reads the activity clock (simHeldClock), so it cannot stamp
+// lastActive on any entry it joins or crosses.
func (w *simWorld) admitHeld(a *Service, sb *simBackend, rt registry.Route) {
mu := w.heldHost[rt.Host]
mu.Lock()
@@ -312,30 +315,54 @@ func (w *simWorld) admitHeld(a *Service, sb *simBackend, rt registry.Route) {
w.mu.Unlock()
return
}
- // Which process the leg is on: the entry it was registered on, if that
- // entry is still the host's and its generation is still the leg's.
+ // The leg was recorded by the registration hook (recordHeldLeg), in the
+ // activator's own critical section; nothing is read about it here.
l := leg.(*heldLeg)
- var proc Proc
- a.mu.Lock()
- if e := a.entries[rt.Host]; e != nil && e.heldLegs[l.id] == l && e.gen.N == l.gen {
- proc = e.proc
+ w.mu.Lock()
+ recorded := false
+ for _, sl := range w.legs {
+ if sl.leg == edge.HeldLeg(l) {
+ recorded = true
+ }
}
- a.mu.Unlock()
- if proc == nil && l.ctx.Err() == nil {
- w.violatef("I4: held leg on %s gen %d is uncancelled, but its generation or entry is no longer current", rt.Host, l.gen)
+ w.mu.Unlock()
+ if !recorded {
+ w.violatef("I4: held leg on %s gen %d was admitted without passing the registration hook", rt.Host, l.gen)
}
+}
+
+// recordHeldLeg is the registration hook's body (heldLegRegistered): it
+// runs under a.mu in the critical section that registers l on e, so I4
+// knows the leg, and the process it is on, before anything can stop that
+// process: there is no window between the activator's registration and
+// the model's record.
+func (w *simWorld) recordHeldLeg(e *actEntry, l *heldLeg) {
w.mu.Lock()
- sl := &simLeg{id: len(w.legs) + 1, host: rt.Host, gen: l.gen, proc: proc, leg: leg}
+ defer w.mu.Unlock()
+ sl := &simLeg{id: len(w.legs) + 1, host: e.host, gen: l.gen, proc: e.proc, leg: l}
w.legs = append(w.legs, sl)
pid := 0
- if p, ok := proc.(*simProc); ok {
+ if p, ok := e.proc.(*simProc); ok {
pid = p.id
w.outcomes["held/admitted on a known process"]++
} else {
w.outcomes["held/admitted, process not read"]++
}
- w.events = append(w.events, fmt.Sprintf("held admit %s: leg %d on gen %d p%d", rt.Host, sl.id, l.gen, pid))
- w.mu.Unlock()
+ w.events = append(w.events, fmt.Sprintf("held admit %s: leg %d on gen %d p%d", e.host, sl.id, l.gen, pid))
+}
+
+// simHeldClock wraps the Service's clock for I5: a held admission's own
+// call stack (AdmitHeldLeg) never reads the activity clock, so it can
+// never stamp lastActive, whatever entry it joins or crosses. The one
+// exception is the stop a dead child or a lost lease starts inside the
+// admission loop (beginStopLocked), which is a stop, not activity.
+func (w *simWorld) simHeldClock(now func() time.Time) func() time.Time {
+ return func() time.Time {
+ if what := heldAdmissionClockRead(); what != "" {
+ w.violatef("I5: held admission read the activity clock: %s", what)
+ }
+ return now()
+ }
}
// finishHeld is the "finish a held leg" action: one live leg ends (Done).
@@ -954,7 +981,15 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s
clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
a := New(Config{Bucket: "sim", Idle: time.Hour}, sb, simDue{})
a.gens = w.gensOn
- a.now = clk.now
+ a.now = w.simHeldClock(clk.now)
+ // I4's record: every leg this Service registers, under a.mu.
+ hook := func(sa *Service, e *actEntry, l *heldLeg) {
+ if sa == a {
+ w.recordHeldLeg(e, l)
+ }
+ }
+ heldLegRegistered.Store(&hook)
+ defer heldLegRegistered.Store(nil)
a.genHealth = func(ctx context.Context, _ Gen) error {
w.jitter()
if err := ctx.Err(); err != nil {