activator: guard held-leg transitions; simulate held legs in swaps (#432)
Human
Prompt
Task 2 of #432 (edge-held streams): pin Task 1's held-leg cancellation with a transition-site guard and add held-leg invariants to the activator swap simulation.
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
- TestHeldLegTransitionSites (go/types via loadVerbGuardPackage): actStopping is assigned only in beginStopLocked, whose first statement cancels every leg; actEntry.proc is assigned only in installProcLocked, after a cancelHeldLegsLocked call; every delete(a.entries, ...) is immediately preceded in its block by cancelHeldLegsLocked(..., 0); the claim producer's cleanup runs its pre-stop (refuseHeldLegsOn) before its first Stop. Other types' proc fields are told apart by type. Failures name file, line and function and point at spec 3.2. - TestSwapInvariants gains "admit a held leg" and "finish a held leg" actions. I4: no simulated process or generation is stopped or killed while a leg admitted on it is uncancelled. I5: under a per-host lock that ordinary requests share, a held admission changes no inflight, no lastActive and starts no live-link wake. Seeds count unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 files changed,
+594
−6
internal/activator/heldlegs_guard_test.go+385 −0internal/activator/swap_sim_test.go+209 −6
diff --git a/internal/activator/heldlegs_guard_test.go b/internal/activator/heldlegs_guard_test.go| new file mode 100644 |
| index 000000000..c38687d0d |
| --- /dev/null |
| +++ b/internal/activator/heldlegs_guard_test.go |
| @@ -0,0 +1,385 @@ |
| +package activator |
| + |
| +// Edge-held streams spec §3.2 (plan Task 2): a held leg is registered only |
| +// on the current generation of an awake entry (heldAdmissibleLocked), so a |
| +// process a leg is connected to can only be told to stop after one of |
| +// these transitions, and each cancels the legs first, under a.mu: |
| +// |
| +// - the entry leaves actAwake: only beginStopLocked assigns actStopping, |
| +// and its first statement cancels every leg; |
| +// - the entry's current process changes: only installProcLocked assigns |
| +// actEntry.proc, and it cancels the outgoing generation's legs before |
| +// the assignment; |
| +// - the entry is removed: every delete(a.entries, …) is immediately |
| +// preceded, in the same block, by cancelHeldLegsLocked(…, 0); |
| +// - a claim start's producer cleanup stops its process directly: the |
| +// goroutine bindProducer starts runs its beforeStop before the first |
| +// Stop, and the package's only binding (bindClaimProducer) passes the |
| +// pre-stop that cancels the entry's legs (refuseHeldLegsOn). |
| +// |
| +// 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. |
| + |
| +import ( |
| + "fmt" |
| + "go/ast" |
| + "go/token" |
| + "go/types" |
| + "slices" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +const heldGuardSpec = "edge-held streams spec §3.2" |
| + |
| +// heldGuardFunc is one function declaration the guard reads: its name as |
| +// "Recv.Name" (or "Name"), and its body. |
| +type heldGuardFunc struct { |
| + file string |
| + name string |
| + decl *ast.FuncDecl |
| +} |
| + |
| +// 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 { |
| + switch f := call.Fun.(type) { |
| + case *ast.SelectorExpr: |
| + return f.Sel.Name == name |
| + case *ast.Ident: |
| + return f.Name == name |
| + } |
| + return false |
| +} |
| + |
| +// heldGuardCancelAll reports whether stmt is exactly a statement |
| +// x.cancelHeldLegsLocked(…, 0). |
| +func heldGuardCancelAll(stmt ast.Stmt) bool { |
| + es, ok := stmt.(*ast.ExprStmt) |
| + if !ok { |
| + return false |
| + } |
| + call, ok := es.X.(*ast.CallExpr) |
| + if !ok || !heldGuardCalls(call, "cancelHeldLegsLocked") || len(call.Args) != 2 { |
| + return false |
| + } |
| + lit, ok := call.Args[1].(*ast.BasicLit) |
| + return ok && lit.Kind == token.INT && lit.Value == "0" |
| +} |
| + |
| +// heldGuardContainsCall reports whether n contains a call named name. |
| +func heldGuardContainsCall(n ast.Node, name string) bool { |
| + found := false |
| + ast.Inspect(n, func(m ast.Node) bool { |
| + if c, ok := m.(*ast.CallExpr); ok && heldGuardCalls(c, name) { |
| + found = true |
| + } |
| + return !found |
| + }) |
| + return found |
| +} |
| + |
| +// heldGuardNamed reports whether t (or what it points to) is the package's |
| +// named type name. |
| +func heldGuardNamed(t types.Type, name string) bool { |
| + if p, ok := t.(*types.Pointer); ok { |
| + t = p.Elem() |
| + } |
| + n, ok := t.(*types.Named) |
| + return ok && n.Obj().Name() == name && n.Obj().Pkg() != nil && n.Obj().Pkg().Name() == "activator" |
| +} |
| + |
| +// 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 { |
| + var out [][]ast.Stmt |
| + ast.Inspect(body, func(n ast.Node) bool { |
| + switch v := n.(type) { |
| + case *ast.BlockStmt: |
| + out = append(out, v.List) |
| + case *ast.CaseClause: |
| + out = append(out, v.Body) |
| + case *ast.CommClause: |
| + out = append(out, v.Body) |
| + } |
| + return true |
| + }) |
| + 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 { |
| + return false |
| + } |
| + return heldGuardIsDeleteEntries(info, call) |
| +} |
| + |
| +func heldGuardIsDeleteEntries(info *types.Info, call *ast.CallExpr) bool { |
| + id, ok := call.Fun.(*ast.Ident) |
| + if !ok { |
| + return false |
| + } |
| + if _, builtin := info.Uses[id].(*types.Builtin); !builtin || id.Name != "delete" || len(call.Args) != 2 { |
| + return false |
| + } |
| + se, ok := call.Args[0].(*ast.SelectorExpr) |
| + if !ok || se.Sel.Name != "entries" { |
| + return false |
| + } |
| + sel := info.Selections[se] |
| + return sel != nil && sel.Kind() == types.FieldVal && heldGuardNamed(sel.Recv(), "Service") |
| +} |
| + |
| +// heldGuardReport is the guard's result over a set of functions. |
| +type heldGuardReport struct { |
| + violations []string |
| + // controls, so a guard that resolves nothing cannot pass. |
| + stoppingSites, procSites, deleteSites, otherProcSites int |
| + otherProcs []string |
| + beginStopFirst, installCancelsFirst, producerPreStop bool |
| +} |
| + |
| +func heldGuardRun(fset *token.FileSet, info *types.Info, funcs []heldGuardFunc) 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 { |
| + switch v := n.(type) { |
| + 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") |
| + } |
| + } |
| + // 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") |
| + } |
| + } |
| + } |
| + 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") |
| + } |
| + } |
| + } |
| + } |
| + case *ast.CallExpr: |
| + if heldGuardIsDeleteEntries(info, v) { |
| + r.deleteSites++ |
| + calls++ |
| + } |
| + } |
| + return true |
| + }) |
| + // Every delete(a.entries, …) statement is immediately preceded in |
| + // its own block by cancelHeldLegsLocked(…, 0). |
| + seen := 0 |
| + for _, list := range heldGuardStmtLists(body) { |
| + for i, s := range list { |
| + if !heldGuardDeleteEntries(info, s) { |
| + 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") |
| + } |
| + } |
| + } |
| + // 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 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" { |
| + var goLit *ast.FuncLit |
| + ast.Inspect(body, func(n ast.Node) bool { |
| + if g, ok := n.(*ast.GoStmt); ok { |
| + if lit, ok := g.Call.Fun.(*ast.FuncLit); ok { |
| + goLit = lit |
| + } |
| + } |
| + return goLit == nil |
| + }) |
| + 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() |
| + } |
| + if se, ok := c.Fun.(*ast.SelectorExpr); ok && se.Sel.Name == "Stop" && stop == token.NoPos { |
| + stop = c.Pos() |
| + } |
| + return true |
| + }) |
| + switch { |
| + case stop == token.NoPos: |
| + 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)") |
| + default: |
| + r.producerPreStop = true |
| + } |
| + } |
| + } |
| + // Every binding of a claim producer goes through bindClaimProducer, |
| + // whose beforeStop is refuseHeldLegsOn. |
| + 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" { |
| + 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") |
| + } |
| + return true |
| + }) |
| + // refuseHeldLegsOn cancels every leg. |
| + if fn.name == "Service.refuseHeldLegsOn" { |
| + found := false |
| + ast.Inspect(body, func(n ast.Node) bool { |
| + if es, ok := n.(*ast.ExprStmt); ok && heldGuardCancelAll(es) { |
| + found = true |
| + } |
| + return !found |
| + }) |
| + if !found { |
| + at(fn, fn.decl.Pos(), "refuseHeldLegsOn does not call cancelHeldLegsLocked(…, 0)") |
| + } |
| + } |
| + } |
| + return r |
| +} |
| + |
| +func TestHeldLegTransitionSites(t *testing.T) { |
| + pkg, err := loadVerbGuardPackage() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var funcs []heldGuardFunc |
| + 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}) |
| + } |
| + } |
| + r := heldGuardRun(pkg.Fset, pkg.TypesInfo, funcs) |
| + for _, v := range r.violations { |
| + t.Error(v) |
| + } |
| + // A guard that resolved nothing proves nothing. |
| + if r.stoppingSites < 1 || !r.beginStopFirst { |
| + t.Errorf("the guard saw %d actStopping assignments (beginStopLocked first-statement cancel: %v): it resolves nothing", r.stoppingSites, r.beginStopFirst) |
| + } |
| + if r.procSites < 1 || !r.installCancelsFirst { |
| + t.Errorf("the guard saw %d actEntry.proc assignments (installProcLocked cancels first: %v): it resolves nothing", r.procSites, r.installCancelsFirst) |
| + } |
| + 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") |
| + } |
| + // Receiver-awareness control: other types' proc fields exist and were |
| + // told apart from an entry's. |
| + if r.otherProcSites < 1 { |
| + t.Errorf("the guard saw no proc assignment of another type (wake, member, rootfs worker): its type check is not exercised") |
| + } |
| + 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, "; ")) |
| +} |
diff --git a/internal/activator/swap_sim_test.go b/internal/activator/swap_sim_test.go| index 2f0e3d710..8b829ec4c 100644 |
| --- a/internal/activator/swap_sim_test.go |
| +++ b/internal/activator/swap_sim_test.go |
| @@ -20,14 +20,19 @@ import ( |
| "time" |
| "github.com/carlosframework/platform/internal/cgroup" |
| + "github.com/carlosframework/platform/internal/edge" |
| "github.com/carlosframework/platform/internal/registry" |
| ) |
| // TestSwapInvariants drives random schedules of requests, overlap and hold |
| // swaps, hibernation, lease loss, restarts, maintenance fences, root |
| -// repoints, supersession, crashes, re-stop cadences and a final Shutdown |
| -// against the real Service and a simulated backend. It checks I1, I2 and I3 |
| -// (plan 3 task 13; spec §12). |
| +// repoints, supersession, crashes, re-stop cadences, held-leg admissions |
| +// and finishes, and a final Shutdown against the real Service and a |
| +// simulated backend. It checks I1, I2 and I3 (plan 3 task 13; spec §12), |
| +// and the edge-held streams invariants (#432 spec §3.2, §7): I4, no process |
| +// or generation is told to stop while a leg admitted on it is uncancelled; |
| +// I5, a held admission changes no in-flight count or last activity and |
| +// starts no wake. |
| // |
| // The simulated processes do not all stop when asked. Some drain slowly, |
| // some answer ErrStillRunning or a failed kill and exit on their own later, |
| @@ -182,6 +187,175 @@ type simWorld struct { |
| // held: the moment a reaper that saw Exited() could act. The model's |
| // own interleaving test sets it; the sweep never does. |
| dying func(p *simProc) |
| + // legs are the held legs admitted so far (edge-held streams, I4 and |
| + // I5); heldHost is the per-host lock an admission takes exclusively and |
| + // an ordinary request takes shared, so no ordinary request starts or |
| + // ends on a host while a held admission is observed there. |
| + legs []*simLeg |
| + heldHost map[string]*sync.RWMutex |
| +} |
| + |
| +// simLeg is one admitted held leg: the host, the generation number it was |
| +// registered on, and the process current on that generation when it was |
| +// admitted (nil when that could not be read; then only KillGen of its |
| +// generation checks it). |
| +type simLeg struct { |
| + id int |
| + host string |
| + gen uint64 |
| + proc Proc |
| + leg edge.HeldLeg |
| + done bool |
| + // stopped: the leg has been met, cancelled, at a stop signal. |
| + stopped bool |
| +} |
| + |
| +// checkHeldLegs is I4 at a stop signal: every recorded leg match selects |
| +// must already be cancelled (by a Done or by the activator). The caller |
| +// holds no model lock. |
| +func (w *simWorld) checkHeldLegs(match func(*simLeg) bool, what string) { |
| + w.mu.Lock() |
| + var bad []int |
| + for _, l := range w.legs { |
| + if !match(l) { |
| + continue |
| + } |
| + if l.leg.Context().Err() == nil { |
| + bad = append(bad, l.id) |
| + } else if !l.done && !l.stopped { |
| + // Coverage: a leg the activator cancelled, met at a stop. |
| + l.stopped = true |
| + w.outcomes["held/leg met at a stop signal, cancelled by the activator"]++ |
| + } |
| + } |
| + w.mu.Unlock() |
| + for _, id := range bad { |
| + w.violatef("I4: %s with held leg %d uncancelled", what, id) |
| + } |
| +} |
| + |
| +// simHeldObs is what I5 reads around a held admission, under a.mu: the |
| +// host's entry, its state, in-flight count and last activity, and the |
| +// backend's count of live-link wake spawns for the host. |
| +type simHeldObs struct { |
| + e *actEntry |
| + state actState |
| + inflight int |
| + lastActive time.Time |
| + wakes int |
| +} |
| + |
| +func simObserveHeld(a *Service, sb *simBackend, host string) simHeldObs { |
| + var o simHeldObs |
| + a.mu.Lock() |
| + if e := a.entries[host]; e != nil { |
| + o.e, o.state, o.inflight, o.lastActive = e, e.state, e.inflight, e.lastActive |
| + } |
| + a.mu.Unlock() |
| + sb.mu.Lock() |
| + o.wakes = sb.wakes[host] |
| + sb.mu.Unlock() |
| + return o |
| +} |
| + |
| +// 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. |
| +func (w *simWorld) admitHeld(a *Service, sb *simBackend, rt registry.Route) { |
| + mu := w.heldHost[rt.Host] |
| + mu.Lock() |
| + defer mu.Unlock() |
| + before := simObserveHeld(a, sb, rt.Host) |
| + // The leg's context is the admission's: it must not end when the |
| + // admission returns, or I4 would see every leg cancelled. A bound on |
| + // the admission's wait ends it only if the admission has not returned. |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + var returned sync.Mutex |
| + finished := false |
| + bound := time.AfterFunc(2*time.Second, func() { |
| + returned.Lock() |
| + if !finished { |
| + cancel() |
| + } |
| + returned.Unlock() |
| + }) |
| + leg, err := a.AdmitHeldLeg(ctx, rt) |
| + returned.Lock() |
| + finished = true |
| + returned.Unlock() |
| + bound.Stop() |
| + after := simObserveHeld(a, sb, rt.Host) |
| + if after.wakes != before.wakes { |
| + w.violatef("I5: held admission on %s changed the wake count (%d -> %d)", rt.Host, before.wakes, after.wakes) |
| + } |
| + if before.e != nil && before.e == after.e { |
| + if after.inflight != before.inflight { |
| + w.violatef("I5: held admission on %s changed inflight (%d -> %d)", rt.Host, before.inflight, after.inflight) |
| + } |
| + if before.state != actWaking && !after.lastActive.Equal(before.lastActive) { |
| + w.violatef("I5: held admission on %s changed lastActive (%v -> %v)", rt.Host, before.lastActive, after.lastActive) |
| + } |
| + } |
| + if err != nil { |
| + cancel() |
| + key := "held/refused: asleep" |
| + if before.e != nil { |
| + key = "held/refused: " + simDigits.ReplaceAllString(err.Error(), "N") |
| + } |
| + w.mu.Lock() |
| + w.outcomes[key]++ |
| + w.events = append(w.events, fmt.Sprintf("held admit %s refused: %v", rt.Host, err)) |
| + 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. |
| + 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 |
| + } |
| + 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.Lock() |
| + sl := &simLeg{id: len(w.legs) + 1, host: rt.Host, gen: l.gen, proc: proc, leg: leg} |
| + w.legs = append(w.legs, sl) |
| + pid := 0 |
| + if p, ok := 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() |
| +} |
| + |
| +// finishHeld is the "finish a held leg" action: one live leg ends (Done). |
| +func (w *simWorld) finishHeld() { |
| + w.mu.Lock() |
| + var live []*simLeg |
| + for _, l := range w.legs { |
| + if !l.done { |
| + live = append(live, l) |
| + } |
| + } |
| + if len(live) == 0 { |
| + w.mu.Unlock() |
| + return |
| + } |
| + l := live[w.rng.Intn(len(live))] |
| + l.done = true |
| + w.events = append(w.events, fmt.Sprintf("held leg %d done", l.id)) |
| + w.mu.Unlock() |
| + l.leg.Done() |
| } |
| func (w *simWorld) logf(format string, args ...any) { |
| @@ -387,6 +561,8 @@ type simProc struct { |
| } |
| func (p *simProc) Stop(context.Context) error { |
| + // I4: no process is told to stop while a leg admitted on it is live. |
| + p.w.checkHeldLegs(func(l *simLeg) bool { return l.proc == Proc(p) }, fmt.Sprintf("p%d stopped", p.id)) |
| p.w.jitter() |
| if p.Exited() { |
| return nil |
| @@ -491,6 +667,10 @@ type simBackend struct { |
| dir string |
| mu sync.Mutex |
| reps map[string]*simRep |
| + // wakes counts the live-link wake spawns (StartGen) per host: I5's |
| + // "a held admission starts no wake". A swap's spawns (StartStaged) |
| + // are not wakes of the live link and are not counted. |
| + wakes map[string]int |
| } |
| var ( |
| @@ -535,6 +715,9 @@ func (b *simBackend) Start(ctx context.Context, rt registry.Route) (Proc, string |
| // StartGen is the wake's spawn of the live link (which only ever names v1 |
| // or v2). |
| func (b *simBackend) StartGen(ctx context.Context, rt registry.Route, n uint64, perGen bool) (Proc, Gen, error) { |
| + b.mu.Lock() |
| + b.wakes[rt.Host]++ |
| + b.mu.Unlock() |
| b.w.jitter() |
| b.w.mu.Lock() |
| build := b.w.live[rt.Host] |
| @@ -622,6 +805,8 @@ func (b *simBackend) KillGen(_ context.Context, rt registry.Route, n uint64) err |
| if !w.contained { |
| return fmt.Errorf("sim: %w", errNoGenContainment) |
| } |
| + // I4: no generation is killed while a leg admitted on it is live. |
| + w.checkHeldLegs(func(l *simLeg) bool { return l.host == rt.Host && l.gen == n }, fmt.Sprintf("%s gen %d killed", rt.Host, n)) |
| w.jitter() |
| key := fmt.Sprintf("%s#%d", rt.Host, n) |
| w.mu.Lock() |
| @@ -747,7 +932,10 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s |
| hosts := []string{"one.sim.example.com", "two.sim.example.com"} |
| w := &simWorld{rng: rand.New(rand.NewSource(int64(seed))), running: map[string]map[*simProc]bool{}, |
| live: map[string]string{}, staged: map[string]string{}, seen: map[string]bool{}, outcomes: map[string]int{}, |
| - killFails: map[string]int{}, hosts: hosts} |
| + killFails: map[string]int{}, hosts: hosts, heldHost: map[string]*sync.RWMutex{}} |
| + for _, h := range hosts { |
| + w.heldHost[h] = new(sync.RWMutex) |
| + } |
| // One seed in five runs with the dormant switch off (today's paths, |
| // where stop()'s own ErrStillRunning check is the only retention), and |
| // one in five without generation containment. |
| @@ -762,7 +950,7 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s |
| for _, h := range hosts { |
| w.live[h] = "v1" |
| } |
| - sb := &simBackend{w: w, dir: sockDir, reps: map[string]*simRep{}} |
| + sb := &simBackend{w: w, dir: sockDir, reps: map[string]*simRep{}, wakes: map[string]int{}} |
| clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| a := New(Config{Bucket: "sim", Idle: time.Hour}, sb, simDue{}) |
| a.gens = w.gensOn |
| @@ -818,11 +1006,15 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s |
| host := hosts[w.intn(len(hosts))] |
| rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(sockDir, host+".sock"), |
| DBPath: filepath.Join(sockDir, host+".db"), Hibernate: true, Status: "ready"} |
| - switch w.intn(12) { |
| + switch w.intn(15) { |
| case 0, 1: |
| reqs.Add(1) |
| go func() { |
| defer reqs.Done() |
| + // An ordinary request: shared with other requests, never |
| + // with a held admission on the host (I5). |
| + w.heldHost[host].RLock() |
| + defer w.heldHost[host].RUnlock() |
| ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| defer cancel() |
| if release, err := a.beginRequest(ctx, rt); err == nil { |
| @@ -846,11 +1038,13 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s |
| go func() { |
| defer swaps.Done() |
| if wakeFirst { |
| + w.heldHost[host].RLock() |
| ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) |
| if release, err := a.beginRequest(ctx, rt); err == nil { |
| release() |
| } |
| cancel() |
| + w.heldHost[host].RUnlock() |
| } |
| w.checkSwap(at, a.Swap(context.Background(), at, newest)) |
| }() |
| @@ -885,6 +1079,15 @@ func simulateSwapOnce(seed int, staged map[string]simArtifact, sockDir string, s |
| // idle. |
| clk.advance(actStopTimeout + time.Second) |
| sweep() |
| + case 12, 13: |
| + // Edge-held streams: admit a held leg (I4, I5). |
| + reqs.Add(1) |
| + go func() { |
| + defer reqs.Done() |
| + w.admitHeld(a, sb, rt) |
| + }() |
| + case 14: |
| + w.finishHeld() |
| } |
| w.jitter() |
| } |