carlos / platform Public

activator: rootfs workers start after web is healthy, restart with backoff, stop first and are proven gone

Rootfs apps Plan 3 Group W, Task W1b (the Service half, #366). A rootfs
instance's declared workers start as doWake's last step, through
workerWakeGate, and are supervised on the resident tick: any exit, a
clean one included, is restarted with the co-spawn backoff (2 s doubling
to 60 s) through workerGate, never touching web. Every start passes the
host's release record and the stray rule. installRootfsWorkerLocked is
the one writer of a worker's handle, guarded by the install guard.
stop() stops and proves every worker in parallel before the sidecar
join and joinOps. Lease loss (the watch and the tick's unwatched arm)
stops them at once. An unproven worker is a stray: it keeps the lease
(releasable, finishStop) and its build pinned until the sweep proves it,
and its files go only after the proof. A worker is restarted only once
its earlier handles have ended (W1.17). RootfsWorkers reports per host.
Copy RFS-3-C08..C10. Dormant until a rootfs release declares a worker.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 2e7555637875c59ba394056ae4279b4c5f58722f parent 44b6cd5
15 files changed, +2,805 −62
  • approved_rootfs_copy_test.go +3 −0
  • internal/activator/activator.go +45 −6
  • internal/activator/backend_rootfs.go +9 −10
  • internal/activator/generations_file.go +11 −1
  • internal/activator/opset.go +6 −2
  • internal/activator/rootfs_install_guard_test.go +82 −30
  • internal/activator/rootfs_processes_test.go +20 −3
  • internal/activator/rootfs_service.go +19 −9
  • internal/activator/rootfs_staged_test.go +15 −1
  • internal/activator/rootfsrelease_test.go +24 −0
  • internal/activator/rootfsworkers.go +924 −0
  • internal/activator/rootfsworkers_test.go +1,600 −0
  • internal/activator/testdata/rootfs_verb_guard/install_worker.go +24 −0
  • internal/activator/testdata/rootfs_verb_guard/install_worker_clean.go +12 −0
  • internal/rolloutwords/words.go +11 −0
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index 4aa69ae8b..009656a5d 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -204,6 +204,9 @@ var rootfsCopyBuilt = []string{
// Plan 3 Group R, R2: the release's failure reasons
// (internal/rolloutwords/words.go)
"RFS-3-C01", "RFS-3-C02",
+ // Plan 3 Group W, W1b: the worker events
+ // (internal/rolloutwords/words.go)
+ "RFS-3-C08", "RFS-3-C09", "RFS-3-C10",
// Plan 4 Task 2: what the creating release says, and where a rootfs row
// may run (internal/console/rootfs.go)
"RFS-4-C01", "RFS-4-C02", "RFS-4-C05", "RFS-4-C06", "RFS-4-C07", "RFS-4-C08",
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 6495aff0f..3e43f1b60 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -833,6 +833,17 @@ type actEntry struct {
// exited (reapShedLocked): a terminal stop keeps the lease until then,
// and no respawn execs beside it.
shed *shedChild
+
+ // A rootfs instance's declared workers (Plan 3 Group W, W1): by name,
+ // started once web is healthy (startRootfsWorkers), supervised on the
+ // resident tick (superviseRootfsLocked) and stopped first by every
+ // stop (stopRootfsWorkers). strayRootfsWorkers are workers whose stop
+ // is not proven: they keep the lease (releasable) and their builds
+ // pinned until the sweep proves them. workerProofs is the claim of a
+ // stop or proof in flight per worker name. All written under a.mu.
+ rootfsWorkers map[string]*rootfsWorker
+ strayRootfsWorkers []*rootfsWorker
+ workerProofs map[string]chan struct{}
}
// shedChild is a respawn child that was exec'd and then refused at its
@@ -3019,10 +3030,12 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
}
w.steps.mark(a.now(), "sidecar")
}
- // 7. A rootfs build's declared processes beside web (Plan 3 Task D,
- // D8): logged, never started, and never a failure of this wake. W1
- // starts the workers here.
- a.rootfsProcessesHook(ctx, e, rt, w.gen)
+ // 7. A rootfs build's declared workers (Plan 3 Group W, W1; spec
+ // §5.4), once web is started, healthy and replicating. This stays the
+ // last step of doWake and doWake returns nil after it: a worker that
+ // does not start is never a failure of this wake, and the supervisor
+ // restarts it.
+ a.startRootfsWorkers(ctx, e, rt, w)
return w, nil
}
@@ -4358,6 +4371,15 @@ func (a *Service) stop(e *actEntry) {
bound.Stop() // the common case closes in milliseconds; don't leave a 2m timer standing
}
+ // A rootfs instance's workers stop first [pf W1.8, W1.9]: before the
+ // sidecar-start join and the barrier's drain, so a worker's stop is not
+ // queued behind a draining generation. Each is stopped and proven gone
+ // in parallel, after any start in flight has finished; one not proven
+ // is a stray, and releasable keeps the lease until the sweep proves it.
+ if !a.stopRootfsWorkers(e) {
+ log.Printf("activator: stop %s: a worker is not proven stopped; the lease is kept until it is", e.host)
+ }
+
// A sidecar restart (sweepOnce) runs its backend.StartSidecar call off
// a.mu (design §6.7) and may still be in flight when a stop begins. Wait,
// bounded by sidecarStopTimeout, for it to land: either it installs a
@@ -4806,6 +4828,18 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
a.mu.Unlock()
return
}
+ // And a rootfs worker (Group W, W1.20): one that may run, or a stray,
+ // keeps replication and the lease, here as well as in releasable.
+ a.mu.Lock()
+ workersLive := rootfsWorkersLiveLocked(e)
+ if workersLive {
+ a.keepPendingLocked(e, outcome)
+ }
+ a.mu.Unlock()
+ if workersLive {
+ log.Printf("activator: stop %s: a worker is not proven stopped; keeping replication and the lease until it is", e.host)
+ return
+ }
// Close = final sync + lease release. After a lost lease the release part
// fails harmlessly (someone else owns the lock); the sync still preserves
// a local checkpoint.
@@ -5814,11 +5848,13 @@ func (a *Service) Shutdown(ctx context.Context) {
// logUnresolvedAtExit names what Shutdown's budget ran out on: failed
// wakes not proven stopped, whose leases are kept, lease releases that
-// failed and were not resolved by a retry, and release commands not proven
-// stopped (each host with its build). The TTL frees each.
+// failed and were not resolved by a retry, release commands not proven
+// stopped (each host with its build), and rootfs workers not proven
+// stopped (each host with the worker's name; W1.21). The TTL frees each.
func (a *Service) logUnresolvedAtExit() {
a.mu.Lock()
var held, owed, releasing []string
+ workers := a.workerStraysAtExitLocked()
for host, u := range a.unprovenWakes {
held = append(held, fmt.Sprintf("%s (generation %d)", host, u.gen.N))
}
@@ -5829,6 +5865,9 @@ func (a *Service) logUnresolvedAtExit() {
releasing = append(releasing, fmt.Sprintf("%s (build %s)", host, op.build.Version))
}
a.mu.Unlock()
+ if len(workers) > 0 {
+ log.Printf("activator: shutdown: out of time with %d worker(s) not proven stopped, their instances' leases still held: %s", len(workers), strings.Join(workers, ", "))
+ }
if len(releasing) > 0 {
slices.Sort(releasing)
log.Printf("activator: shutdown: out of time with %d release command(s) not proven stopped, their leases still held: %s", len(releasing), strings.Join(releasing, ", "))
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go
index 91a65e611..82a28b53e 100644
--- a/internal/activator/backend_rootfs.go
+++ b/internal/activator/backend_rootfs.go
@@ -84,16 +84,15 @@ func (b *ExecBackend) Processes(rt registry.Route, id release.StagedIdentity) (m
return m.Processes, nil
}
-// rootfsProcessesHook is where a rootfs wake (doWake, after step 6) and
-// an overlap swap (swapOverlap, step 8) meet the processes the serving
-// build declares beside web. This box runs web and, before it, the
-// release (Group R: every wake and swap site runs it), so it reads
-// Processes(rt, stagedIdentityOf(g)) and logs, once per call, the workers
-// it does not run yet (D8); a refused read logs once. It starts nothing
-// and never fails a wake or a swap. Group W's W1 makes the doWake call
-// start the workers and W2 the swap's hand them over (ctx and e are
-// theirs). A binary row reads nothing. The caller does not hold a.mu: the
-// read is file I/O.
+// rootfsProcessesHook is where an overlap swap (swapOverlap, step 8)
+// meets the processes the serving build declares beside web. The release
+// runs at every wake and swap site (Group R), and a wake starts its
+// workers (startRootfsWorkers, Group W's W1), so only the swap is left
+// here: it reads Processes(rt, stagedIdentityOf(g)) and logs, once per
+// call, the workers a swap does not hand over yet (D8); a refused read
+// logs once. It starts nothing and never fails a swap. W2 replaces it with
+// the handover (ctx and e are W2's). A binary row reads nothing. The
+// caller does not hold a.mu: the read is file I/O.
func (a *Service) rootfsProcessesHook(ctx context.Context, e *actEntry, rt registry.Route, g Gen) {
if !rt.Rootfs() {
return
diff --git a/internal/activator/generations_file.go b/internal/activator/generations_file.go
index 0823acd20..5b46978e0 100644
--- a/internal/activator/generations_file.go
+++ b/internal/activator/generations_file.go
@@ -176,7 +176,8 @@ func (a *Service) generationsSnapshotLocked() release.Generations {
// stored, so both are on disk before either execs;
// - a socketless attempt's build and fallback (Task 11);
// - the generation every run not yet proven settled was admitted
-// against (merge ruling M2).
+// against (merge ruling M2);
+// - every rootfs worker's build, and every stray's (Group W).
//
// The plan's builds stay listed while the entry lives, as e.plan does
// (afterWake reads it after the wake): a few more pins than the processes
@@ -216,6 +217,15 @@ func (a *Service) entryGenerationsLocked(e *actEntry, add func(release.StagedIde
for _, h := range cmdHoldsLocked(e) {
gen(h.gen)
}
+ // A rootfs worker's build, its own identity (W1.19): from its start's
+ // registration, before root is asked, while it runs, and while it is a
+ // stray, whatever happened to its generation since.
+ for _, wk := range e.rootfsWorkers {
+ add(wk.build)
+ }
+ for _, wk := range e.strayRootfsWorkers {
+ add(wk.build)
+ }
}
// genIdentity is g as the generations file names it, and whether it is
diff --git a/internal/activator/opset.go b/internal/activator/opset.go
index ed56bdf14..b89ffe798 100644
--- a/internal/activator/opset.go
+++ b/internal/activator/opset.go
@@ -692,7 +692,9 @@ func (a *Service) reapExited(e *actEntry, m *genMember) {
// (settleCmds; run spec §5.3, merge ruling M1). A run writes the database
// as the serving process does, so it is held to the same rule, and so is a
// release command: no record of the host may be open, running or not
-// proven stopped (Group R, [pf R1.11]; finishStop asks it too). It runs
+// proven stopped (Group R, [pf R1.11]; finishStop asks it too), and so is
+// a rootfs worker: none may run, be starting or be a stray
+// (rootfsWorkersGone, Group W; finishStop asks it too). It runs
// without a.mu held; genTerminated may take DeadlineControl, and a run's
// settle up to cmdStopBound.
func (a *Service) releasable(e *actEntry) bool {
@@ -705,7 +707,9 @@ func (a *Service) releasable(e *actEntry) bool {
if members > 0 || strays > 0 || restoring || resizing || releasing {
return false
}
- return a.genTerminated(rt, g, p) && a.settleCmds(e)
+ // A rootfs instance's workers (Group W, W1.20): none runs, starts or is
+ // a stray; due strays are re-proven here, off a.mu.
+ return a.rootfsWorkersGone(e) && a.genTerminated(rt, g, p) && a.settleCmds(e)
}
// resizeInFlight reports whether a live size change of e is in flight
diff --git a/internal/activator/rootfs_install_guard_test.go b/internal/activator/rootfs_install_guard_test.go
index 66a45a27e..911f44678 100644
--- a/internal/activator/rootfs_install_guard_test.go
+++ b/internal/activator/rootfs_install_guard_test.go
@@ -9,6 +9,10 @@ package activator
// of their fields), their address taken, or an actEntry literal that sets
// one. Resolution is by type (go/types), so a member's or a wake's fields
// of the same names are not an entry's.
+//
+// Group W (W1.11) adds a second guarded field with one owner: a rootfs
+// worker's handle, rootfsWorker.proc, is written only by
+// installRootfsWorkerLocked, which installs it only under the lease watch.
import (
"go/ast"
@@ -27,6 +31,23 @@ var installGuardFields = []string{"proc", "gen", "rep"}
// installGuardOwner is the one function that may write them.
const installGuardOwner = "installProcLocked"
+// installGuard is one guarded type: its fields only owner (a Service
+// method) writes. tierOwner, for actEntry alone, may write exactly
+// X.gen.Tier. Rows are only added.
+type installGuard struct {
+ typ string
+ fields []string
+ owner string
+ tierOwner string
+}
+
+// installGuards: actEntry's process, generation and replica (Plan 3 Task
+// 8), and a rootfs worker's handle (Group W, W1.11).
+var installGuards = []installGuard{
+ {typ: "actEntry", fields: installGuardFields, owner: installGuardOwner, tierOwner: installGuardTierOwner},
+ {typ: "rootfsWorker", fields: []string{"proc"}, owner: "installRootfsWorkerLocked"},
+}
+
// installGuardTierOwner may write exactly X.gen.Tier and nothing else of
// the three: a swap's captured tier for the current generation, which
// installs nothing (recordCurrentTierLocked).
@@ -39,32 +60,34 @@ func isGenTier(info *types.Info, x ast.Expr) bool {
return false
}
inner, ok := se.X.(*ast.SelectorExpr)
- return ok && entryField(info, inner) == "gen"
+ return ok && entryField(info, inner, installGuards[0]) == "gen"
}
-// entryField reports the guarded actEntry field a selector names, or "".
-func entryField(info *types.Info, se *ast.SelectorExpr) string {
+// entryField reports the field of g's type a selector names, when g
+// guards it, or "".
+func entryField(info *types.Info, se *ast.SelectorExpr, g installGuard) string {
sel := info.Selections[se]
- if sel == nil || sel.Kind() != types.FieldVal || !slices.Contains(installGuardFields, se.Sel.Name) {
+ if sel == nil || sel.Kind() != types.FieldVal || !slices.Contains(g.fields, se.Sel.Name) {
return ""
}
t := sel.Recv()
if p, ok := t.(*types.Pointer); ok {
t = p.Elem()
}
- if n, ok := t.(*types.Named); ok && n.Obj().Name() == "actEntry" {
+ if n, ok := t.(*types.Named); ok && n.Obj().Name() == g.typ {
return se.Sel.Name
}
return ""
}
-// guardedField is the guarded entry field x writes through: x itself, or
-// any selector, index or star on the way down to it (e.gen.StagedPath).
-func guardedField(info *types.Info, x ast.Expr) string {
+// guardedField is the guarded field of g's type x writes through: x
+// itself, or any selector, index or star on the way down to it
+// (e.gen.StagedPath).
+func guardedField(info *types.Info, x ast.Expr, g installGuard) string {
for {
switch v := x.(type) {
case *ast.SelectorExpr:
- if f := entryField(info, v); f != "" {
+ if f := entryField(info, v, g); f != "" {
return f
}
x = v.X
@@ -80,13 +103,28 @@ func guardedField(info *types.Info, x ast.Expr) string {
}
}
-// installGuardViolations is every guarded write in f outside
-// installGuardOwner, as "<func>: <what>"; owned counts the writes inside it.
+// installGuardViolations is every guarded write in f outside its owner,
+// for every installGuards row, as "<func>: <what>"; owned counts, per
+// owner, the writes inside it.
+func installGuardViolations(pkg *packages.Package, f *ast.File) (violations []string, owned map[string]int) {
+ owned = map[string]int{}
+ for _, g := range installGuards {
+ v, n := installGuardViolationsOf(pkg, f, g)
+ violations = append(violations, v...)
+ owned[g.owner] += n
+ }
+ return violations, owned
+}
+
+// installGuardViolationsOf is every write in f of a field g guards outside
+// g's owner, as "<func>: <what>"; owned counts the writes inside it.
// Every declaration is read: a function's or method's body, and every
// package-level declaration whole (a var initialised with a function
-// literal or an actEntry literal), with no owner exemption for the latter.
-func installGuardViolations(pkg *packages.Package, f *ast.File) (violations []string, owned int) {
+// literal or a literal of the type), with no owner exemption for the
+// latter.
+func installGuardViolationsOf(pkg *packages.Package, f *ast.File, g installGuard) (violations []string, owned int) {
info := pkg.TypesInfo
+ typ := g.typ
for _, decl := range f.Decls {
var name string
var body ast.Node
@@ -115,14 +153,14 @@ func installGuardViolations(pkg *packages.Package, f *ast.File) (violations []st
continue
}
report := func(what string, x ast.Expr) {
- if name == "Service."+installGuardOwner {
+ if name == "Service."+g.owner {
owned++
return
}
- if name == installGuardTierOwner && x != nil && isGenTier(info, x) {
+ if g.tierOwner != "" && name == g.tierOwner && x != nil && isGenTier(info, x) {
return
}
- violations = append(violations, name+": "+what+" outside "+installGuardOwner)
+ violations = append(violations, name+": "+what+" outside "+g.owner)
}
ast.Inspect(body, func(n ast.Node) bool {
switch v := n.(type) {
@@ -131,26 +169,26 @@ func installGuardViolations(pkg *packages.Package, f *ast.File) (violations []st
return true
}
for _, lhs := range v.Lhs {
- if field := guardedField(info, lhs); field != "" {
- report("sets actEntry."+field, lhs)
+ if field := guardedField(info, lhs, g); field != "" {
+ report("sets "+typ+"."+field, lhs)
}
}
case *ast.IncDecStmt:
- if field := guardedField(info, v.X); field != "" {
- report("sets actEntry."+field, nil)
+ if field := guardedField(info, v.X, g); field != "" {
+ report("sets "+typ+"."+field, nil)
}
case *ast.UnaryExpr:
if v.Op == token.AND {
- if field := guardedField(info, v.X); field != "" {
- report("takes the address of actEntry."+field, nil)
+ if field := guardedField(info, v.X, g); field != "" {
+ report("takes the address of "+typ+"."+field, nil)
}
}
case *ast.CompositeLit:
- if n, ok := info.TypeOf(v).(*types.Named); ok && n.Obj().Name() == "actEntry" {
+ if n, ok := info.TypeOf(v).(*types.Named); ok && n.Obj().Name() == typ {
for _, elt := range v.Elts {
if kv, ok := elt.(*ast.KeyValueExpr); ok {
- if id, ok := kv.Key.(*ast.Ident); ok && slices.Contains(installGuardFields, id.Name) {
- report("builds an actEntry with "+id.Name, nil)
+ if id, ok := kv.Key.(*ast.Ident); ok && slices.Contains(g.fields, id.Name) {
+ report("builds an "+typ+" with "+id.Name, nil)
}
}
}
@@ -178,6 +216,14 @@ var installGuardFixtures = map[string][]string{
"package-level installResidentGen: sets actEntry.gen outside"},
"install_pkglit.go": {"package-level residentEntry: builds an actEntry with proc",
"package-level residentEntries: builds an actEntry with gen"},
+ // Group W, W1.11: a rootfs worker's handle written around its owner,
+ // in each shape, and the owner's namesake on another receiver.
+ "install_worker.go": {"Service.installGuardWorker: sets rootfsWorker.proc outside installRootfsWorkerLocked",
+ "Service.installGuardWorkerTuple: sets rootfsWorker.proc outside",
+ "Service.installGuardWorkerAddr: takes the address of rootfsWorker.proc outside",
+ "Service.installGuardWorkerLiteral: builds an rootfsWorker with proc",
+ "shedChild.installRootfsWorkerLocked: sets rootfsWorker.proc outside"},
+ "install_worker_clean.go": nil,
}
func TestResidentProcessInstallsGoThroughOnePlace(t *testing.T) {
@@ -186,21 +232,27 @@ func TestResidentProcessInstallsGoThroughOnePlace(t *testing.T) {
t.Fatal(err)
}
files := packageFiles(pkg)
- owned := 0
+ owned := map[string]int{}
for base, f := range files {
if strings.HasPrefix(base, verbGuardFixturePrefix) || strings.HasSuffix(base, "_test.go") {
continue
}
v, n := installGuardViolations(pkg, f)
- owned += n
+ for o, c := range n {
+ owned[o] += c
+ }
for _, p := range v {
t.Errorf("%s: %s", base, p)
}
}
// A guard that resolved nothing proves nothing: installProcLocked's own
- // three writes (rep, proc, gen) must be seen.
- if owned < 3 {
- t.Fatalf("the guard saw %d writes inside %s, want its 3: it resolves nothing", owned, installGuardOwner)
+ // three writes (rep, proc, gen) must be seen, and
+ // installRootfsWorkerLocked's one.
+ if owned[installGuardOwner] < 3 {
+ t.Fatalf("the guard saw %d writes inside %s, want its 3: it resolves nothing", owned[installGuardOwner], installGuardOwner)
+ }
+ if owned["installRootfsWorkerLocked"] < 1 {
+ t.Fatalf("the guard saw %d writes inside installRootfsWorkerLocked, want its 1: it resolves nothing", owned["installRootfsWorkerLocked"])
}
for fixture, want := range installGuardFixtures {
t.Run(fixture, func(t *testing.T) {
diff --git a/internal/activator/rootfs_processes_test.go b/internal/activator/rootfs_processes_test.go
index ffa948e2d..6dce1fc8b 100644
--- a/internal/activator/rootfs_processes_test.go
+++ b/internal/activator/rootfs_processes_test.go
@@ -321,9 +321,26 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
done()
evs.wait(t, GenHealthy)
onlyStart(t, ctl, next)
- onlyWebAsked(t, ctl)
- if n := logs.count(workersLine(rt.Host, "v2", "jobs, mailer")); n != 1 {
- t.Errorf("the workers line was logged %d times, want once; logs:\n%s", n, logs)
+ // Group W (W1.12): the wake starts the declared workers, through
+ // root's worker start, and no longer logs D8's workers line. No
+ // command, no binary start, and root's images are web's and the
+ // two workers', in that order.
+ noBinaryStart(t, ctl)
+ noCallStarts(t, ctl.fakeControl, "cmd-rootfs")
+ for _, w := range []string{"jobs", "mailer"} {
+ ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+lb.rt.Host+" "+w+" ")
+ }
+ ctl.fakeControl.mu.Lock()
+ var procs []string
+ for _, img := range ctl.fakeControl.rootfsImages {
+ procs = append(procs, img.Process)
+ }
+ ctl.fakeControl.mu.Unlock()
+ if want := []string{release.ProcessWeb, "jobs", "mailer"}; !slices.Equal(procs, want) {
+ t.Errorf("root's images ran %v, want %v", procs, want)
+ }
+ if n := logs.count(workersLine(rt.Host, "v2", "jobs, mailer")) + logs.matching(rt.Host, "does not run workers yet"); n != 0 {
+ t.Errorf("the workers line was logged %d times, want none; logs:\n%s", n, logs)
}
noReleaseLine(t, logs, rt.Host)
if !entryAwake(a, rt.Host) {
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index e8d21bd9d..1975c1042 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -658,10 +658,11 @@ func (a *Service) residentOrderLocked(routes []registry.Route) []registry.Route
// sweep's crash arm stops one (StopExited), so a crash is seen within
// residentPoll rather than the sweep's 30 s. A resident with no lease
// watch (its replica has no lease signal), awake or stopping, whose
-// replica reports its lease lost has its generations killed once and
-// its stop begun (residentLeaseLostLocked): the second line under the
-// watch installProcLocked installs. Then superviseRootfsLocked for
-// every other awake rootfs entry.
+// replica reports its lease lost has its generations killed once, its
+// workers stopped (stopRootfsWorkersAtLoss) and its stop begun
+// (residentLeaseLostLocked): the second line under the watch
+// installProcLocked installs. Then superviseRootfsLocked (the
+// workers, Group W) for every other awake rootfs entry.
// 3. A host no longer listed is forgotten. Each listed row, from just
// after the last host reserved (residentOrderLocked), not held
// (residentHeldLocked), not starting, not waiting (residentWaitingLocked),
@@ -695,6 +696,7 @@ func (a *Service) rootfsTick() {
e.ownerKilled = true
if gens := a.residentLeaseLostLocked(e, err); gens != nil {
go a.killResidentGens(e.route, gens)
+ go a.stopRootfsWorkersAtLoss(e) // [pf W1.10]
}
continue
}
@@ -921,12 +923,24 @@ func (a *Service) residentLeaseShort(e *actEntry, left time.Duration) {
// residentLeaseLost is the loss itself: e is stopped if it is still awake,
// and every generation it has is killed and proven gone, off a.mu.
+//
+// Its workers are stopped at the same moment, beside the kills and
+// without waiting for the entry's stop [pf W1.10]: root kills only a
+// generation, so each is stopped and proven gone (stopRootfsWorkersAtLoss).
func (a *Service) residentLeaseLost(e *actEntry, err error) {
a.mu.Lock()
gens := a.residentLeaseLostLocked(e, err)
+ rt := e.route
a.mu.Unlock()
if gens != nil {
- a.killResidentGens(e.route, gens)
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ a.stopRootfsWorkersAtLoss(e)
+ }()
+ a.killResidentGens(rt, gens)
+ wg.Wait()
}
}
@@ -985,10 +999,6 @@ func (a *Service) killResidentGens(rt registry.Route, gens []uint64) {
wg.Wait()
}
-// superviseRootfsLocked is the resident tick's supervision hook for an awake
-// rootfs entry. A no-op in group A; W1 fills it with worker supervision.
-func (a *Service) superviseRootfsLocked(e *actEntry) {}
-
// noteResidentWakeLocked is a wake's outcome for residency, in wake's final
// critical section. A proactive wake (e.resident) gives back its
// reservation. For any wake of a resident row, proactive or by request, a
diff --git a/internal/activator/rootfs_staged_test.go b/internal/activator/rootfs_staged_test.go
index 0c8e68514..4985e7380 100644
--- a/internal/activator/rootfs_staged_test.go
+++ b/internal/activator/rootfs_staged_test.go
@@ -40,6 +40,11 @@ type stagedRootfsCtl struct {
units map[string][3]string // unit -> ActiveState, InvocationID, "populated" or ""
starts []stagedRootfsStart
serve func(gen uint64, img instancectl.StagedImage)
+ // workerStopErr, when set, is what a worker's StopRootfs answers (a
+ // stop root could not prove), leaving its unit as it was; every other
+ // stop is unaffected (Group W).
+ workerStopErr error
+ workerStarts int
}
type stagedRootfsStart struct {
@@ -68,9 +73,18 @@ func (c *stagedRootfsCtl) StopRootfs(ctx context.Context, host string, role inst
if err := c.fakeControl.StopRootfs(ctx, host, role, gen, worker, kill); err != nil {
return err
}
+ c.umu.Lock()
+ werr := c.workerStopErr
+ c.umu.Unlock()
+ if role == instancectl.RoleWorker && werr != nil {
+ return werr
+ }
unit := instancectl.RootfsUnitName(role, host)
- if gen != 0 {
+ switch {
+ case gen != 0:
unit = instancectl.RootfsGenUnitName(host, gen)
+ case role == instancectl.RoleWorker:
+ unit = instancectl.WorkerUnitName(host, worker)
}
c.umu.Lock()
if u, ok := c.units[unit]; ok {
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
index 7ade349e5..d609dc3ca 100644
--- a/internal/activator/rootfsrelease_test.go
+++ b/internal/activator/rootfsrelease_test.go
@@ -1851,6 +1851,30 @@ func TestReleaseOpConsumersReadTheRecord(t *testing.T) {
t.Fatal("the claim was read for a host with an open release record")
}
})
+
+ // A rootfs worker's start (Group W, [pf W0.1]): a restart is refused
+ // while the host's record exists, asking root nothing, and starts on
+ // the first tick after the record is gone.
+ t.Run("a worker start", func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ openReleaseRecord(r.a, r.host)
+ r.clk.advance(sidecarRestartMax)
+ r.tick(t)
+ if n := len(r.b.workers("jobs")); n != 1 {
+ t.Fatalf("root was asked for %d worker starts over an open release record", n-1)
+ }
+ r.a.mu.Lock()
+ delete(r.a.releaseOps, r.host)
+ r.a.mu.Unlock()
+ r.clk.advance(sidecarRestartMax)
+ r.tick(t)
+ if n := len(r.b.workers("jobs")); n != 2 {
+ t.Fatalf("%d worker starts after the record went, want 1", n-1)
+ }
+ })
}
// INV-R2: an unproven release of an awake incumbent, whose owner never
diff --git a/internal/activator/rootfsworkers.go b/internal/activator/rootfsworkers.go
new file mode 100644
index 000000000..a6ca493af
--- /dev/null
+++ b/internal/activator/rootfsworkers.go
@@ -0,0 +1,924 @@
+package activator
+
+// Rootfs apps Plan 3, Group W, Task W1b: the Service half of a rootfs
+// instance's workers (spec §5.4). The workers a build declares start once
+// its web is healthy (doWake's last step), run beside it under its lease,
+// are restarted with the co-spawn backoff whenever they exit (a clean exit
+// included), never take web down, stop first and are proven gone before
+// the lease goes, stop at once when the lease is lost, and are reported
+// per host. The backend half is W1a's RootfsWorkerBackend.
+//
+// Every write below is under a.mu; every control request, file write,
+// manifest read and proof runs off it. A worker's handle is written only
+// by installRootfsWorkerLocked (TestResidentProcessInstallsGoThroughOnePlace).
+//
+// One worker unit exists per host and name, whatever the generation, so a
+// proof is by name (RootfsWorkerGone): it proves the live worker of that
+// name and every stray of it. Work on one name is serialised two ways: a
+// start (doWake's or a restart's) holds starting and startDone, and a
+// stop or a stray's re-proof holds the name's claim (workerProofs). A stop
+// waits for the starts; the lease-loss stop and the stray re-proof skip a
+// name that is starting, whose own cleanup proves what it started.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "slices"
+ "strconv"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rolloutwords"
+)
+
+// rootfsWorker is one declared worker of a rootfs entry, or a stray of one
+// (a worker whose stop is not proven). Every field is written under a.mu.
+type rootfsWorker struct {
+ name string
+ // proc is the worker's handle. Set only in installRootfsWorkerLocked
+ // [pf W1.11]; it stays the last installed handle until the next
+ // install, so an exited one is what the supervisor reads.
+ proc Proc
+ // gen is the generation whose environment and image the worker runs.
+ gen uint64
+ // build is stagedIdentityOf that generation. It is the worker's own
+ // pin in the generations file, kept through a stray until proven gone,
+ // so it survives dropMember of its generation.
+ build release.StagedIdentity
+ started time.Time
+ // retryAt is when the next restart may run. Zero means an exit not yet
+ // noted (superviseRootfsLocked notes it, and sets it); set means the
+ // exit is noted and the restart waits for it.
+ retryAt time.Time
+ backoff time.Duration
+ restarts int
+ // crashLoop: the backoff reached sidecarRestartMax.
+ crashLoop bool
+ // starting marks a start in flight off a.mu; startDone is closed when
+ // it has finished, however it finished.
+ starting bool
+ startDone chan struct{}
+ // lastExitEvent is when RFS-3-C09 was last emitted, at most once a
+ // minute in a crash loop.
+ lastExitEvent time.Time
+ // startFailed: the last start installed nothing (no handle, or one
+ // proven gone or left a stray), so the exit the supervisor notes has
+ // no exit record of its own.
+ startFailed bool
+ // strayAt is when a stray's stop was last tried: the sweep re-tries it
+ // at most every actStopTimeout.
+ strayAt time.Time
+ // unproven is a stray's handle whose stop was not proven (nil when
+ // none was returned). Each re-proof stops it again, to close its
+ // listeners once its observer has returned, and no worker of its name
+ // starts until it has ended [pf W1.17].
+ unproven Proc
+}
+
+// WorkerReport is one worker's line for a host (W1.25).
+type WorkerReport struct {
+ Name string
+ State string // WorkerRunning, WorkerRestarting, WorkerCrashLoop or WorkerStopped
+ Restarts int
+}
+
+// The states RootfsWorkers reports.
+const (
+ WorkerRunning = "running"
+ WorkerRestarting = "restarting"
+ WorkerCrashLoop = "crash-loop"
+ WorkerStopped = "stopped"
+)
+
+// workerListenerWait bounds a worker handle's own Stop, asked only to close
+// its listeners once the unit is proven gone or has exited [pf W1.8, W1.17].
+// The termination proof is RootfsWorkerGone's, on its own bounds.
+const workerListenerWait = 2 * time.Second
+
+// errWorkerStray refuses a worker's start beside a stray it must not run
+// beside (W1.14): a worker of another generation, or of the same name,
+// whose stop is not proven.
+var errWorkerStray = errors.New("activator: a worker of this instance is not proven stopped")
+
+// errWorkerGeneration refuses a worker's restart once its generation is no
+// longer the entry's current one (a swap's handover is W2's).
+var errWorkerGeneration = errors.New("activator: the worker's generation is no longer the instance's current one")
+
+// rootfsWorkerFiles is the backend's removal of a worker's files, called
+// only over RootfsWorkerGone's nil (INV-2). ExecBackend has it; SplitBackend
+// forwards it for an exec row.
+type rootfsWorkerFiles interface {
+ removeRootfsWorkerFiles(rt registry.Route, name string)
+}
+
+var (
+ _ rootfsWorkerFiles = (*ExecBackend)(nil)
+ _ rootfsWorkerFiles = (*SplitBackend)(nil)
+)
+
+// removeRootfsWorkerFiles forwards to the exec side for an exec row; a
+// unit-backed row has no worker files.
+func (b *SplitBackend) removeRootfsWorkerFiles(rt registry.Route, name string) {
+ if rt.Backing != registry.BackingUnit {
+ if f, ok := b.Exec.(rootfsWorkerFiles); ok {
+ f.removeRootfsWorkerFiles(rt, name)
+ }
+ }
+}
+
+// workerExitReader is a worker handle that kept its exit record
+// (unitProc.WorkerExit).
+type workerExitReader interface {
+ WorkerExit() (instancectl.ExitRecord, bool)
+}
+
+// workerNames is the workers procs declares, sorted, refused unless the
+// declaration passes the ship door's own rule [pf W1.15].
+func workerNames(procs map[string]release.Process) ([]string, error) {
+ if err := release.ValidateProcesses(procs); err != nil {
+ return nil, err
+ }
+ var names []string
+ for name := range procs {
+ if release.ValidWorkerName(name) {
+ names = append(names, name)
+ }
+ }
+ slices.Sort(names)
+ return names, nil
+}
+
+// startRootfsWorkers is doWake's last step (spec §5.4): with web started,
+// healthy and replicating, the workers the wake's generation declares
+// start, in name order, one at a time, each through workerWakeGate. A
+// declaration that cannot be read or is not valid starts none and logs
+// once; web serves. A worker that fails to start is no failure of the wake:
+// it is left for the supervisor to restart. The caller does not hold a.mu.
+func (a *Service) startRootfsWorkers(ctx context.Context, e *actEntry, rt registry.Route, w *wokenInstance) {
+ if !rt.Rootfs() || e.worker {
+ return
+ }
+ procs, err := a.declaredProcesses(rt, w.gen)
+ if err != nil {
+ log.Printf("activator: %s: build %s: its declared processes cannot be read, so this box runs web alone: %v", rt.Host, w.gen.Build, err)
+ return
+ }
+ names, err := workerNames(procs)
+ if err != nil {
+ log.Printf("activator: %s: build %s: its declared processes are not valid, so this box runs no worker of it: %v", rt.Host, w.gen.Build, err)
+ return
+ }
+ if len(names) == 0 {
+ return
+ }
+ wb, ok := a.backend.(RootfsWorkerBackend)
+ if !ok {
+ log.Printf("activator: %s: build %s declares workers (%s); this backend cannot run them, so web runs alone", rt.Host, w.gen.Build, strings.Join(names, ", "))
+ return
+ }
+ build, err := stagedIdentityOf(w.gen)
+ if err != nil {
+ log.Printf("activator: %s: build %s: no worker started: %v", rt.Host, w.gen.Build, err)
+ return
+ }
+ for _, name := range names {
+ wk := &rootfsWorker{name: name, gen: w.gen.N, build: build, starting: true, startDone: make(chan struct{})}
+ a.mu.Lock()
+ if a.entries[e.host] != e || e.state != actWaking {
+ a.mu.Unlock()
+ return
+ }
+ if e.rootfsWorkers == nil {
+ e.rootfsWorkers = map[string]*rootfsWorker{}
+ }
+ e.rootfsWorkers[name] = wk
+ a.mu.Unlock()
+ a.runWorkerStart(ctx, wb, e, rt, wk, w.gen, w.proc, a.workerWakeGate(e, w.gen, w.rep, name))
+ }
+}
+
+// workerWakeGate is the doWake start's gate [pf W1.13, W1.14, W0.1], asked
+// under a.mu right before root is (runExecGate): the entry is the host's,
+// unfenced, not shutting down (ownedLocked, waking) and still waking; the
+// startup sweep proved the box clean; the wake's replica holds the lease;
+// no release record of the host is open; and the stray rule.
+func (a *Service) workerWakeGate(e *actEntry, g Gen, rep Rep, name string) func() error {
+ return func() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if err := a.ownedLocked(e, true); err != nil {
+ return err
+ }
+ if !a.rootfsSwept.Load() {
+ return errRootfsUnswept
+ }
+ if e.state != actWaking {
+ return errSwapNotAwake
+ }
+ if rep == nil || rep.Err() != nil {
+ return errSwapLeaseLost
+ }
+ if a.releaseOps[e.host] != nil {
+ return errReleaseOpen
+ }
+ return workerStrayRuleLocked(e, g.N, name)
+ }
+}
+
+// workerGate is every later start's gate (a restart; W2's handover), asked
+// under a.mu right before root is: the startup sweep proved the box clean;
+// the entry is the host's, awake, unfenced, its replica holding the lease
+// (ownedLocked); its current generation is the worker's; the worker is
+// still the entry's; no release record is open; and the stray rule.
+func (a *Service) workerGate(e *actEntry, wk *rootfsWorker) func() error {
+ return func() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if !a.rootfsSwept.Load() {
+ return errRootfsUnswept
+ }
+ if err := a.ownedLocked(e, false); err != nil {
+ return err
+ }
+ if e.gen.N != wk.gen {
+ return errWorkerGeneration
+ }
+ if e.rootfsWorkers[wk.name] != wk {
+ return errSwapSuperseded
+ }
+ if a.releaseOps[e.host] != nil {
+ return errReleaseOpen
+ }
+ return workerStrayRuleLocked(e, wk.gen, wk.name)
+ }
+}
+
+// workerStrayRuleLocked refuses a start of worker name of generation gen
+// while any stray of the entry is of another generation or has that name
+// [pf W1.14]. The caller holds a.mu.
+func workerStrayRuleLocked(e *actEntry, gen uint64, name string) error {
+ for _, s := range e.strayRootfsWorkers {
+ if s.gen != gen || s.name == name {
+ return fmt.Errorf("%w: worker %s of generation %d", errWorkerStray, s.name, s.gen)
+ }
+ }
+ return nil
+}
+
+// installRootfsWorkerLocked is the one writer of rootfsWorker.proc [pf
+// W1.11]. It installs only on the host's own entry, for a worker that is
+// still the entry's, while the entry is waking (doWake's start) or awake
+// and owned; an awake resident only with its lease watch present (or a
+// replica with no lease signal, which the tick watches). It reports
+// whether it installed; refused, the caller stops what it started and
+// proves it gone. The caller holds a.mu.
+func (a *Service) installRootfsWorkerLocked(e *actEntry, wk *rootfsWorker, proc Proc) bool {
+ if a.entries[e.host] != e || e.rootfsWorkers[wk.name] != wk {
+ return false
+ }
+ switch {
+ case e.state == actWaking:
+ case e.state == actAwake && a.ownedLocked(e, false) == nil:
+ if e.route.Resident() && !residentWatchedLocked(e) {
+ return false
+ }
+ default:
+ return false
+ }
+ wk.proc = proc
+ return true
+}
+
+// residentWatchedLocked reports whether an awake resident is under its
+// lease watch: the watch is running, or its replica has no lease signal
+// for one, so the tick's rep.Err check is its watch (as
+// watchResidentLeaseLocked decides). The caller holds a.mu.
+func residentWatchedLocked(e *actEntry) bool {
+ if e.ownerDone != nil {
+ return true
+ }
+ _, signal := e.rep.(residentOwnership)
+ return !signal
+}
+
+// runWorkerStart is one start of wk, off a.mu, for doWake and for a
+// restart: publish the pins, launch with gate on ctx, install. It always
+// ends with wk.starting false and wk.startDone closed, and by then
+// whatever it started is installed, proven gone, or a stray.
+func (a *Service) runWorkerStart(ctx context.Context, wb RootfsWorkerBackend, e *actEntry, rt registry.Route, wk *rootfsWorker, g Gen, web Proc, gate func() error) {
+ var (
+ installed, refused bool
+ stray bool
+ started Proc // a handle root returned and that was not installed
+ )
+ defer func() {
+ a.mu.Lock()
+ now := a.now()
+ switch {
+ case installed:
+ wk.started, wk.retryAt, wk.startFailed = now, time.Time{}, false
+ case refused:
+ // Not a crash: the exit is treated as noted, and the start is
+ // asked again after the current backoff.
+ wk.startFailed = true
+ wk.retryAt = now.Add(max(wk.backoff, sidecarRestartBase))
+ default:
+ wk.started, wk.retryAt, wk.startFailed = time.Time{}, time.Time{}, true
+ }
+ switch {
+ case stray:
+ a.strayWorkerLocked(e, wk, now, started)
+ case started != nil && !workerEnded(started) && (e.state == actAwake || e.state == actWaking):
+ // Proven gone, but the handle's observer has not returned: kept
+ // as a stray, due again at once, so no worker of its name is
+ // prepared beside it [pf W1.17].
+ a.strayWorkerLocked(e, wk, now, started)
+ wk.strayAt = time.Time{}
+ }
+ wk.starting = false
+ close(wk.startDone)
+ a.mu.Unlock()
+ if installed {
+ emitEvent(a.Logs, rt, "info", fmt.Sprintf(rolloutwords.EventWorkerStarted, wk.name))
+ }
+ }()
+ // The worker's build is in the generations file before root is asked
+ // (W1.19): its entry already lists it.
+ if err := a.publishBeforeExec(); err != nil {
+ log.Printf("activator: %s: worker %s not started: %v; the next tick retries", rt.Host, wk.name, err)
+ refused = true
+ return
+ }
+ p, err := wb.LaunchRootfsWorker(withExecGate(ctx, gate), rt, wk.name, g, web)
+ if err != nil {
+ if p == nil && !startMayHaveRun(nil, err) {
+ // Nothing ran. A gate's refusal is no crash.
+ refused = launchNotStarted(err)
+ log.Printf("activator: %s: worker %s of build %s not started: %v", rt.Host, wk.name, g.Build, err)
+ return
+ }
+ // The start may have run: proven gone, or a stray.
+ log.Printf("activator: %s: worker %s of build %s may have started: %v; proving it gone", rt.Host, wk.name, g.Build, err)
+ started = p
+ stray = a.proveWorkerGone(wb, rt, wk.name, p) != nil
+ return
+ }
+ a.mu.Lock()
+ installed = a.installRootfsWorkerLocked(e, wk, p)
+ a.mu.Unlock()
+ if !installed {
+ // The entry left waking or awake (a stop, a lost lease) while root
+ // started it: stopped and proven before startDone closes.
+ log.Printf("activator: %s: worker %s started as its instance stopped or lost its lease; stopping it", rt.Host, wk.name)
+ started = p
+ stray = a.proveWorkerGone(wb, rt, wk.name, p) != nil
+ }
+}
+
+// proveWorkerGone stops worker name and proves it gone, off a.mu [pf W1.8]:
+// each handle's stopRequested first, so its observer never stops a later
+// invocation as foreign; then RootfsWorkerGone on its own bounds; then each
+// handle's Stop on a short context, only to close its listeners. Proven,
+// the worker's files go (INV-2). nil is the proof. ps are the name's
+// handles: the live one and any stray's (nil entries are skipped).
+func (a *Service) proveWorkerGone(wb RootfsWorkerBackend, rt registry.Route, name string, ps ...Proc) error {
+ for _, p := range ps {
+ if up, ok := p.(*unitProc); ok {
+ up.stopRequested.Store(true)
+ }
+ }
+ err := wb.RootfsWorkerGone(context.Background(), rt, name)
+ for _, p := range ps {
+ if p != nil {
+ ctx, cancel := context.WithTimeout(context.Background(), workerListenerWait)
+ _ = p.Stop(ctx)
+ cancel()
+ }
+ }
+ if err != nil {
+ log.Printf("activator: %s: worker %s is not proven stopped: %v; the lease is kept until it is", rt.Host, name, err)
+ return err
+ }
+ if f, ok := a.backend.(rootfsWorkerFiles); ok {
+ f.removeRootfsWorkerFiles(rt, name)
+ }
+ return nil
+}
+
+// strayWorkerLocked records wk, whose stop is not proven, as a stray: it
+// leaves rootfsWorkers, and a fresh worker of the same name takes its
+// place there (proc unset, its pacing kept) on an entry still awake, so
+// the supervisor restarts it once the stray is proven. p is the handle
+// whose stop was not proven (nil: wk's own). The caller holds a.mu.
+func (a *Service) strayWorkerLocked(e *actEntry, wk *rootfsWorker, now time.Time, p Proc) {
+ wk.strayAt = now
+ if p == nil {
+ p = wk.proc
+ }
+ wk.unproven = p
+ if !slices.Contains(e.strayRootfsWorkers, wk) {
+ e.strayRootfsWorkers = append(e.strayRootfsWorkers, wk)
+ }
+ if e.rootfsWorkers[wk.name] != wk {
+ return
+ }
+ delete(e.rootfsWorkers, wk.name)
+ if e.state == actAwake || e.state == actWaking {
+ e.rootfsWorkers[wk.name] = &rootfsWorker{name: wk.name, gen: wk.gen, build: wk.build,
+ retryAt: now.Add(max(wk.backoff, sidecarRestartBase)), backoff: wk.backoff, restarts: wk.restarts,
+ crashLoop: wk.crashLoop, lastExitEvent: wk.lastExitEvent, startFailed: true}
+ }
+}
+
+// superviseRootfsLocked supervises an awake rootfs entry's workers on the
+// resident tick (W1.22), under a.mu, with no I/O. A worker whose handle has
+// ended, or that has none, is a crash whatever its exit status (Review
+// Focus 3): the exit is noted once (the backoff, RFS-3-C09 or C10) and the
+// restart runs once the backoff has passed, as a goroutine. A stray due
+// for another try is re-proven, off a.mu. Nothing here stops web.
+func (a *Service) superviseRootfsLocked(e *actEntry) {
+ if len(e.rootfsWorkers) == 0 && len(e.strayRootfsWorkers) == 0 {
+ return
+ }
+ now := a.now()
+ a.reproveStraysLocked(e, now)
+ for _, name := range sortedWorkerNames(e.rootfsWorkers) {
+ wk := e.rootfsWorkers[name]
+ if wk.starting || e.workerProofs[name] != nil {
+ continue
+ }
+ if wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc) {
+ continue // running
+ }
+ if wk.retryAt.IsZero() {
+ a.noteWorkerExitLocked(e, wk, now)
+ continue
+ }
+ if now.Before(wk.retryAt) {
+ continue
+ }
+ a.restartRootfsWorkerLocked(e, wk)
+ }
+}
+
+// workerEnded reports whether a worker's handle has ended: a unit handle
+// once its observer has finished (its exit record is kept by then), any
+// other once Exited.
+func workerEnded(p Proc) bool {
+ if up, ok := p.(*unitProc); ok {
+ select {
+ case <-up.done:
+ return true
+ default:
+ return false
+ }
+ }
+ return p.Exited()
+}
+
+// noteWorkerExitLocked notes one exit of wk (or one failed start): the
+// backoff (sidecarRestartBase doubling to sidecarRestartMax, reset by a
+// run of sidecarHealthyRun), the restart count, and the member's event:
+// RFS-3-C10 once on entering the crash loop, RFS-3-C09 with the delay
+// otherwise (at most once a minute in the loop). An exit with no status to
+// tell gives an operator line instead of C09 [pf W1.16]. The caller holds
+// a.mu.
+func (a *Service) noteWorkerExitLocked(e *actEntry, wk *rootfsWorker, now time.Time) {
+ if !wk.started.IsZero() && now.Sub(wk.started) >= sidecarHealthyRun {
+ wk.backoff, wk.crashLoop = 0, false
+ }
+ if wk.backoff == 0 {
+ wk.backoff = sidecarRestartBase
+ } else {
+ wk.backoff = min(wk.backoff*2, sidecarRestartMax)
+ }
+ wk.restarts++
+ wk.retryAt = now.Add(wk.backoff)
+ entered := !wk.crashLoop && wk.backoff >= sidecarRestartMax
+ if wk.backoff >= sidecarRestartMax {
+ wk.crashLoop = true
+ }
+ status, ok := -1, false
+ if !wk.startFailed {
+ status, ok = workerExitStatus(wk.proc)
+ }
+ wait := time.Duration(retryAfterSeconds(wk.backoff)) * time.Second
+ switch {
+ case entered:
+ emitEvent(a.Logs, e.route, "error", fmt.Sprintf(rolloutwords.EventWorkerCrashLoop, wk.name))
+ case !ok:
+ log.Printf("activator: %s: worker %s ended with no exit status to tell (a failed start, no exit record, or an unknown signal); starting it again in %s", e.host, wk.name, wait)
+ case wk.crashLoop && !wk.lastExitEvent.IsZero() && now.Sub(wk.lastExitEvent) < time.Minute:
+ default:
+ wk.lastExitEvent = now
+ emitEvent(a.Logs, e.route, "warn", fmt.Sprintf(rolloutwords.EventWorkerExited, wk.name, status, wait.String()))
+ }
+}
+
+// workerSignals numbers the signals a worker's exit record may name
+// [pf W1.16]: a signal death's status is 128 plus its number.
+var workerSignals = map[string]int{
+ "HUP": 1, "INT": 2, "QUIT": 3, "ILL": 4, "ABRT": 6, "BUS": 7, "FPE": 8,
+ "KILL": 9, "SEGV": 11, "PIPE": 13, "ALRM": 14, "TERM": 15,
+}
+
+// workerExitStatus is the status RFS-3-C09 names for p's end: the exit
+// code of an "exited" record with a numeric status, 128 plus the number of
+// a known signal for "killed" or "dumped"; ok is false for no record or an
+// unknown signal.
+func workerExitStatus(p Proc) (int, bool) {
+ r, ok := p.(workerExitReader)
+ if !ok {
+ return 0, false
+ }
+ rec, ok := r.WorkerExit()
+ if !ok {
+ return 0, false
+ }
+ switch rec.Code {
+ case "exited":
+ n, err := strconv.Atoi(rec.Status)
+ return n, err == nil && n >= 0
+ case "killed", "dumped":
+ n, known := workerSignals[strings.TrimPrefix(strings.ToUpper(rec.Status), "SIG")]
+ return 128 + n, known
+ }
+ return 0, false
+}
+
+// restartRootfsWorkerLocked restarts wk as a goroutine, in the sidecar
+// restart's shape: (i) the old handle's Stop on a short context, only to
+// close its listeners; (ii) RootfsWorkerGone, so the old invocation is
+// proven gone before a new one starts [pf W1.17] (unproven, it becomes a
+// stray and nothing starts beside it); (iii) to (v) runWorkerStart, on a
+// context bounded by DeadlineControl and the Service's lifetime, through
+// workerGate, installing only on the same entry still awake. The caller
+// holds a.mu.
+func (a *Service) restartRootfsWorkerLocked(e *actEntry, wk *rootfsWorker) {
+ wb, ok := a.backend.(RootfsWorkerBackend)
+ if !ok {
+ return
+ }
+ if e.gen.N != wk.gen {
+ // The entry's generation moved on (a swap; W2 hands workers
+ // over): not a crash, asked again after the backoff.
+ wk.retryAt = a.now().Add(max(wk.backoff, sidecarRestartBase))
+ return
+ }
+ wk.starting = true
+ wk.startDone = make(chan struct{})
+ rt, g, web := e.route, e.gen, e.proc
+ handles := workerHandlesLocked(e, wk.name)
+ needProof := len(handles) > 0 || slices.ContainsFunc(e.strayRootfsWorkers, func(s *rootfsWorker) bool { return s.name == wk.name })
+ go func() {
+ if needProof {
+ if err := a.proveWorkerGone(wb, rt, wk.name, handles...); err != nil {
+ a.mu.Lock()
+ a.strayWorkerLocked(e, wk, a.now(), nil)
+ wk.starting = false
+ close(wk.startDone)
+ a.mu.Unlock()
+ return
+ }
+ a.mu.Lock()
+ a.dropProvenStraysLocked(e, wk.name)
+ // [pf W1.17] The unit is proven gone; every earlier handle of
+ // the name must also have ended (its observer returned, its
+ // listeners closed) before prepare binds the log socket again.
+ // One that has not is no crash: asked again after the base
+ // backoff, its stray kept until then.
+ if slices.ContainsFunc(handles, func(p Proc) bool { return !workerEnded(p) }) {
+ wk.retryAt = a.now().Add(sidecarRestartBase)
+ wk.starting = false
+ close(wk.startDone)
+ a.mu.Unlock()
+ log.Printf("activator: %s: worker %s is proven stopped but its last handle has not ended; starting it again shortly", rt.Host, wk.name)
+ return
+ }
+ a.mu.Unlock()
+ }
+ ctx, cancel := context.WithTimeout(a.life(), instancectl.DeadlineControl)
+ defer cancel()
+ a.runWorkerStart(ctx, wb, e, rt, wk, g, web, a.workerGate(e, wk))
+ }()
+}
+
+// dropProvenStraysLocked forgets the strays named name once a proof by
+// name has proven their unit gone (one unit per host and name proves them
+// all). On an awake entry, where a restart may follow, a stray whose
+// handle has not ended yet is kept, due again at once, so no worker of
+// its name starts beside its observer [pf W1.17]. The caller holds a.mu.
+func (a *Service) dropProvenStraysLocked(e *actEntry, name string) {
+ e.strayRootfsWorkers = slices.DeleteFunc(e.strayRootfsWorkers, func(s *rootfsWorker) bool {
+ if s.name != name {
+ return false
+ }
+ if e.state == actAwake && s.unproven != nil && !workerEnded(s.unproven) {
+ s.strayAt = time.Time{}
+ return false
+ }
+ return true
+ })
+}
+
+// workerHandlesLocked is every handle of worker name the entry still
+// holds: the live worker's, and each stray's unproven one. The caller
+// holds a.mu.
+func workerHandlesLocked(e *actEntry, name string) []Proc {
+ var ps []Proc
+ if wk := e.rootfsWorkers[name]; wk != nil && wk.proc != nil {
+ ps = append(ps, wk.proc)
+ }
+ for _, s := range e.strayRootfsWorkers {
+ if s.name == name && s.unproven != nil && !slices.Contains(ps, s.unproven) {
+ ps = append(ps, s.unproven)
+ }
+ }
+ return ps
+}
+
+// sortedWorkerNames is m's names in order.
+func sortedWorkerNames(m map[string]*rootfsWorker) []string {
+ names := make([]string, 0, len(m))
+ for n := range m {
+ names = append(names, n)
+ }
+ slices.Sort(names)
+ return names
+}
+
+// claimWorkerNamesLocked takes the proof claim of each of names not
+// already claimed and returns those it took; busy are the claims of others
+// in flight, to wait on. The caller holds a.mu.
+func claimWorkerNamesLocked(e *actEntry, names []string) (mine []string, busy []chan struct{}) {
+ for _, n := range names {
+ if ch := e.workerProofs[n]; ch != nil {
+ busy = append(busy, ch)
+ continue
+ }
+ if e.workerProofs == nil {
+ e.workerProofs = map[string]chan struct{}{}
+ }
+ e.workerProofs[n] = make(chan struct{})
+ mine = append(mine, n)
+ }
+ return mine, busy
+}
+
+// proveWorkerNames proves each of names gone, in parallel, off a.mu, then
+// records the answers and gives the claims back: a proven name's worker
+// and strays are forgotten; an unproven one's worker becomes a stray, and
+// its strays wait actStopTimeout before the next try. The caller holds
+// each name's claim and not a.mu.
+func (a *Service) proveWorkerNames(e *actEntry, names []string) {
+ if len(names) == 0 {
+ return
+ }
+ a.mu.Lock()
+ rt := e.route
+ procs := make([][]Proc, len(names))
+ for i, n := range names {
+ procs[i] = workerHandlesLocked(e, n)
+ }
+ a.mu.Unlock()
+ errs := make([]error, len(names))
+ wb, ok := a.backend.(RootfsWorkerBackend)
+ var wg sync.WaitGroup
+ for i, n := range names {
+ if !ok {
+ errs[i] = fmt.Errorf("%s: %w", rt.Host, errNoRootfsControl)
+ continue
+ }
+ wg.Add(1)
+ go func(i int, n string) {
+ defer wg.Done()
+ errs[i] = a.proveWorkerGone(wb, rt, n, procs[i]...)
+ }(i, n)
+ }
+ wg.Wait()
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ now := a.now()
+ for i, n := range names {
+ if errs[i] == nil {
+ // An awake entry's worker is the not-yet-restarted
+ // replacement of a stray (proc unset): the supervisor starts it.
+ if wk := e.rootfsWorkers[n]; wk != nil && !wk.starting && e.state != actAwake {
+ delete(e.rootfsWorkers, n)
+ }
+ a.dropProvenStraysLocked(e, n)
+ } else {
+ if wk := e.rootfsWorkers[n]; wk != nil && !wk.starting && e.state != actAwake {
+ delete(e.rootfsWorkers, n)
+ wk.strayAt, wk.unproven = now, wk.proc
+ e.strayRootfsWorkers = append(e.strayRootfsWorkers, wk)
+ }
+ for _, s := range e.strayRootfsWorkers {
+ if s.name == n {
+ s.strayAt = now
+ }
+ }
+ }
+ if ch := e.workerProofs[n]; ch != nil {
+ delete(e.workerProofs, n)
+ close(ch)
+ }
+ }
+}
+
+// workerNamesLocked is every name the entry knows, a worker's or a
+// stray's, sorted. The caller holds a.mu.
+func workerNamesLocked(e *actEntry) []string {
+ names := sortedWorkerNames(e.rootfsWorkers)
+ for _, s := range e.strayRootfsWorkers {
+ if !slices.Contains(names, s.name) {
+ names = append(names, s.name)
+ }
+ }
+ slices.Sort(names)
+ return names
+}
+
+// stopRootfsWorkers is a stop's first step [pf W1.8, W1.9]: once every
+// start in flight has finished, every worker of the entry (and every
+// stray) is stopped and proven gone, in parallel; an unproven one is a
+// stray, which keeps the lease (releasable). The state is stopping by now,
+// so no new start passes its gate or installs. It reports whether none is
+// left. Never call it with a.mu held.
+func (a *Service) stopRootfsWorkers(e *actEntry) bool {
+ for {
+ a.mu.Lock()
+ var wait chan struct{}
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting {
+ wait = wk.startDone
+ break
+ }
+ }
+ a.mu.Unlock()
+ if wait == nil {
+ break
+ }
+ <-wait
+ }
+ a.mu.Lock()
+ mine, busy := claimWorkerNamesLocked(e, workerNamesLocked(e))
+ a.mu.Unlock()
+ a.proveWorkerNames(e, mine)
+ for _, ch := range busy {
+ <-ch
+ }
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return len(e.rootfsWorkers) == 0 && len(e.strayRootfsWorkers) == 0
+}
+
+// stopRootfsWorkersAtLoss stops a resident's workers the moment its lease
+// is lost [pf W1.10], beside the generation kills and without waiting for
+// the entry's stop: each worker not mid-start is stopped and proven gone
+// in parallel, off a.mu; an unproven one is a stray, and the stop path
+// still proves it before the lease goes. A start in flight proves what it
+// started itself (its install is refused). No kill: root refuses one for
+// a worker.
+func (a *Service) stopRootfsWorkersAtLoss(e *actEntry) {
+ a.mu.Lock()
+ var names []string
+ for _, n := range workerNamesLocked(e) {
+ if wk := e.rootfsWorkers[n]; wk == nil || !wk.starting {
+ names = append(names, n)
+ }
+ }
+ mine, _ := claimWorkerNamesLocked(e, names)
+ a.mu.Unlock()
+ a.proveWorkerNames(e, mine)
+}
+
+// rootfsWorkersGone is releasable's worker half (W1.20): true only when no
+// worker of the entry runs, is starting or is a stray. Off a.mu it re-stops
+// and re-proves each stray due for another try (actStopTimeout after the
+// last, or at once during Shutdown) and any worker left on a stopping
+// entry. Never call it with a.mu held.
+func (a *Service) rootfsWorkersGone(e *actEntry) bool {
+ a.mu.Lock()
+ if len(e.rootfsWorkers) == 0 && len(e.strayRootfsWorkers) == 0 {
+ a.mu.Unlock()
+ return true
+ }
+ now := a.now()
+ var due []string
+ for _, n := range workerNamesLocked(e) {
+ if wk := e.rootfsWorkers[n]; wk != nil {
+ if wk.starting {
+ continue
+ }
+ if e.state != actAwake {
+ due = append(due, n)
+ continue
+ }
+ }
+ for _, s := range e.strayRootfsWorkers {
+ if s.name == n && (a.shuttingDown || now.Sub(s.strayAt) >= actStopTimeout) {
+ due = append(due, n)
+ break
+ }
+ }
+ }
+ mine, _ := claimWorkerNamesLocked(e, due)
+ a.mu.Unlock()
+ a.proveWorkerNames(e, mine)
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return len(e.rootfsWorkers) == 0 && len(e.strayRootfsWorkers) == 0
+}
+
+// reproveStraysLocked re-proves, as a goroutine, the strays of an awake
+// entry due for another try (actStopTimeout after the last) whose name is
+// not starting or claimed, so a worker's restart waits only as long as
+// its own stray does. The caller holds a.mu.
+func (a *Service) reproveStraysLocked(e *actEntry, now time.Time) {
+ var due []string
+ for _, s := range e.strayRootfsWorkers {
+ if wk := e.rootfsWorkers[s.name]; wk != nil && wk.starting {
+ continue
+ }
+ if now.Sub(s.strayAt) >= actStopTimeout && !slices.Contains(due, s.name) {
+ due = append(due, s.name)
+ }
+ }
+ mine, _ := claimWorkerNamesLocked(e, due)
+ if len(mine) > 0 {
+ go a.proveWorkerNames(e, mine)
+ }
+}
+
+// rootfsWorkersLiveLocked reports whether a worker of the entry may still
+// run: one installed or starting, or a stray. finishStop's own check, so
+// no stop path releases the lease beside one. The caller holds a.mu.
+func rootfsWorkersLiveLocked(e *actEntry) bool {
+ if len(e.strayRootfsWorkers) > 0 {
+ return true
+ }
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting || (wk.proc != nil && !wk.startFailed) {
+ return true
+ }
+ }
+ return false
+}
+
+// RootfsWorkers reports host's workers [pf W1.25], sorted by name: nil for
+// no entry or a binary host; every known name stopped while the entry is
+// waking or stopping; awake, running while its handle is alive, crash-loop
+// in the loop, restarting otherwise.
+func (a *Service) RootfsWorkers(host string) []WorkerReport {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ if e == nil || !e.route.Rootfs() {
+ return nil
+ }
+ var out []WorkerReport
+ for _, n := range workerNamesLocked(e) {
+ r := WorkerReport{Name: n, State: WorkerStopped}
+ wk := e.rootfsWorkers[n]
+ if wk != nil {
+ r.Restarts = wk.restarts
+ }
+ if e.state == actAwake && wk != nil {
+ switch {
+ case !wk.starting && wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc):
+ r.State = WorkerRunning
+ case wk.crashLoop:
+ r.State = WorkerCrashLoop
+ default:
+ r.State = WorkerRestarting
+ }
+ }
+ out = append(out, r)
+ }
+ return out
+}
+
+// workerStraysAtExitLocked names, for logUnresolvedAtExit, every worker
+// whose stop is not proven, as "host (worker name)". The caller holds a.mu.
+func (a *Service) workerStraysAtExitLocked() []string {
+ var out []string
+ for host, e := range a.entries {
+ for _, s := range e.strayRootfsWorkers {
+ out = append(out, fmt.Sprintf("%s (worker %s)", host, s.name))
+ }
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting || (wk.proc != nil && !wk.startFailed) {
+ out = append(out, fmt.Sprintf("%s (worker %s)", host, wk.name))
+ }
+ }
+ }
+ slices.Sort(out)
+ return slices.Compact(out)
+}
diff --git a/internal/activator/rootfsworkers_test.go b/internal/activator/rootfsworkers_test.go
new file mode 100644
index 000000000..942090974
--- /dev/null
+++ b/internal/activator/rootfsworkers_test.go
@@ -0,0 +1,1600 @@
+package activator
+
+// Rootfs apps Plan 3, Group W, Task W1b: the Service half of a rootfs
+// instance's workers. The Service tests drive the real wake, tick, stop,
+// sweep and Shutdown over fakeWorkerBackend (fakeBackend with the worker
+// verbs, and the generation kill), on a fake clock; the production-wired
+// witnesses drive the real ExecBackend over fakeControl. Not parallel:
+// several capture the standard logger or move package vars.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/instancectl"
+ "github.com/carlosframework/platform/internal/lease"
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/rolloutwords"
+)
+
+// fakeWorkerProc is a worker's handle: alive until it exits, is stopped,
+// or root proves its unit gone. Its exit record is what exit set.
+type fakeWorkerProc struct {
+ mu sync.Mutex
+ name string
+ dead bool
+ rec instancectl.ExitRecord
+ recOK bool
+ stops int
+ // lingers: its observer has not returned, so neither a stop nor a
+ // proof of its unit ends it (a stray's handle, W1.17).
+ lingers bool
+}
+
+func (p *fakeWorkerProc) Stop(context.Context) error {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.stops++
+ if p.lingers {
+ return ErrStillRunning
+ }
+ p.dead = true
+ return nil
+}
+
+// end ends a lingering handle: its observer has returned.
+func (p *fakeWorkerProc) end() {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.lingers, p.dead = false, true
+}
+
+func (p *fakeWorkerProc) Exited() bool {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ return p.dead
+}
+
+func (p *fakeWorkerProc) WorkerExit() (instancectl.ExitRecord, bool) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ if !p.dead {
+ return instancectl.ExitRecord{}, false
+ }
+ return p.rec, p.recOK
+}
+
+// exit ends the worker on its own with a record of code and status (no
+// record when code is "").
+func (p *fakeWorkerProc) exit(code, status string) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.dead = true
+ p.rec = instancectl.ExitRecord{Invocation: "inv", Code: code, Status: status}
+ p.recOK = code != ""
+}
+
+// fakeWorkerBackend is fakeBackend with the generation kill and the worker
+// verbs (RootfsWorkerBackend) and their file removal. Starts that pass
+// their exec gate are logged "start <name> gen<N>", proofs "gone <name>",
+// removals "files <name>", into fakeBackend's order log.
+type fakeWorkerBackend struct {
+ *killBackend
+ wmu sync.Mutex
+ wprocs []*fakeWorkerProc
+ // prepare, when set, runs at the start of LaunchRootfsWorker, before the
+ // exec gate: the worker's preparation.
+ prepare func(name string, g Gen)
+ // block, when set, holds a start that passed its gate (root is running
+ // it) until it closes; entered gets one value per held start.
+ block chan struct{}
+ entered chan string
+ // goneErr, when set, is RootfsWorkerGone's answer for a name (nil is
+ // the proof).
+ goneErr func(name string) error
+ // uncertain, when set, makes the next start that passed its gate
+ // return its handle with an error (a start that may have run), the
+ // handle lingering; it is cleared by that start.
+ uncertain bool
+ // launches counts LaunchRootfsWorker calls per name: each is a
+ // preparation (prepareWorker binds the worker's log socket), gate or no.
+ launches map[string]int
+}
+
+func (b *fakeWorkerBackend) LaunchRootfsWorker(ctx context.Context, _ registry.Route, name string, g Gen, _ Proc) (Proc, error) {
+ b.wmu.Lock()
+ prep := b.prepare
+ if b.launches == nil {
+ b.launches = map[string]int{}
+ }
+ b.launches[name]++
+ b.wmu.Unlock()
+ if prep != nil {
+ prep(name, g)
+ }
+ if err := runExecGate(ctx); err != nil {
+ return nil, err
+ }
+ b.record(fmt.Sprintf("start %s gen%d", name, g.N))
+ b.wmu.Lock()
+ block, entered := b.block, b.entered
+ b.wmu.Unlock()
+ if block != nil {
+ if entered != nil {
+ entered <- name
+ }
+ <-block
+ }
+ p := &fakeWorkerProc{name: name}
+ b.wmu.Lock()
+ b.wprocs = append(b.wprocs, p)
+ uncertain := b.uncertain
+ b.uncertain = false
+ b.wmu.Unlock()
+ if uncertain {
+ p.lingers = true
+ return p, errors.New("instance control: 502 Bad Gateway")
+ }
+ return p, nil
+}
+
+func (b *fakeWorkerBackend) launchCount(name string) int {
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ return b.launches[name]
+}
+
+func (b *fakeWorkerBackend) RootfsWorkerGone(_ context.Context, _ registry.Route, name string) error {
+ b.record("gone " + name)
+ b.wmu.Lock()
+ f := b.goneErr
+ b.wmu.Unlock()
+ if f != nil {
+ if err := f(name); err != nil {
+ return err
+ }
+ }
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ for _, p := range b.wprocs {
+ if p.name == name {
+ p.mu.Lock()
+ if !p.lingers {
+ p.dead = true
+ }
+ p.mu.Unlock()
+ }
+ }
+ return nil
+}
+
+func (b *fakeWorkerBackend) removeRootfsWorkerFiles(_ registry.Route, name string) {
+ b.record("files " + name)
+}
+
+func (b *fakeWorkerBackend) setGone(f func(string) error) {
+ b.wmu.Lock()
+ b.goneErr = f
+ b.wmu.Unlock()
+}
+
+func (b *fakeWorkerBackend) setPrepare(f func(string, Gen)) {
+ b.wmu.Lock()
+ b.prepare = f
+ b.wmu.Unlock()
+}
+
+// workers is every handle of name started so far, in order.
+func (b *fakeWorkerBackend) workers(name string) []*fakeWorkerProc {
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ var out []*fakeWorkerProc
+ for _, p := range b.wprocs {
+ if p.name == name {
+ out = append(out, p)
+ }
+ }
+ return out
+}
+
+func (b *fakeWorkerBackend) lastWorker(t *testing.T, name string) *fakeWorkerProc {
+ t.Helper()
+ ws := b.workers(name)
+ if len(ws) == 0 {
+ t.Fatalf("worker %s never started", name)
+ }
+ return ws[len(ws)-1]
+}
+
+// alive counts the handles still running.
+func (b *fakeWorkerBackend) alive() int {
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ n := 0
+ for _, p := range b.wprocs {
+ if !p.Exited() {
+ n++
+ }
+ }
+ return n
+}
+
+// count is how many order events are ev exactly.
+func (b *fakeWorkerBackend) count(ev string) int {
+ n := 0
+ for _, e := range b.events() {
+ if e == ev {
+ n++
+ }
+ }
+ return n
+}
+
+// stampedSink is a member event sink that stamps each event with the
+// Service's clock.
+type stampedSink struct {
+ mu sync.Mutex
+ clk *fakeClock
+ evs []stampedEvent
+}
+
+type stampedEvent struct {
+ level, msg string
+ at time.Time
+}
+
+func (s *stampedSink) App(string, string, string, string) {}
+func (s *stampedSink) Event(_, _, _, level, msg string) {
+ s.mu.Lock()
+ s.evs = append(s.evs, stampedEvent{level, msg, s.clk.now()})
+ s.mu.Unlock()
+}
+
+// with is every event whose message starts with prefix.
+func (s *stampedSink) with(prefix string) []stampedEvent {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ var out []stampedEvent
+ for _, e := range s.evs {
+ if strings.HasPrefix(e.msg, prefix) {
+ out = append(out, e)
+ }
+ }
+ return out
+}
+
+// workerRig is a Service over fakeWorkerBackend with generations on, its
+// rootfs admission open, a fake clock, a generations file, and a build
+// that declares web and the rig's workers.
+type workerRig struct {
+ a *Service
+ b *fakeWorkerBackend
+ clk *fakeClock
+ sink *stampedSink
+ rt registry.Route
+ host string
+}
+
+func newWorkerRig(t *testing.T, rt registry.Route, workers ...string) *workerRig {
+ t.Helper()
+ kb := &killBackend{fakeBackend: &fakeBackend{}}
+ wb := &fakeWorkerBackend{killBackend: kb}
+ clk := &fakeClock{t: time.Unix(1_700_000_000, 0)}
+ reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, wb, reg)
+ a.now = clk.now
+ a.gens = true
+ armRootfsForTest(a)
+ startsFromStagedIdentity(kb.fakeBackend)
+ a.residentJitter = func() float64 { return 0 }
+ sink := &stampedSink{clk: clk}
+ a.Logs = sink
+ a.GenerationsFile = filepath.Join(t.TempDir(), "generations.json")
+ procs := map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}
+ for _, w := range workers {
+ procs[w] = release.Process{Command: []string{"/app/" + w}}
+ }
+ kb.processes = func(registry.Route, release.StagedIdentity) (map[string]release.Process, error) { return procs, nil }
+ kb.repWrap = func(r *fakeRep) Rep {
+ kb.record("replicate")
+ r.setOnClose(func() { kb.record("close") })
+ return r
+ }
+ t.Cleanup(func() {
+ wb.setGone(nil)
+ wb.wmu.Lock()
+ if wb.block != nil {
+ select {
+ case <-wb.block:
+ default:
+ close(wb.block)
+ }
+ }
+ wb.wmu.Unlock()
+ clk.advance(actStopTimeout + time.Second)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ a.Shutdown(ctx)
+ })
+ return &workerRig{a: a, b: wb, clk: clk, sink: sink, rt: rt, host: rt.Host}
+}
+
+// wake wakes the rig's host by a request.
+func (r *workerRig) wake(t *testing.T) *actEntry {
+ t.Helper()
+ arrangeAwake(t, r.a, r.rt)
+ e := r.a.awakeEntry(r.host)
+ if e == nil {
+ t.Fatalf("%s is not awake after its wake", r.host)
+ }
+ return e
+}
+
+// tick runs one resident tick and waits until no worker start or proof
+// it began is in flight.
+func (r *workerRig) tick(t *testing.T) {
+ t.Helper()
+ r.a.rootfsTick()
+ waitFor(t, "the tick's worker starts and proofs", r.settled)
+}
+
+func (r *workerRig) settled() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ e := r.a.entries[r.host]
+ if e == nil {
+ return true
+ }
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting {
+ return false
+ }
+ }
+ return len(e.workerProofs) == 0
+}
+
+func (r *workerRig) strays() []string {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ e := r.a.entries[r.host]
+ if e == nil {
+ return nil
+ }
+ var out []string
+ for _, s := range e.strayRootfsWorkers {
+ out = append(out, s.name)
+ }
+ return out
+}
+
+func (r *workerRig) pendingStop() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ e := r.a.entries[r.host]
+ return e != nil && e.pendingStop
+}
+
+func (r *workerRig) gen() Gen {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ if e := r.a.entries[r.host]; e != nil {
+ return e.gen
+ }
+ return Gen{}
+}
+
+// index is the position of ev in the order log after from, or -1.
+func index(events []string, ev string, from int) int {
+ for i := from; i < len(events); i++ {
+ if events[i] == ev {
+ return i
+ }
+ }
+ return -1
+}
+
+func workerHost() registry.Route { return rootfsGateRoute("shop.example.com") }
+
+// lastWithPrefix is the position of the last event starting with prefix,
+// or -1.
+func lastWithPrefix(events []string, prefix string) int {
+ last := -1
+ for i, e := range events {
+ if strings.HasPrefix(e, prefix) {
+ last = i
+ }
+ }
+ return last
+}
+
+// openReleaseRecord plants an open release record for host, as R's
+// runRelease holds one while a release runs or is not proven stopped.
+func openReleaseRecord(a *Service, host string) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.releaseOps == nil {
+ a.releaseOps = map[string]*releaseOp{}
+ }
+ a.releaseOps[host] = &releaseOp{host: host}
+}
+
+// Spec §5.4: workers start once web is started, healthy and replicating,
+// in name order, each with RFS-3-C08; a failed web start starts none.
+func TestRootfsWorkersStartAfterWebHealthy(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "mailer", "jobs")
+ r.wake(t)
+ g := r.gen()
+ ev := r.b.events()
+ web, rep := index(ev, "start v1", 0), index(ev, "replicate", 0)
+ jobs, mailer := index(ev, fmt.Sprintf("start jobs gen%d", g.N), 0), index(ev, fmt.Sprintf("start mailer gen%d", g.N), 0)
+ if web < 0 || rep < web || jobs < rep || mailer < jobs {
+ t.Fatalf("order %v: want web's start, its replica, then jobs and mailer of generation %d", ev, g.N)
+ }
+ for _, name := range []string{"jobs", "mailer"} {
+ if n := len(r.sink.with(fmt.Sprintf(rolloutwords.EventWorkerStarted, name))); n != 1 {
+ t.Errorf("RFS-3-C08 for %s emitted %d times, want once", name, n)
+ }
+ }
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerRunning, 0}, {"mailer", WorkerRunning, 0}}) {
+ t.Errorf("report %+v, want both running", got)
+ }
+
+ // A web that fails to start starts no worker.
+ f := newWorkerRig(t, workerHost(), "jobs")
+ f.b.mu.Lock()
+ f.b.startErr = errors.New("the image would not start")
+ f.b.mu.Unlock()
+ if _, err := f.a.beginRequest(context.Background(), f.rt); err == nil {
+ t.Fatal("the wake of a web that failed to start succeeded")
+ }
+ for _, e := range f.b.events() {
+ if strings.HasPrefix(e, "start jobs") {
+ t.Fatalf("a worker started beside a failed web: %v", f.b.events())
+ }
+ }
+ if n := len(f.sink.with("worker ")); n != 0 {
+ t.Errorf("%d worker events for a failed web", n)
+ }
+}
+
+// crashLoop makes jobs exit ten times with code and status and checks the
+// restarts' delays, web untouched, and the member's events.
+func crashLoop(t *testing.T, code, status string, want int) {
+ t.Helper()
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ web := r.b.lastProc()
+ rep := r.b.lastRep()
+ delays := []time.Duration{2, 4, 8, 16, 32, 60, 60, 60, 60, 60}
+ for i, d := range delays {
+ d *= time.Second
+ r.b.lastWorker(t, "jobs").exit(code, status)
+ r.tick(t) // the exit is noted
+ noted := r.clk.now()
+ n := len(r.b.workers("jobs"))
+ for len(r.b.workers("jobs")) == n {
+ if r.clk.now().Sub(noted) > 2*time.Minute {
+ t.Fatalf("exit %d: no restart within 2m", i+1)
+ }
+ r.clk.advance(time.Second)
+ r.tick(t)
+ }
+ if got := r.clk.now().Sub(noted); got != d {
+ t.Errorf("exit %d: restarted after %s, want %s", i+1, got, d)
+ }
+ if i == 5 {
+ if got := r.a.RootfsWorkers(r.host); len(got) != 1 || got[0].State != WorkerRunning || got[0].Restarts != 6 {
+ t.Errorf("report after the sixth restart %+v", got)
+ }
+ }
+ }
+ if !entryAwake(r.a, r.host) || rep.isClosed() || web.isStopped() || web.Exited() {
+ t.Fatalf("a worker's exits touched web: awake %v, replica closed %v, web stopped %v", entryAwake(r.a, r.host), rep.isClosed(), web.isStopped())
+ }
+ if n := len(r.sink.with(fmt.Sprintf(rolloutwords.EventWorkerCrashLoop, "jobs"))); n != 1 {
+ t.Errorf("RFS-3-C10 emitted %d times, want once", n)
+ }
+ exited := r.sink.with("worker jobs exited")
+ if len(exited) != 9 {
+ t.Fatalf("RFS-3-C09 emitted %d times, want 9 (every exit but the one that entered the loop): %+v", len(exited), exited)
+ }
+ for i, wait := range []string{"2s", "4s", "8s", "16s", "32s", "1m0s", "1m0s", "1m0s", "1m0s"} {
+ if w := fmt.Sprintf(rolloutwords.EventWorkerExited, "jobs", want, wait); exited[i].msg != w {
+ t.Errorf("C09 %d = %q, want %q", i+1, exited[i].msg, w)
+ }
+ }
+ loop := r.sink.with(fmt.Sprintf(rolloutwords.EventWorkerCrashLoop, "jobs"))[0].at
+ last := loop
+ for _, e := range exited {
+ if e.at.After(loop) {
+ if e.at.Sub(last) < time.Minute {
+ t.Errorf("C09 at %s, %s after the previous loop event: more than once a minute", e.at, e.at.Sub(last))
+ }
+ last = e.at
+ }
+ }
+}
+
+// Review Focus 3: a worker's crash never stops web; the backoff doubles
+// from 2 s to the 60 s cap.
+func TestRootfsWorkerCrashNeverStopsWeb(t *testing.T) { crashLoop(t, "exited", "3", 3) }
+
+// Review Focus 3: a clean exit is a crash too: restarted, never parked.
+func TestCleanExitingWorkerIsRestartedNotParked(t *testing.T) { crashLoop(t, "exited", "0", 0) }
+
+// [pf W1.16] C09's status: an exit code, 128 plus a known signal's number;
+// no record or an unknown signal tells none.
+func TestRootfsWorkerExitStatus(t *testing.T) {
+ for _, c := range []struct {
+ code, status string
+ want int
+ ok bool
+ }{
+ {"exited", "0", 0, true}, {"exited", "3", 3, true}, {"killed", "KILL", 137, true},
+ {"dumped", "SEGV", 139, true}, {"killed", "TERM", 143, true}, {"killed", "SIGINT", 130, true},
+ {"killed", "WINCH", 0, false}, {"exited", "three", 0, false}, {"", "", 0, false},
+ } {
+ p := &fakeWorkerProc{}
+ p.exit(c.code, c.status)
+ got, ok := workerExitStatus(p)
+ if ok != c.ok || (ok && got != c.want) {
+ t.Errorf("%s/%s: %d, %v; want %d, %v", c.code, c.status, got, ok, c.want, c.ok)
+ }
+ }
+ if _, ok := workerExitStatus(&fakeProc{dead: true}); ok {
+ t.Error("a handle with no exit record told a status")
+ }
+}
+
+// [pf W1.8, W1.9] A stop stops and proves the workers first, before web's
+// stop and the lease's release; an unproven worker keeps the stop pending,
+// its replica open and its lease held, until a sweep proves it.
+func TestRootfsWorkersStopFirstAndProven(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.a.Bounce(r.host)
+ waitFor(t, "the stop", func() bool { return !r.a.hasEntry(r.host) })
+ ev := r.b.events()
+ gone, web, closed := index(ev, "gone jobs", 0), index(ev, "stop:instance", 0), index(ev, "close", 0)
+ if gone < 0 || web < gone || closed < web {
+ t.Fatalf("order %v: want the worker proven gone, then web stopped, then the lease released", ev)
+ }
+ if index(ev, "files jobs", gone) < 0 {
+ t.Errorf("the proven worker's files were not removed: %v", ev)
+ }
+
+ f := newWorkerRig(t, workerHost(), "jobs")
+ f.wake(t)
+ rep := f.b.lastRep()
+ var fails atomic.Int32
+ fails.Store(1)
+ f.b.setGone(func(string) error {
+ if fails.Add(-1) >= 0 {
+ return instancectl.ErrGenUnproven
+ }
+ return nil
+ })
+ f.a.Bounce(f.host)
+ waitFor(t, "the stop to be kept pending", f.pendingStop)
+ for i := 0; i < 3; i++ {
+ f.a.sweepOnce()
+ }
+ time.Sleep(50 * time.Millisecond)
+ if !f.pendingStop() || rep.isClosed() || f.b.releaseCount() != 0 {
+ t.Fatalf("the stop finished beside an unproven worker: pending %v, replica closed %v, releases %d", f.pendingStop(), rep.isClosed(), f.b.releaseCount())
+ }
+ if got := f.b.count("gone jobs"); got != 1 {
+ t.Fatalf("%d proofs inside actStopTimeout, want 1", got)
+ }
+ f.clk.advance(actStopTimeout)
+ f.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !f.a.hasEntry(f.host) })
+ ev = f.b.events()
+ if second, closed := index(ev, "gone jobs", index(ev, "gone jobs", 0)+1), index(ev, "close", 0); second < 0 || closed < second {
+ t.Fatalf("order %v: the lease went before the worker's second proof", ev)
+ }
+ if !rep.isClosed() {
+ t.Fatal("the replica was not closed after the proof")
+ }
+}
+
+// [pf 2.4] The Service half: a worker stop root answers unproven, or a
+// 502, leaves a stray that keeps the stop; the next proof forgets it.
+func TestRootfsWorkerStopAnswersInTheService(t *testing.T) {
+ for name, first := range map[string]error{
+ "unproven then proven": instancectl.ErrGenUnproven,
+ "a 502": errors.New("instance control: 502 Bad Gateway"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ var answered atomic.Bool
+ r.b.setGone(func(string) error {
+ if answered.CompareAndSwap(false, true) {
+ return first
+ }
+ return nil
+ })
+ r.a.Bounce(r.host)
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ if got := r.strays(); !slices.Equal(got, []string{"jobs"}) {
+ t.Fatalf("strays %v after %v, want jobs", got, first)
+ }
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerStopped, 0}}) {
+ t.Errorf("report of a stopping entry %+v", got)
+ }
+ if r.b.count("files jobs") != 0 {
+ t.Fatal("a stray's files were removed before its proof (INV-2)")
+ }
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
+ if r.b.count("files jobs") != 1 {
+ t.Errorf("the proven stray's files: %v", r.b.events())
+ }
+ })
+ }
+}
+
+// INV-2 through the real backend: an unproven worker keeps its launch
+// file, its exit records and its stray; only the proof removes them.
+func TestRootfsWorkerUnprovenKeepsItsFiles(t *testing.T) {
+ lb, ctl := newRootfsLaunch(t, &fakeSwapBackend{fakeBackend: &fakeBackend{}})
+ next := stageDeclared(t, lb.eb, "v2", map[string]release.Process{
+ release.ProcessWeb: {Command: []string{"/app/serve"}}, "jobs": {Command: []string{"/app/jobs"}},
+ }, nil)
+ ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
+ a, rt, evs := rootfsPlanned(t, lb, WakePlan{Boot: next, Mode: ModeOverlap}, registry.RuntimeRootfsV1)
+ rt.GoodVersion, rt.GoodDigest = next.Version, next.Digest
+ clk := &fakeClock{t: time.Now()}
+ a.now = clk.now
+ done, err := a.beginRequest(context.Background(), rt)
+ if err != nil {
+ t.Fatalf("the wake: %v; calls:\n%s", err, ctl.joined())
+ }
+ done()
+ evs.wait(t, GenHealthy)
+ ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+lb.rt.Host+" jobs ")
+ p := lb.eb.pathsFor(lb.rt)
+ launch := filepath.Join(p.dataDir, instancectl.WorkerLaunchFileName("jobs"))
+ record := filepath.Join(p.runDir, instancectl.WorkerExitRecordName("jobs", "earlier"))
+ if err := os.WriteFile(record, []byte(`{"code":"exited","status":"1"}`), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := os.Stat(launch); err != nil {
+ t.Fatalf("the worker's launch file: %v", err)
+ }
+ ctl.umu.Lock()
+ ctl.workerStopErr = instancectl.ErrGenUnproven
+ ctl.umu.Unlock()
+ a.Bounce(rt.Host)
+ waitFor(t, "the stop to be kept pending", func() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[rt.Host]
+ return e != nil && e.pendingStop && len(e.strayRootfsWorkers) == 1
+ })
+ for _, f := range []string{launch, record} {
+ if _, err := os.Stat(f); err != nil {
+ t.Errorf("%s went with the worker unproven: %v", filepath.Base(f), err)
+ }
+ }
+ ctl.umu.Lock()
+ ctl.workerStopErr = nil
+ ctl.umu.Unlock()
+ clk.advance(actStopTimeout)
+ a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(rt.Host) })
+ for _, f := range []string{launch, record} {
+ if _, err := os.Stat(f); !os.IsNotExist(err) {
+ t.Errorf("%s outlived the proof: %v", filepath.Base(f), err)
+ }
+ }
+}
+
+// [race] A restart held inside root's start while Shutdown runs: the
+// worker it started is stopped and proven before the lease goes, and no
+// worker survives.
+func TestRootfsWorkerStartRacesStop(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
+ block, entered := make(chan struct{}), make(chan string, 1)
+ r.b.wmu.Lock()
+ r.b.block, r.b.entered = block, entered
+ r.b.wmu.Unlock()
+ r.a.rootfsTick()
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the restart never reached root")
+ }
+ shut := make(chan struct{})
+ go func() {
+ defer close(shut)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ r.a.Shutdown(ctx)
+ }()
+ waitFor(t, "Shutdown to begin the stop", func() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ e := r.a.entries[r.host]
+ return e != nil && e.state == actStopping
+ })
+ time.Sleep(50 * time.Millisecond)
+ if index(r.b.events(), "close", 0) >= 0 {
+ t.Fatal("the lease went with a worker start in flight")
+ }
+ // The stop waits for the start in flight (its startDone) before it
+ // proves the worker: nothing is proven while root is still starting it.
+ if ev := r.b.events(); index(ev, "gone jobs", lastWithPrefix(ev, "start jobs")+1) >= 0 {
+ t.Fatalf("order %v: the stop proved the worker while its start was still in flight", ev)
+ }
+ r.b.wmu.Lock()
+ close(block)
+ r.b.block = nil
+ r.b.wmu.Unlock()
+ select {
+ case <-shut:
+ case <-time.After(10 * time.Second):
+ t.Fatal("Shutdown did not return")
+ }
+ ev := r.b.events()
+ second := -1
+ for i, e := range ev {
+ if strings.HasPrefix(e, "start jobs") {
+ second = i
+ }
+ }
+ gone, closed := index(ev, "gone jobs", second), index(ev, "close", 0)
+ if second < 0 || gone < 0 || closed < gone {
+ t.Fatalf("order %v: the raced worker was not proven gone before the lease went", ev)
+ }
+ if n := r.b.alive(); n != 0 {
+ t.Fatalf("%d workers survived Shutdown", n)
+ }
+}
+
+// [pf W1.11] A restart whose install is refused (the lease lost while
+// root started it, the entry still awake) stops and proves what it started
+// before its startDone closes; nothing else proves it, and no worker runs.
+func TestRootfsWorkerStartThatLostItsLeaseIsProvenGone(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
+ block, entered := make(chan struct{}), make(chan string, 1)
+ r.b.wmu.Lock()
+ r.b.block, r.b.entered = block, entered
+ r.b.wmu.Unlock()
+ r.a.rootfsTick()
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the restart never reached root")
+ }
+ r.b.lastRep().setErr(lease.ErrLost)
+ r.b.wmu.Lock()
+ close(block)
+ r.b.block = nil
+ r.b.wmu.Unlock()
+ waitFor(t, "the restart to finish", r.settled)
+ ev := r.b.events()
+ second := -1
+ for i, e := range ev {
+ if strings.HasPrefix(e, "start jobs") {
+ second = i
+ }
+ }
+ if index(ev, "gone jobs", second) < 0 {
+ t.Fatalf("order %v: the worker whose install was refused was not proven gone", ev)
+ }
+ if n := r.b.alive(); n != 0 {
+ t.Fatalf("%d workers run after a refused install", n)
+ }
+ if !r.a.hasEntry(r.host) {
+ t.Fatal("the entry went: this case needs no stop to prove the worker")
+ }
+}
+
+// [pf W1.20] finishStop's own check, beside releasable's: a stray keeps
+// replication and the lease, and the stop pending, whatever path reached
+// finishStop.
+func TestRootfsWorkerStrayKeepsFinishStopPending(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ e := r.wake(t)
+ rep := r.b.lastRep()
+ r.a.mu.Lock()
+ e.strayRootfsWorkers = append(e.strayRootfsWorkers, &rootfsWorker{name: "jobs", gen: e.gen.N, build: fakeIdentity("v1")})
+ e.state = actStopping
+ e.stopped = make(chan struct{})
+ r.a.mu.Unlock()
+ r.a.finishStop(e, &stopObservation{})
+ if !r.a.hasEntry(r.host) || !r.pendingStop() || rep.isClosed() {
+ t.Fatalf("finishStop beside a stray: entry %v, pending %v, replica closed %v", r.a.hasEntry(r.host), r.pendingStop(), rep.isClosed())
+ }
+}
+
+// [pf W1.21] A worker still unproven when Shutdown's budget runs out is
+// named in the exit report, host and worker.
+func TestRootfsWorkerStrayNamedAtShutdown(t *testing.T) {
+ logs := captureLogLines(t)
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.setGone(func(string) error { return instancectl.ErrGenUnproven })
+ ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
+ defer cancel()
+ r.a.Shutdown(ctx)
+ if n := logs.matching("shutdown: out of time", "worker(s) not proven stopped", r.host+" (worker jobs)"); n != 1 {
+ t.Fatalf("%d exit report lines naming the worker, want 1; logs:\n%s", n, logs)
+ }
+}
+
+// residentWorkerRig is a workerRig over an awake resident whose replica
+// carries the lease's signal (its lease watch runs), with jobs and mailer.
+func residentWorkerRig(t *testing.T) (*workerRig, func() *ownedRep) {
+ t.Helper()
+ shrinkResidentPoll(t, time.Hour) // the test ticks by hand
+ rt := residentRoute("shop.example.com")
+ r := newWorkerRig(t, rt, "jobs", "mailer")
+ r.a.residentLister = &fakeResidents{routes: []registry.Route{rt}}
+ var mu sync.Mutex
+ var rep *ownedRep
+ kb := r.b.killBackend
+ kb.mu.Lock()
+ kb.repWrap = func(fr *fakeRep) Rep {
+ fr.setOnClose(func() { kb.record("close") })
+ mu.Lock()
+ defer mu.Unlock()
+ rep = newOwnedRep(fr, time.Now().Add(time.Hour))
+ return rep
+ }
+ kb.mu.Unlock()
+ t.Cleanup(func() {
+ mu.Lock()
+ defer mu.Unlock()
+ if rep != nil {
+ rep.timer.Stop()
+ }
+ })
+ startResident(t, r.a, r.host)
+ if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 2 {
+ t.Fatalf("%d workers started, want 2", n)
+ }
+ return r, func() *ownedRep {
+ mu.Lock()
+ defer mu.Unlock()
+ return rep
+ }
+}
+
+// [pf W1.10] At a resident's lease loss every worker is stopped at once,
+// beside the generation kill and before the lease goes; none restarts; an
+// unproven one keeps the stop pending until it is proven. And when the
+// entry's own stop already ran and left a worker unproven, the loss
+// re-proves it at once, without waiting for the sweep's next try.
+func TestRootfsWorkersStopAtLeaseLoss(t *testing.T) {
+ t.Run("awake at the loss", func(t *testing.T) {
+ r, rep := residentWorkerRig(t)
+ var stuck atomic.Bool
+ stuck.Store(true)
+ r.b.setGone(func(name string) error {
+ if name == "mailer" && stuck.Load() {
+ return instancectl.ErrGenUnproven
+ }
+ return nil
+ })
+ rep().lose(lease.ErrLost)
+ waitFor(t, "both workers' proofs and the kill", func() bool {
+ ev := r.b.events()
+ return index(ev, "gone jobs", 0) >= 0 && index(ev, "gone mailer", 0) >= 0 && indexWithPrefix(ev, "kill:") >= 0
+ })
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ for i := 0; i < 3; i++ {
+ r.a.rootfsTick()
+ r.a.sweepOnce()
+ }
+ time.Sleep(50 * time.Millisecond)
+ if index(r.b.events(), "close", 0) >= 0 {
+ t.Fatalf("the lease went beside an unproven worker: %v", r.b.events())
+ }
+ if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 2 {
+ t.Fatalf("%d worker starts after the loss, want none", n-2)
+ }
+ if got := r.strays(); !slices.Equal(got, []string{"mailer"}) {
+ t.Fatalf("strays %v, want mailer", got)
+ }
+ stuck.Store(false)
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
+ ev := r.b.events()
+ closed := index(ev, "close", 0)
+ for _, w := range []string{"gone jobs", "gone mailer"} {
+ if i := index(ev, w, 0); i < 0 || i > closed {
+ t.Errorf("order %v: %s not before the lease's release", ev, w)
+ }
+ }
+ })
+ t.Run("its stop already pending", func(t *testing.T) {
+ r, rep := residentWorkerRig(t)
+ var stuck atomic.Bool
+ stuck.Store(true)
+ r.b.setGone(func(name string) error {
+ if name == "mailer" && stuck.Load() {
+ return instancectl.ErrGenUnproven
+ }
+ return nil
+ })
+ // A stop begun before the loss (a drain that no longer fits, a
+ // bounce) leaves mailer unproven: the sweep would try it again only
+ // after actStopTimeout.
+ r.a.Bounce(r.host)
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ if got := r.strays(); !slices.Equal(got, []string{"mailer"}) {
+ t.Fatalf("strays %v, want mailer", got)
+ }
+ if n := r.b.count("gone mailer"); n != 1 {
+ t.Fatalf("%d proofs of mailer before the loss, want 1", n)
+ }
+ stuck.Store(false)
+ rep().lose(lease.ErrLost)
+ waitFor(t, "the loss to prove mailer at once", func() bool { return r.b.count("gone mailer") == 2 })
+ waitFor(t, "the stray to go", func() bool { return len(r.strays()) == 0 })
+ r.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
+ ev := r.b.events()
+ if second, closed := index(ev, "gone mailer", index(ev, "gone mailer", 0)+1), index(ev, "close", 0); second < 0 || closed < second {
+ t.Fatalf("order %v: the lease went before the stray's proof", ev)
+ }
+ })
+}
+
+// [pf W1.15] Five workers is more than the ship door allows: none starts,
+// web serves, one line says why.
+func TestTooManyWorkersStartNone(t *testing.T) {
+ logs := captureLogLines(t)
+ r := newWorkerRig(t, workerHost(), "a1", "a2", "a3", "a4", "a5")
+ r.wake(t)
+ for _, e := range r.b.events() {
+ if strings.HasPrefix(e, "start a") {
+ t.Fatalf("a worker started from an invalid declaration: %v", r.b.events())
+ }
+ }
+ if n := logs.matching(r.host, "declared processes are not valid", "at most 4 worker processes"); n != 1 {
+ t.Errorf("%d refusal lines, want 1; logs:\n%s", n, logs)
+ }
+ if got := r.a.RootfsWorkers(r.host); got != nil {
+ t.Errorf("report %+v, want none", got)
+ }
+ if !entryAwake(r.a, r.host) {
+ t.Fatal("web does not serve beside the refused declaration")
+ }
+ // release.MaxWorkers of them is the ship door's limit, and all start.
+ four := newWorkerRig(t, workerHost(), "a1", "a2", "a3", "a4")
+ four.wake(t)
+ if got := four.a.RootfsWorkers(four.host); len(got) != release.MaxWorkers {
+ t.Errorf("four workers: report %+v", got)
+ }
+}
+
+// A declaration that cannot be read at the worker start (a digest that
+// does not match) starts no worker; web serves; one line.
+func TestWorkerProcessesRefusalStartsNone(t *testing.T) {
+ logs := captureLogLines(t)
+ r := newWorkerRig(t, workerHost(), "jobs")
+ kb := r.b.killBackend.fakeBackend
+ kb.processes = func(registry.Route, release.StagedIdentity) (map[string]release.Process, error) {
+ kb.mu.Lock()
+ started := kb.starts > 0
+ kb.mu.Unlock()
+ if started {
+ return nil, refuseRootfs(errors.New("build v1: the staged manifest names digest ab, the image is cd"))
+ }
+ return map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}, "jobs": {Command: []string{"/app/jobs"}}}, nil
+ }
+ r.wake(t)
+ if n := len(r.b.workers("jobs")); n != 0 {
+ t.Fatalf("%d workers started over a refused read", n)
+ }
+ if n := logs.matching(r.host, "declared processes cannot be read", "names digest"); n != 1 {
+ t.Errorf("%d refusal lines, want 1; logs:\n%s", n, logs)
+ }
+}
+
+// W1.19: the generations file on disk names a worker's build before root
+// is asked, while it runs, after its generation stops being the entry's,
+// and while it is a stray; once proven gone it is no longer pinned.
+func TestWorkerImagePinnedWhileItRuns(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ // The pin is checked inside the worker's preparation, after
+ // publishBeforeExec and before root is asked; the wake's own entries
+ // (its plan, its generation) are cleared there, so only the worker's
+ // registration can name v1.
+ var beforeRoot atomic.Int32
+ r.b.setPrepare(func(string, Gen) {
+ r.a.mu.Lock()
+ e := r.a.entries[r.host]
+ saved := e.gen
+ e.plan = WakePlan{}
+ e.gen = Gen{}
+ r.a.mu.Unlock()
+ if err := r.a.persistGenerations(); err != nil {
+ t.Error(err)
+ }
+ if pinnedSettled(t, r.a, r.host, "v1") {
+ beforeRoot.Add(1)
+ }
+ r.a.mu.Lock()
+ e.gen = saved
+ r.a.mu.Unlock()
+ })
+ e := r.wake(t)
+ r.b.setPrepare(nil)
+ if beforeRoot.Load() != 1 {
+ t.Fatal("the worker's build was not in the generations file before root was asked")
+ }
+ if !pinnedSettled(t, r.a, r.host, "v1") {
+ t.Fatal("the running worker's build is not pinned")
+ }
+ // A swap's shape: v2 becomes current and v1 retires as an operation
+ // member, then dropMember proves it gone and drops it. Only the worker
+ // still runs v1.
+ v2 := fakeIdentity("v2")
+ r.a.mu.Lock()
+ e.plan = WakePlan{}
+ old, oldProc := e.gen, e.proc
+ m := &genMember{gen: old, role: roleRetiring, proc: oldProc, done: make(chan struct{})}
+ r.a.addMemberLocked(e, m)
+ r.a.installProcLocked(e, nil, &fakeProc{}, Gen{N: old.N + 1, Build: v2.Version, StagedPath: v2.StagedPath, Digest: v2.Digest})
+ r.a.mu.Unlock()
+ if !r.a.dropMember(e, m) {
+ t.Fatal("the retiring generation was not dropped")
+ }
+ if err := r.a.persistGenerations(); err != nil {
+ t.Fatal(err)
+ }
+ if !pinnedSettled(t, r.a, r.host, "v2") {
+ t.Fatal("the current generation is not pinned")
+ }
+ if !pinnedSettled(t, r.a, r.host, "v1") {
+ t.Fatal("the worker's build was dropped with its generation")
+ }
+ r.b.setGone(func(string) error { return instancectl.ErrGenUnproven })
+ r.a.Bounce(r.host)
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ if got := r.strays(); !slices.Equal(got, []string{"jobs"}) {
+ t.Fatalf("strays %v, want jobs", got)
+ }
+ if err := r.a.persistGenerations(); err != nil {
+ t.Fatal(err)
+ }
+ if !pinnedSettled(t, r.a, r.host, "v1") {
+ t.Fatal("a stray's build is not pinned")
+ }
+ r.b.setGone(nil)
+ r.clk.advance(actStopTimeout)
+ r.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
+ waitFor(t, "the pin to go", func() bool { return !pinnedSettled(t, r.a, r.host, "v1") })
+}
+
+// [pf W1.14, W0.1] A restart's gate is asked at the last moment, after its
+// preparation: a lost lease, a fence, an open release record or a moved
+// generation each starts nothing, and no worker runs.
+func TestWorkerGateRefusesAtTheLastMoment(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ hit func(r *workerRig, e *actEntry) (undo func())
+ }{
+ {"the lease lost", func(r *workerRig, _ *actEntry) func() {
+ r.b.lastRep().setErr(lease.ErrLost)
+ return func() {}
+ }},
+ {"a fence", func(r *workerRig, _ *actEntry) func() {
+ raiseFence(r.a, r.host)
+ return func() {
+ r.a.mu.Lock()
+ r.a.fences[r.host]--
+ r.a.mu.Unlock()
+ }
+ }},
+ {"a release record", func(r *workerRig, _ *actEntry) func() {
+ openReleaseRecord(r.a, r.host)
+ return func() {
+ r.a.mu.Lock()
+ delete(r.a.releaseOps, r.host)
+ r.a.mu.Unlock()
+ }
+ }},
+ {"the generation moved", func(r *workerRig, e *actEntry) func() {
+ r.a.mu.Lock()
+ g := e.gen
+ g.N++
+ r.a.installProcLocked(e, nil, e.proc, g)
+ r.a.mu.Unlock()
+ return func() {}
+ }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ e := r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
+ var undo func()
+ r.b.setPrepare(func(string, Gen) { undo = c.hit(r, e) })
+ r.tick(t)
+ if undo == nil {
+ t.Fatal("the restart never reached its preparation")
+ }
+ undo()
+ if n := len(r.b.workers("jobs")); n != 1 {
+ t.Fatalf("root was asked for %d more starts", n-1)
+ }
+ if r.b.alive() != 0 {
+ t.Fatal("a worker runs")
+ }
+ if got := r.a.RootfsWorkers(r.host); len(got) == 1 && got[0].State == WorkerRunning {
+ t.Fatalf("report %+v", got)
+ }
+ })
+ }
+}
+
+// The doWake start's gate through the real wake(): (a) it starts inside
+// doWake, the entry still waking, root asked once with the wake's
+// generation, and the worker is supervised under that generation once
+// installed; (b) a lease lost during its preparation starts nothing, and
+// the wake ends as one with a lost lease does.
+func TestColdWakeWorkerGate(t *testing.T) {
+ t.Run("the wake's generation", func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ var state actState
+ var asked Gen
+ r.b.setPrepare(func(_ string, g Gen) {
+ r.a.mu.Lock()
+ state = r.a.entries[r.host].state
+ r.a.mu.Unlock()
+ asked = g
+ })
+ r.wake(t)
+ r.b.setPrepare(nil)
+ g := r.gen()
+ if state != actWaking || asked.N != g.N || asked.N == 0 {
+ t.Fatalf("the worker was prepared in state %v with generation %d; want waking, the wake's %d", state, asked.N, g.N)
+ }
+ if n := r.b.count(fmt.Sprintf("start jobs gen%d", g.N)); n != 1 {
+ t.Fatalf("root was asked %d times, want once", n)
+ }
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
+ r.tick(t)
+ if n := r.b.count(fmt.Sprintf("start jobs gen%d", g.N)); n != 2 {
+ t.Fatalf("the restart under the installed generation: %d starts, want 2; %v", n, r.b.events())
+ }
+ })
+ t.Run("the lease lost in its preparation", func(t *testing.T) {
+ logs := captureLogLines(t)
+ r := newWorkerRig(t, workerHost(), "jobs")
+ var lost atomic.Bool
+ var lostGen atomic.Uint64
+ r.b.setPrepare(func(_ string, g Gen) {
+ if lost.CompareAndSwap(false, true) {
+ lostGen.Store(g.N)
+ r.b.lastRep().setErr(lease.ErrLost)
+ }
+ })
+ r.wake(t)
+ r.b.setPrepare(nil)
+ if !lost.Load() || lostGen.Load() == 0 {
+ t.Fatal("the worker's preparation never ran inside the wake")
+ }
+ if n := r.b.count(fmt.Sprintf("start jobs gen%d", lostGen.Load())); n != 0 {
+ t.Fatalf("root was asked %d times for the worker of the wake whose lease was lost", n)
+ }
+ // Today's outcome for a lost lease: the request finds the entry's
+ // replica lost, stands it down (StopLeaseLost) and wakes again; the
+ // worker of that new wake starts, and it is the only one running.
+ if n := logs.matching(r.host, "LEASE LOST", "standing down"); n != 1 {
+ t.Fatalf("%d stand-down lines, want 1; logs:\n%s", n, logs)
+ }
+ g := r.gen()
+ if g.N == lostGen.Load() {
+ t.Fatalf("still on generation %d, the one whose lease was lost", g.N)
+ }
+ if n := r.b.count(fmt.Sprintf("start jobs gen%d", g.N)); n != 1 {
+ t.Fatalf("the new wake's worker started %d times, want once: %v", n, r.b.events())
+ }
+ if n := r.b.alive(); n != 1 {
+ t.Fatalf("%d workers run, want the new wake's one", n)
+ }
+ })
+}
+
+// [pf W1.23] A worker start under the wake's context writes no second
+// pending record: web's exec wrote the wake's one.
+func TestWorkerStartWritesNoPendingRecord(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs", "mailer")
+ var records atomic.Int32
+ r.a.BeforeExec = func(context.Context, string, string) error {
+ records.Add(1)
+ return nil
+ }
+ r.wake(t)
+ if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 2 {
+ t.Fatalf("%d workers started, want 2", n)
+ }
+ if n := records.Load(); n != 1 {
+ t.Fatalf("%d build records for one wake, want 1", n)
+ }
+}
+
+// W1.25: no entry and a binary host report nothing; a stopping entry's
+// workers are stopped; awake, running, restarting and crash-loop.
+func TestRootfsWorkersReport(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ if got := r.a.RootfsWorkers(r.host); got != nil {
+ t.Fatalf("no entry: %+v", got)
+ }
+ var waking []WorkerReport
+ r.b.setPrepare(func(string, Gen) { waking = r.a.RootfsWorkers(r.host) })
+ r.wake(t)
+ r.b.setPrepare(nil)
+ if !slices.Equal(waking, []WorkerReport{{"jobs", WorkerStopped, 0}}) {
+ t.Errorf("waking: %+v", waking)
+ }
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerRunning, 0}}) {
+ t.Errorf("awake: %+v", got)
+ }
+ for i := 1; i <= 6; i++ {
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ want := WorkerRestarting
+ if i == 6 {
+ want = WorkerCrashLoop
+ }
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", want, i}}) {
+ t.Errorf("after exit %d: %+v, want %s", i, got, want)
+ }
+ r.clk.advance(sidecarRestartMax)
+ r.tick(t)
+ }
+
+ bin := newWorkerRig(t, testRoute("plain.example.com"), "jobs")
+ bin.wake(t)
+ if got := bin.a.RootfsWorkers(bin.host); got != nil {
+ t.Errorf("a binary host: %+v", got)
+ }
+}
+
+// The doWake path no longer logs D8's workers line; the backend half runs
+// them (W1.12). Through the real backend over the staged control fake.
+func TestWorkersThroughTheProductionBackendInTheService(t *testing.T) {
+ b, ctl, rt, units := newWorkerBackend(t)
+ pb := productionBackend(t, b)
+ a := New(Config{Bucket: "test-bucket"}, pb, nil)
+ armRootfsForTest(a)
+ t.Cleanup(func() { a.Shutdown(context.Background()) })
+ web, g := startWorkerWeb(t, b, ctl, rt, units, "SHOP_MODE=live\n")
+ writeDeclaredManifest(t, b, g.Build, g.Digest, map[string]release.Process{
+ release.ProcessWeb: {Command: []string{"/app/serve"}}, "jobs": {Command: []string{"/app/jobs"}},
+ }, nil)
+ units.set(instancectl.WorkerUnitName(rt.Host, "jobs"), "active", "winv", true)
+ ctl.inv = "winv"
+ e := &actEntry{host: rt.Host, route: rt, state: actWaking}
+ a.mu.Lock()
+ a.entries[rt.Host] = e
+ a.mu.Unlock()
+ a.startRootfsWorkers(context.Background(), e, rt, &wokenInstance{gen: g, proc: web, rep: &fakeRep{}})
+ ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+rt.Host+" jobs ")
+ a.mu.Lock()
+ wk := e.rootfsWorkers["jobs"]
+ installed := wk != nil && wk.proc != nil
+ e.state = actStopping
+ a.mu.Unlock()
+ if !installed {
+ t.Fatal("the worker was not installed through the production backend")
+ }
+ launch := workerLaunchPath(b, rt, "jobs")
+ if _, err := os.Stat(launch); err != nil {
+ t.Fatalf("the worker's launch file: %v", err)
+ }
+ if !a.stopRootfsWorkers(e) {
+ t.Fatal("the worker was not proven gone through the production backend")
+ }
+ ctl.mustHaveCallPrefix(t, "stop-rootfs "+rt.Host+" role=worker gen=0 worker=jobs kill=false")
+ if _, err := os.Stat(launch); !os.IsNotExist(err) {
+ t.Fatalf("the proven worker's launch file: %v", err)
+ }
+ a.mu.Lock()
+ delete(a.entries, rt.Host)
+ a.mu.Unlock()
+}
+
+// [pf W1.17] A worker is restarted only once every earlier handle of its
+// name has ended (its observer returned, its listeners closed), even after
+// root proved the unit gone: no preparation binds the log socket beside a
+// handle still holding it, neither the restart's own proof nor the tick's
+// re-proof of the stray lets one through, and once the handle ends the
+// worker starts again.
+func TestRootfsWorkerRestartWaitsForItsOldHandle(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ unproven bool
+ }{
+ {"its proof not given", true},
+ {"proven, its handle lingering", false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
+ // The restart proves the old handle gone, then its start may
+ // have run (a 502 with a handle back, which lingers), and that
+ // start's proof is given or not.
+ r.b.wmu.Lock()
+ r.b.uncertain = true
+ r.b.wmu.Unlock()
+ var calls atomic.Int32
+ r.b.setGone(func(string) error {
+ if calls.Add(1) == 2 && c.unproven {
+ return instancectl.ErrGenUnproven
+ }
+ return nil
+ })
+ r.tick(t)
+ if got := r.strays(); !slices.Equal(got, []string{"jobs"}) {
+ t.Fatalf("strays %v, want jobs", got)
+ }
+ stray := r.b.lastWorker(t, "jobs")
+ launches := r.b.launchCount("jobs")
+ if launches != 2 {
+ t.Fatalf("%d preparations, want the wake's and the restart's", launches)
+ }
+
+ // The restart's own proof: the unit is gone, the handle is not.
+ r.clk.advance(sidecarRestartBase)
+ r.tick(t)
+ if n := r.b.launchCount("jobs"); n != launches {
+ t.Fatalf("the worker was prepared %d times beside its lingering handle", n-launches)
+ }
+ if got := r.strays(); !slices.Equal(got, []string{"jobs"}) {
+ t.Fatalf("strays %v after a proof with the handle lingering, want jobs kept", got)
+ }
+ // The tick's re-proof of the stray, twice.
+ r.clk.advance(actStopTimeout)
+ r.tick(t)
+ r.tick(t)
+ if n := r.b.launchCount("jobs"); n != launches {
+ t.Fatalf("the worker was prepared %d times beside its lingering handle", n-launches)
+ }
+ if got := r.strays(); !slices.Equal(got, []string{"jobs"}) {
+ t.Fatalf("strays %v after re-proofs with the handle lingering, want jobs kept", got)
+ }
+
+ stray.end()
+ for i := 0; i < 4 && r.b.launchCount("jobs") == launches; i++ {
+ r.clk.advance(sidecarRestartMax)
+ r.tick(t)
+ }
+ if n := r.b.launchCount("jobs"); n != launches+1 {
+ t.Fatalf("%d starts once the handle ended, want 1", n-launches)
+ }
+ if len(r.strays()) != 0 || r.b.alive() != 1 {
+ t.Fatalf("strays %v, %d alive; want none and the new worker", r.strays(), r.b.alive())
+ }
+ })
+ }
+}
+
+// [pf W1.10] The tick's arm for a resident whose replica has no lease
+// signal (no watch runs): a loss found while its stop is already pending
+// with a worker unproven re-proves that worker at once.
+func TestRootfsWorkersStopAtLeaseLossUnwatched(t *testing.T) {
+ shrinkResidentPoll(t, time.Hour)
+ rt := residentRoute("shop.example.com")
+ r := newWorkerRig(t, rt, "jobs", "mailer")
+ r.a.residentLister = &fakeResidents{routes: []registry.Route{rt}}
+ startResident(t, r.a, r.host)
+ r.a.mu.Lock()
+ watched := r.a.entries[r.host].ownerDone != nil
+ r.a.mu.Unlock()
+ if watched {
+ t.Fatal("the rig's replica has a lease watch; this case needs none")
+ }
+ var stuck atomic.Bool
+ stuck.Store(true)
+ r.b.setGone(func(name string) error {
+ if name == "mailer" && stuck.Load() {
+ return instancectl.ErrGenUnproven
+ }
+ return nil
+ })
+ r.a.Bounce(r.host)
+ waitFor(t, "the stop to be kept pending", r.pendingStop)
+ if n := r.b.count("gone mailer"); n != 1 {
+ t.Fatalf("%d proofs of mailer before the loss, want 1", n)
+ }
+ stuck.Store(false)
+ r.b.lastRep().setErr(lease.ErrLost)
+ r.a.rootfsTick()
+ waitFor(t, "the tick to prove mailer at once", func() bool { return r.b.count("gone mailer") == 2 })
+ waitFor(t, "the stray to go", func() bool { return len(r.strays()) == 0 })
+ r.a.sweepOnce()
+ waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
+ ev := r.b.events()
+ if second, closed := index(ev, "gone mailer", index(ev, "gone mailer", 0)+1), index(ev, "close", 0); second < 0 || closed < second {
+ t.Fatalf("order %v: the lease went before the stray's proof", ev)
+ }
+}
+
+// [pf W1.13, W0.1] The doWake start's own gate, asked after the worker's
+// preparation inside the wake: a fence, a release record or a shutdown
+// raised there starts nothing, and the worker is not counted as running.
+func TestWorkerGateRefusesTheWakeStart(t *testing.T) {
+ for _, c := range []struct {
+ name string
+ hit func(r *workerRig)
+ }{
+ {"a fence", func(r *workerRig) { raiseFence(r.a, r.host) }},
+ {"a release record", func(r *workerRig) { openReleaseRecord(r.a, r.host) }},
+ {"the startup sweep not proven", func(r *workerRig) { r.a.rootfsSwept.Store(false) }},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ var hit atomic.Bool
+ r.b.setPrepare(func(string, Gen) {
+ if hit.CompareAndSwap(false, true) {
+ c.hit(r)
+ }
+ })
+ release, err := r.a.beginRequest(context.Background(), r.rt)
+ if err == nil {
+ release()
+ }
+ if !hit.Load() {
+ t.Fatal("the worker's preparation never ran inside the wake")
+ }
+ if n := len(r.b.workers("jobs")); n != 0 {
+ t.Fatalf("root was asked for %d worker starts", n)
+ }
+ if got := r.a.RootfsWorkers(r.host); len(got) == 1 && got[0].State == WorkerRunning {
+ t.Fatalf("report %+v", got)
+ }
+ r.a.mu.Lock()
+ delete(r.a.releaseOps, r.host)
+ r.a.fences = nil
+ r.a.mu.Unlock()
+ r.a.rootfsSwept.Store(true)
+ })
+ }
+}
+
+// [pf W1.14] The stray rule: a start of worker n of generation G is
+// refused while any stray is of another generation or is named n; a stray
+// of G with another name does not block it.
+func TestWorkerGateStrayRule(t *testing.T) {
+ stray := func(name string, gen uint64) *rootfsWorker { return &rootfsWorker{name: name, gen: gen} }
+ for _, c := range []struct {
+ strays []*rootfsWorker
+ name string
+ gen uint64
+ refuse bool
+ }{
+ {nil, "jobs", 2, false},
+ {[]*rootfsWorker{stray("mailer", 2)}, "jobs", 2, false},
+ {[]*rootfsWorker{stray("jobs", 2)}, "jobs", 2, true},
+ {[]*rootfsWorker{stray("mailer", 1)}, "jobs", 2, true},
+ {[]*rootfsWorker{stray("jobs", 1)}, "jobs", 2, true},
+ {[]*rootfsWorker{stray("mailer", 2), stray("cron", 1)}, "jobs", 2, true},
+ } {
+ e := &actEntry{strayRootfsWorkers: c.strays}
+ err := workerStrayRuleLocked(e, c.gen, c.name)
+ if (err != nil) != c.refuse || (err != nil && !errors.Is(err, errWorkerStray)) {
+ var have []string
+ for _, s := range c.strays {
+ have = append(have, fmt.Sprintf("%s/%d", s.name, s.gen))
+ }
+ t.Errorf("start %s/%d beside strays %v: %v, want refused %v", c.name, c.gen, have, err, c.refuse)
+ }
+ }
+}
+
+// [pf W1.11] The one install point installs only on the host's own entry,
+// for a worker still the entry's, while it is waking, or awake and owned,
+// and an awake resident only under its lease watch (or with a replica
+// that has no lease signal, which the tick watches).
+func TestRootfsWorkerInstallNeedsTheLeaseWatch(t *testing.T) {
+ a := New(Config{Bucket: "test-bucket"}, &fakeBackend{}, nil)
+ signal := newOwnedRep(&fakeRep{}, time.Now().Add(time.Hour))
+ t.Cleanup(func() { signal.timer.Stop() })
+ lost := &fakeRep{}
+ lost.setErr(lease.ErrLost)
+ for _, c := range []struct {
+ name string
+ rt registry.Route
+ state actState
+ rep Rep
+ watched bool
+ other bool // another entry is the host's
+ install bool
+ }{
+ {"waking", residentRoute("shop.example.com"), actWaking, nil, false, false, true},
+ {"awake on demand", workerHost(), actAwake, &fakeRep{}, false, false, true},
+ {"awake resident, watched", residentRoute("shop.example.com"), actAwake, signal, true, false, true},
+ {"awake resident, no lease signal", residentRoute("shop.example.com"), actAwake, &fakeRep{}, false, false, true},
+ {"awake resident, its watch not running", residentRoute("shop.example.com"), actAwake, signal, false, false, false},
+ {"awake, the lease lost", workerHost(), actAwake, lost, false, false, false},
+ {"stopping", workerHost(), actStopping, &fakeRep{}, false, false, false},
+ {"not the host's entry", workerHost(), actAwake, &fakeRep{}, false, true, false},
+ } {
+ t.Run(c.name, func(t *testing.T) {
+ e := &actEntry{host: c.rt.Host, route: c.rt, state: c.state, rep: c.rep}
+ if c.watched {
+ e.ownerDone = make(chan struct{})
+ }
+ wk := &rootfsWorker{name: "jobs"}
+ e.rootfsWorkers = map[string]*rootfsWorker{"jobs": wk}
+ a.mu.Lock()
+ a.entries[c.rt.Host] = e
+ if c.other {
+ a.entries[c.rt.Host] = &actEntry{host: c.rt.Host, route: c.rt, state: actAwake}
+ }
+ got := a.installRootfsWorkerLocked(e, wk, &fakeWorkerProc{name: "jobs"})
+ delete(a.entries, c.rt.Host)
+ a.mu.Unlock()
+ if got != c.install || (wk.proc != nil) != c.install {
+ t.Fatalf("installed %v (handle %v), want %v", got, wk.proc != nil, c.install)
+ }
+ })
+ }
+}
+
+// The rootfs launch fixture's worker seams: the real backend's, over the
+// rig's own row, as its other seams are.
+func (b *rootfsLaunch) LaunchRootfsWorker(ctx context.Context, _ registry.Route, name string, g Gen, web Proc) (Proc, error) {
+ return b.eb.LaunchRootfsWorker(ctx, b.rt, name, g, web)
+}
+
+func (b *rootfsLaunch) RootfsWorkerGone(ctx context.Context, _ registry.Route, name string) error {
+ return b.eb.RootfsWorkerGone(ctx, b.rt, name)
+}
+
+func (b *rootfsLaunch) removeRootfsWorkerFiles(_ registry.Route, name string) {
+ b.eb.removeRootfsWorkerFiles(b.rt, name)
+}
+
+// StartRootfsWorker makes the worker's unit active and populated, as root
+// starting it would; its stop (StopRootfs) empties it.
+func (c *stagedRootfsCtl) StartRootfsWorker(ctx context.Context, host, name string, max int64, img instancectl.StagedImage) (string, error) {
+ if _, err := c.fakeControl.StartRootfsWorker(ctx, host, name, max, img); err != nil {
+ return "", err
+ }
+ c.umu.Lock()
+ defer c.umu.Unlock()
+ c.workerStarts++
+ inv := fmt.Sprintf("winv-%s-%d", name, c.workerStarts)
+ c.units[instancectl.WorkerUnitName(host, name)] = [3]string{"active", inv, "populated"}
+ return inv, nil
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/install_worker.go b/internal/activator/testdata/rootfs_verb_guard/install_worker.go
new file mode 100644
index 000000000..4f7618db5
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/install_worker.go
@@ -0,0 +1,24 @@
+// A rootfs worker's handle written around installRootfsWorkerLocked (Group
+// W, W1.11): directly, in a tuple, through its address, in a literal, and
+// by a namesake of the owner on another receiver.
+package activator
+
+func (a *Service) installGuardWorker(wk *rootfsWorker, p Proc) {
+ wk.proc = p
+}
+
+func (a *Service) installGuardWorkerTuple(wk *rootfsWorker, p Proc) {
+ wk.name, wk.proc = "jobs", p
+}
+
+func (a *Service) installGuardWorkerAddr(wk *rootfsWorker) *Proc {
+ return &wk.proc
+}
+
+func (a *Service) installGuardWorkerLiteral(p Proc) *rootfsWorker {
+ return &rootfsWorker{name: "jobs", proc: p}
+}
+
+func (s *shedChild) installRootfsWorkerLocked(wk *rootfsWorker, p Proc) {
+ wk.proc = p
+}
diff --git a/internal/activator/testdata/rootfs_verb_guard/install_worker_clean.go b/internal/activator/testdata/rootfs_verb_guard/install_worker_clean.go
new file mode 100644
index 000000000..368312100
--- /dev/null
+++ b/internal/activator/testdata/rootfs_verb_guard/install_worker_clean.go
@@ -0,0 +1,12 @@
+// The worker install guard's clean fixture (Group W, W1.11): an install
+// through installRootfsWorkerLocked, a literal without a handle, and reads
+// of the handle.
+package activator
+
+func (a *Service) installGuardWorkerClean(e *actEntry, p Proc) bool {
+ wk := &rootfsWorker{name: "jobs", gen: 3}
+ if !a.installRootfsWorkerLocked(e, wk, p) {
+ return false
+ }
+ return wk.proc != nil && !wk.proc.Exited()
+}
diff --git a/internal/rolloutwords/words.go b/internal/rolloutwords/words.go
index 50618d0b6..af5fd5ee4 100644
--- a/internal/rolloutwords/words.go
+++ b/internal/rolloutwords/words.go
@@ -100,6 +100,17 @@ const (
EventReleaseLeaseLost = "the release command of build %s was stopped because this box no longer holds the instance. it runs again on the next attempt" // RFS-3-C29
)
+// A rootfs instance's worker events (rootfs apps Plan 3, Group W),
+// approved in the same deck: a worker the build declares beside web,
+// filled with the worker's name first. C09's status is the exit code, or
+// 128 plus the signal's number for a signal's end; its delay is the wait
+// before the restart, formatted as C11's is.
+const (
+ EventWorkerStarted = "worker %s started" // RFS-3-C08
+ EventWorkerExited = "worker %s exited with status %d. starting it again in %s" // RFS-3-C09
+ EventWorkerCrashLoop = "worker %s keeps exiting. it is started again once a minute" // RFS-3-C10
+)
+
// States: the REASON column of `carlos instances list` (spec §9.1).
const (
StateHeld = "held: build %s failed on this box"