carlos / platform Public

activator: rootfs workers handed over after the switch; never two worker sets

Overlap swap step 8 now calls handOverRootfsWorkers in place of D8's
rootfsProcessesHook, which is removed. The handover stops every worker of
an earlier generation, and every stray of one, through stopRootfsWorkers's
parallel stop and proof (stopRootfsWorkersWhere, a generation filter),
waiting for any start in flight. Only then does it register the switched
generation's set as pending, through registerRootfsWorkers: the one
registration path, which doWake's declareRootfsWorkers now shares. It
launches nothing. The 2 s tick starts the new set through workerGate,
whose stray rule refuses each start while an old worker is unproven
(Paul's ruling, W2 addendum). A config or restart attempt onto the same
build hands over the same way.

Shared W1 code: a retiring worker (one whose generation the swap moved
past) is no longer supervised, is forgotten without root when it never
ran, is forgotten once proven, and becomes a stray only if it holds a
handle. Registration never drops a live handle: it is made a stray.

Tests: rootfs_deploy_test.go (never two sets, with ticks racing the swap
and with one old worker unproven; config attempt env through the real
ExecBackend; pins after dropMember; hold swap; R3's
TestNoWorkerAfterAFailedRelease; in-flight start, never-started set,
retiring exits); D8's swap subtest now asserts the handover; a
reachability guard proves nothing from swapOverlap launches or installs
a worker. No instancectl change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 99426ea136ec69e72d3ed484605544bc35aea2e3 parent 01eb553
6 files changed, +1,008 −90
  • internal/activator/backend_rootfs.go +0 −31
  • internal/activator/rootfs_deploy_test.go +773 −0
  • internal/activator/rootfs_install_guard_test.go +33 −0
  • internal/activator/rootfs_processes_test.go +71 −22
  • internal/activator/rootfsworkers.go +126 −34
  • internal/activator/swap.go +5 −3
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go
index 6720b99b2..db95c24d6 100644
--- a/internal/activator/backend_rootfs.go
+++ b/internal/activator/backend_rootfs.go
@@ -10,7 +10,6 @@ import (
"log"
"os"
"path/filepath"
- "slices"
"strings"
"sync"
@@ -84,36 +83,6 @@ func (b *ExecBackend) Processes(rt registry.Route, id release.StagedIdentity) (m
return m.Processes, nil
}
-// 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 woken instance's
-// workers are declared by its wake and started by the tick (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
- }
- procs, err := a.declaredProcesses(rt, g)
- if err != nil {
- log.Printf("activator: %s: build %s: its declared processes cannot be read, so this box runs web alone: %v", rt.Host, g.Build, err)
- return
- }
- var workers []string
- for name := range procs {
- if release.ValidWorkerName(name) {
- workers = append(workers, name)
- }
- }
- slices.Sort(workers)
- if len(workers) > 0 {
- log.Printf("activator: %s: build %s declares workers (%s); this box does not run workers yet", rt.Host, g.Build, strings.Join(workers, ", "))
- }
-}
-
// declaredProcesses is g's declared processes through the Service's
// backend, refused when g names no whole staged build or the backend
// cannot read them.
diff --git a/internal/activator/rootfs_deploy_test.go b/internal/activator/rootfs_deploy_test.go
new file mode 100644
index 000000000..5d34aa1af
--- /dev/null
+++ b/internal/activator/rootfs_deploy_test.go
@@ -0,0 +1,773 @@
+package activator
+
+// Rootfs apps Plan 3, Group W, Task W2: a rootfs row's workers handed over
+// at an overlap swap's step 8 (spec §5.2, §5.4), under Paul's ruling that
+// only the tick starts a worker: the retiring generation's workers are
+// stopped and proven gone, then the switched generation's set is
+// registered as pending, and the tick starts it through workerGate. Two
+// generations' workers never run at once. The ordering tests drive the
+// real Service.Swap over the swap fake with W1b's fake worker verbs
+// sharing its order log, on a fake clock; the production-wired witnesses
+// drive the real ExecBackend over fakeControl. Not parallel: several
+// capture the standard logger.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "slices"
+ "strings"
+ "sync"
+ "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"
+)
+
+// relWorkerBackend is relSwapBackend with W1b's fake worker verbs; the
+// verbs record into the same order log ("start <name> gen<N>" once a
+// start passed its gate, "gone <name>", "proven <name>", "files <name>").
+type relWorkerBackend struct {
+ *relSwapBackend
+ w *fakeWorkerBackend
+}
+
+func (b *relWorkerBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) {
+ return b.w.LaunchRootfsWorker(ctx, rt, name, g, web)
+}
+
+func (b *relWorkerBackend) RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error {
+ return b.w.RootfsWorkerGone(ctx, rt, name)
+}
+
+func (b *relWorkerBackend) removeRootfsWorkerFiles(rt registry.Route, name string) {
+ b.w.removeRootfsWorkerFiles(rt, name)
+}
+
+var (
+ _ RootfsWorkerBackend = (*relWorkerBackend)(nil)
+ _ SwapBackend = (*relWorkerBackend)(nil)
+ _ ReleaseBackend = (*relWorkerBackend)(nil)
+)
+
+// handoverFixture is relSwapFixture over relWorkerBackend: the rootfs
+// incumbent (v1) runs gen 1's workers, registered as a handover registers
+// a set and started by the tick; v2 declares the same workers and no
+// release unless the test says otherwise.
+type handoverFixture struct {
+ *relSwapFixture
+ w *fakeWorkerBackend
+ workers []string
+}
+
+// workerProcs is a build declaring web and workers.
+func workerProcs(workers ...string) map[string]release.Process {
+ procs := map[string]release.Process{release.ProcessWeb: {Command: []string{"/app/serve"}}}
+ for _, w := range workers {
+ procs[w] = release.Process{Command: []string{"/app/" + w}}
+ }
+ return procs
+}
+
+func newHandoverFixture(t *testing.T, workers ...string) *handoverFixture {
+ t.Helper()
+ h := newHandoverFixtureDeclared(t, workers...)
+ h.tick(t)
+ for _, n := range workers {
+ if got := h.w.count(fmt.Sprintf("start %s gen%d", n, h.incumbent.N)); got != 1 {
+ t.Fatalf("gen 1's %s started %d times, want once; order %v", n, got, h.b.events())
+ }
+ }
+ return h
+}
+
+// newHandoverFixtureDeclared is newHandoverFixture before the tick: gen
+// 1's set is registered and none of it has started.
+func newHandoverFixtureDeclared(t *testing.T, workers ...string) *handoverFixture {
+ t.Helper()
+ f := newRelSwapFixture(t, true)
+ armRootfsForTest(f.a)
+ w := &fakeWorkerBackend{killBackend: &killBackend{fakeBackend: f.rb.fakeBackend}}
+ f.a.backend = &relWorkerBackend{relSwapBackend: f.rb, w: w}
+ f.a.genHealth = func(_ context.Context, g Gen) error {
+ f.b.record(fmt.Sprintf("health:%d", g.N))
+ return nil
+ }
+ f.rb.rmu.Lock()
+ f.rb.procs["v1"], f.rb.procs["v2"] = workerProcs(workers...), workerProcs(workers...)
+ f.rb.rmu.Unlock()
+ // The incumbent names a whole staged build, as a rootfs generation does.
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ e.gen.Digest = "aa11"
+ f.incumbent = e.gen
+ f.a.mu.Unlock()
+ h := &handoverFixture{relSwapFixture: f, w: w, workers: workers}
+ t.Cleanup(func() {
+ w.setGone(nil)
+ f.clk.advance(actStopTimeout + time.Second)
+ })
+ // Gen 1's set: registered as a handover registers one (nothing old
+ // to stop); the tick starts it.
+ f.a.handOverRootfsWorkers(e)
+ return h
+}
+
+// tick runs one resident tick and waits until no worker start or proof is
+// in flight.
+func (h *handoverFixture) tick(t *testing.T) {
+ t.Helper()
+ tickWorkers(t, h.a, h.host)
+}
+
+func tickWorkers(t *testing.T, a *Service, host string) {
+ t.Helper()
+ a.rootfsTick()
+ waitFor(t, "the tick's worker starts and proofs", func() bool { return workersSettled(a, host) })
+}
+
+func workersSettled(a *Service, host string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[host]
+ if e == nil {
+ return true
+ }
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting {
+ return false
+ }
+ }
+ return len(e.workerProofs) == 0
+}
+
+// strayNames is host's strays by name and generation.
+func strayNames(a *Service, host string) []string {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ var out []string
+ if e := a.entries[host]; e != nil {
+ for _, s := range e.strayRootfsWorkers {
+ out = append(out, fmt.Sprintf("%s gen%d", s.name, s.gen))
+ }
+ }
+ return out
+}
+
+// registered is host's workers as "<name> gen<N> pending|started".
+func registered(a *Service, host string) []string {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ var out []string
+ if e := a.entries[host]; e != nil {
+ for _, n := range sortedWorkerNames(e.rootfsWorkers) {
+ wk := e.rootfsWorkers[n]
+ state := "started"
+ if wk.pending {
+ state = "pending"
+ }
+ out = append(out, fmt.Sprintf("%s gen%d %s", n, wk.gen, state))
+ }
+ }
+ return out
+}
+
+// startsOf is the positions of every worker start of generation n.
+func startsOf(ev []string, n uint64) []int {
+ var out []int
+ suffix := fmt.Sprintf(" gen%d", n)
+ for i, e := range ev {
+ if strings.HasPrefix(e, "start ") && strings.HasSuffix(e, suffix) {
+ out = append(out, i)
+ }
+ }
+ return out
+}
+
+// neverTwoSets fails t unless, in the order log ev, every start of
+// generation g2's workers follows the successor's health check and the
+// switch to it, and the proof of every gen-1 worker's last start: no
+// gen-2 worker ran beside a gen-1 one. It answers the first gen-2 start.
+func neverTwoSets(t *testing.T, ev []string, g1, g2 uint64, workers []string) int {
+ t.Helper()
+ g2s := startsOf(ev, g2)
+ if len(g2s) == 0 {
+ t.Fatalf("no worker of generation %d started; order %v", g2, ev)
+ }
+ first := g2s[0]
+ health, sw := index(ev, fmt.Sprintf("health:%d", g2), 0), index(ev, fmt.Sprintf("switch:%d", g2), 0)
+ if health < 0 || sw < health || first < sw {
+ t.Errorf("generation %d's first worker start (%d) does not follow its health (%d) and switch (%d); order %v", g2, first, health, sw, ev)
+ }
+ for _, n := range workers {
+ last := lastWithPrefix(ev, fmt.Sprintf("start %s gen%d", n, g1))
+ if last < 0 {
+ t.Fatalf("gen 1's %s never started; order %v", n, ev)
+ }
+ proven := index(ev, "proven "+n, last)
+ if proven < 0 || proven > first {
+ t.Errorf("generation %d's first worker start (%d) precedes the proof of gen 1's %s (%d): two worker sets ran at once; order %v", g2, first, n, proven, ev)
+ }
+ }
+ return first
+}
+
+// W2 rules 1 and 2 [pf W1.14, W2.4], with Paul's ruling (addendum): the
+// handover stops and proves gen 1's set, registers gen 2's and launches
+// nothing; the tick starts gen 2's after the successor's health and every
+// gen-1 proof; with a gen-1 worker unproven, no gen-2 worker starts by any
+// path until a tick proves it, and then the tick starts the set. Ticks
+// race the swap in the last two cases (run under -race).
+func TestOverlapHandsOverWorkersNeverTwoSets(t *testing.T) {
+ t.Run("the handover registers, the tick starts", func(t *testing.T) {
+ h := newHandoverFixture(t, "jobs", "mailer")
+ g1 := h.incumbent.N
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ g2 := res.Gen.N
+ ev := h.b.events()
+ if n := len(startsOf(ev, g2)); n != 0 {
+ t.Fatalf("the swap started %d gen-2 workers; the tick alone starts them; order %v", n, ev)
+ }
+ for _, n := range h.workers {
+ if c := h.w.launchCount(n); c != 1 {
+ t.Errorf("%s was prepared %d times by the swap (gen 1's once); the handover launches nothing", n, c)
+ }
+ if !h.w.lastWorker(t, n).Exited() {
+ t.Errorf("gen 1's %s still runs after the handover", n)
+ }
+ }
+ want := []string{fmt.Sprintf("jobs gen%d pending", g2), fmt.Sprintf("mailer gen%d pending", g2)}
+ if got := registered(h.a, h.host); !slices.Equal(got, want) {
+ t.Fatalf("registered %v after the swap, want %v", got, want)
+ }
+ if s := strayNames(h.a, h.host); len(s) != 0 {
+ t.Fatalf("strays %v after a proven handover", s)
+ }
+ h.tick(t)
+ ev = h.b.events()
+ neverTwoSets(t, ev, g1, g2, h.workers)
+ want = []string{fmt.Sprintf("jobs gen%d started", g2), fmt.Sprintf("mailer gen%d started", g2)}
+ if got := registered(h.a, h.host); !slices.Equal(got, want) {
+ t.Fatalf("registered %v after the tick, want %v", got, want)
+ }
+ if n := h.w.alive(); n != 2 {
+ t.Fatalf("%d workers alive, want gen 2's two", n)
+ }
+ })
+ t.Run("ticks racing the swap", func(t *testing.T) {
+ h := newHandoverFixture(t, "jobs", "mailer")
+ g1 := h.incumbent.N
+ stop := raceTicks(h.a)
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ stop()
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ h.tick(t)
+ neverTwoSets(t, h.b.events(), g1, res.Gen.N, h.workers)
+ if n := h.w.alive(); n != 2 {
+ t.Fatalf("%d workers alive, want gen 2's two", n)
+ }
+ })
+ t.Run("one gen-1 worker unproven", func(t *testing.T) {
+ h := newHandoverFixture(t, "jobs", "mailer")
+ g1 := h.incumbent.N
+ h.w.setGone(func(name string) error {
+ if name == "mailer" {
+ return errors.New("instance control: 502: stop: termination unproven")
+ }
+ return nil
+ })
+ stop := raceTicks(h.a)
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ stop()
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ g2 := res.Gen.N
+ if s := strayNames(h.a, h.host); !slices.Equal(s, []string{fmt.Sprintf("mailer gen%d", g1)}) {
+ t.Fatalf("strays %v, want gen 1's mailer", s)
+ }
+ // Ticks inside the stray's retry pace: still no gen-2 worker, by
+ // any path.
+ for range 3 {
+ h.clk.advance(time.Second)
+ h.tick(t)
+ }
+ if n := len(startsOf(h.b.events(), g2)); n != 0 {
+ t.Fatalf("%d gen-2 workers started beside gen 1's unproven mailer; order %v", n, h.b.events())
+ }
+ // The stray's proof, by the tick; then the tick starts gen 2's set.
+ h.w.setGone(nil)
+ h.clk.advance(actStopTimeout)
+ for i := 0; len(startsOf(h.b.events(), g2)) < 2; i++ {
+ if i == 5 {
+ t.Fatalf("gen 2's set did not start after the stray's proof; order %v", h.b.events())
+ }
+ h.clk.advance(sidecarRestartBase)
+ h.tick(t)
+ }
+ ev := h.b.events()
+ first := neverTwoSets(t, ev, g1, g2, h.workers)
+ if last := lastWithPrefix(ev, "proven mailer"); last > first {
+ t.Errorf("a gen-2 start (%d) preceded the stray's last proof (%d); order %v", first, last, ev)
+ }
+ if s := strayNames(h.a, h.host); len(s) != 0 {
+ t.Fatalf("strays %v after the proof", s)
+ }
+ })
+}
+
+// A retiring worker is the handover's alone: one that exits after the
+// switch, before step 8 (here while the retiring generation drains), is
+// neither noted as a crash (no RFS-3-C09) nor restarted by the tick.
+func TestRetiringWorkerIsNotSupervised(t *testing.T) {
+ h := newHandoverFixture(t, "jobs")
+ jobs := h.w.lastWorker(t, "jobs")
+ incumbent := h.b.lastProc()
+ incumbent.mu.Lock()
+ incumbent.onStopEnter = func() {
+ jobs.exit("exited", "1")
+ h.clk.advance(sidecarRestartMax)
+ tickWorkers(t, h.a, h.host)
+ h.clk.advance(sidecarRestartMax)
+ tickWorkers(t, h.a, h.host)
+ }
+ incumbent.mu.Unlock()
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ if !incumbent.isStopped() {
+ t.Fatal("the retiring generation was not stopped: the hook never ran")
+ }
+ if n := h.w.launchCount("jobs"); n != 1 {
+ t.Fatalf("jobs was prepared %d times by the swap; the retiring one must not be restarted", n)
+ }
+ if n := eventsLike(h.sink.msgs(), "worker jobs exited"); n != 0 {
+ t.Fatalf("a retiring worker's exit was reported %d times: %q", n, h.sink.msgs())
+ }
+ h.tick(t)
+ if n := len(startsOf(h.b.events(), res.Gen.N)); n != 1 {
+ t.Fatalf("gen 2's jobs started %d times, want once; order %v", n, h.b.events())
+ }
+}
+
+// A gen-1 set registered but never started (the swap came before the
+// tick's first pass) ran nothing, so the handover forgets it without
+// asking root (W1's pending rule, on an awake entry), even when every
+// proof would fail, and registers gen 2's set.
+func TestHandoverOfANeverStartedSet(t *testing.T) {
+ h := newHandoverFixtureDeclared(t, "jobs", "mailer")
+ h.w.setGone(func(string) error { return errors.New("instance control: 502: stop: termination unproven") })
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ for _, ev := range h.b.events() {
+ if strings.HasPrefix(ev, "gone ") || strings.HasPrefix(ev, "start ") {
+ t.Fatalf("root was asked %q for a set that never started; order %v", ev, h.b.events())
+ }
+ }
+ if s := strayNames(h.a, h.host); len(s) != 0 {
+ t.Fatalf("strays %v from a set that never started", s)
+ }
+ want := []string{fmt.Sprintf("jobs gen%d pending", res.Gen.N), fmt.Sprintf("mailer gen%d pending", res.Gen.N)}
+ if got := registered(h.a, h.host); !slices.Equal(got, want) {
+ t.Fatalf("registered %v, want %v", got, want)
+ }
+ h.tick(t)
+ if n := len(startsOf(h.b.events(), res.Gen.N)); n != 2 {
+ t.Fatalf("gen 2's set started %d workers, want 2; order %v", n, h.b.events())
+ }
+}
+
+// W2 rule 4 (addendum): an old worker's start in flight when step 8 runs
+// is waited for (startDone), then proven gone, before the new set is
+// registered; root's answer to the start never lands after the proof.
+func TestHandoverWaitsForAnOldStart(t *testing.T) {
+ h := newHandoverFixture(t, "jobs")
+ g1 := h.incumbent.N
+ // Gen 1's jobs exits; the tick notes it, and its restart is held in
+ // root once it passed its gate.
+ h.w.lastWorker(t, "jobs").exit("exited", "1")
+ h.tick(t)
+ block, entered := make(chan struct{}), make(chan string, 1)
+ h.w.wmu.Lock()
+ h.w.block, h.w.entered = block, entered
+ h.w.wmu.Unlock()
+ h.clk.advance(sidecarRestartMax)
+ h.a.rootfsTick()
+ select {
+ case <-entered:
+ case <-time.After(10 * time.Second):
+ t.Fatal("gen 1's restart never reached root")
+ }
+ h.w.wmu.Lock()
+ h.w.block, h.w.entered = nil, nil
+ h.w.wmu.Unlock()
+ ch := h.swapAsync(h.attempt(ModeOverlap))
+ waitFor(t, "the switch", func() bool { return lastWithPrefix(h.b.events(), "switch:") >= 0 })
+ time.Sleep(50 * time.Millisecond)
+ if p, sw := lastWithPrefix(h.b.events(), "gone jobs"), lastWithPrefix(h.b.events(), "switch:"); p > sw {
+ t.Fatalf("the handover asked root to prove jobs (%d) while its start was in flight; order %v", p, h.b.events())
+ }
+ close(block)
+ res := waitSwap(t, ch)
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ h.tick(t)
+ ev := h.b.events()
+ returned := index(ev, "returned jobs", lastWithPrefix(ev, "switch:"))
+ proven := index(ev, "proven jobs", returned)
+ if returned < 0 || proven < 0 {
+ t.Fatalf("the held start's return (%d) and a later proof (%d); order %v", returned, proven, ev)
+ }
+ neverTwoSets(t, ev, g1, res.Gen.N, h.workers)
+ if n := h.w.alive(); n != 1 {
+ t.Fatalf("%d workers alive, want gen 2's jobs alone", n)
+ }
+}
+
+// raceTicks runs the resident tick in a loop until the returned stop is
+// called, as the 2 s ticker would, far faster.
+func raceTicks(a *Service) (stop func()) {
+ done := make(chan struct{})
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-done:
+ return
+ default:
+ }
+ a.rootfsTick()
+ time.Sleep(200 * time.Microsecond)
+ }
+ }()
+ return func() { close(done); wg.Wait() }
+}
+
+// [pf W1.19] The retiring set's pins are the workers' own builds: after
+// dropMember of gen 1, the generations file on disk still names v1 while
+// gen 1's mailer is a stray, and stops naming it once the stray is proven
+// (published by the next start).
+func TestRetiringWorkersStayPinnedAfterDropMember(t *testing.T) {
+ h := newHandoverFixture(t, "jobs", "mailer")
+ h.w.setGone(func(name string) error {
+ if name == "mailer" {
+ return errors.New("instance control: 502: stop: termination unproven")
+ }
+ return nil
+ })
+ res := h.a.Swap(context.Background(), h.attempt(ModeOverlap), h.newest)
+ if res.Outcome != SwapDone {
+ t.Fatalf("Swap = %+v", res)
+ }
+ if _, members := h.a.genStateForTest(h.host); len(members) != 0 {
+ t.Fatalf("members %v: the retiring generation was not dropped", members)
+ }
+ if !pinnedSettled(t, h.a, h.host, "v1") {
+ t.Fatal("the generations file stopped naming v1 while gen 1's mailer is a stray")
+ }
+ h.w.setGone(nil)
+ h.clk.advance(actStopTimeout)
+ for i := 0; len(startsOf(h.b.events(), res.Gen.N)) < 2; i++ {
+ if i == 5 {
+ t.Fatalf("gen 2's set did not start; order %v", h.b.events())
+ }
+ h.clk.advance(sidecarRestartBase)
+ h.tick(t)
+ }
+ if pinnedSettled(t, h.a, h.host, "v1") {
+ t.Fatal("the generations file still names v1 after gen 1's last worker was proven")
+ }
+ if !pinnedSettled(t, h.a, h.host, "v2") {
+ t.Fatal("the generations file does not name v2")
+ }
+}
+
+// [pf W2.3] A hold swap stops the entry, which stops and proves gen 1's
+// workers first (W1b's stop-first), and its pinned wake registers gen 2's,
+// which the tick starts: never both.
+func TestHoldSwapStopsThenStartsWorkers(t *testing.T) {
+ h := newHandoverFixture(t, "jobs", "mailer")
+ ownedWakeLeases(h.b.fakeBackend)
+ g1 := h.incumbent.N
+ res := waitSwap(t, h.swapAsync(h.attempt(ModeHold)))
+ if res.Outcome != SwapDone {
+ t.Fatalf("the hold = %+v", res)
+ }
+ g2 := res.Gen.N
+ ev := h.b.events()
+ web := lastWithPrefix(ev, "startGen:")
+ for _, n := range h.workers {
+ last := lastWithPrefix(ev, fmt.Sprintf("start %s gen%d", n, g1))
+ if p := index(ev, "proven "+n, last); p < 0 || web < 0 || p > web {
+ t.Errorf("gen 1's %s proven at %d, the pinned wake's web started at %d; want the proof first; order %v", n, p, web, ev)
+ }
+ }
+ if n := len(startsOf(ev, g2)); n != 0 {
+ t.Fatalf("%d gen-2 workers started inside the pinned wake; order %v", n, ev)
+ }
+ tickWorkers(t, h.a, h.host)
+ ev = h.b.events()
+ first := startsOf(ev, g2)
+ if len(first) != 2 {
+ t.Fatalf("gen 2's workers started %d times after the tick, want 2; order %v", len(first), ev)
+ }
+ for _, n := range h.workers {
+ last := lastWithPrefix(ev, fmt.Sprintf("start %s gen%d", n, g1))
+ if p := index(ev, "proven "+n, last); p < 0 || p > first[0] {
+ t.Errorf("a gen-2 worker started (%d) before gen 1's %s was proven (%d); order %v", first[0], n, p, ev)
+ }
+ }
+ if n := h.w.alive(); n != 2 {
+ t.Fatalf("%d workers alive, want gen 2's two", n)
+ }
+}
+
+// R3's conditional test, written by W as the group that landed second [pf
+// W0.1, W2.2]: a cold wake whose release ends in lease loss, refusal or
+// failure starts no worker of B (it never reaches an awake entry of B, so
+// the tick never starts B's set), and an overlap whose release fails is
+// never admitted, so step 8 never runs and gen 1's workers are untouched.
+func TestNoWorkerAfterAFailedRelease(t *testing.T) {
+ // coldWorkers is the wake release rig with the worker verbs: B (v2)
+ // declares a release and jobs, A (v1) declares mailer.
+ coldWorkers := func(t *testing.T) (*wakeRelRig, *fakeWorkerBackend) {
+ r := newWakeRelRig(t)
+ w := &fakeWorkerBackend{killBackend: &killBackend{fakeBackend: r.b.fakeBackend}}
+ r.a.backend = &wakeWorkerBackend{wakeRelBackend: r.b, w: w}
+ procs := releaseDeclared()
+ procs["jobs"] = release.Process{Command: []string{"/app/jobs"}}
+ r.b.rmu.Lock()
+ r.b.procs["v2"], r.b.procs["v1"] = procs, workerProcs("mailer")
+ r.b.rmu.Unlock()
+ return r, w
+ }
+ noneOfB := func(t *testing.T, r *wakeRelRig, w *fakeWorkerBackend) {
+ t.Helper()
+ for range 3 {
+ r.clk.advance(sidecarRestartBase)
+ tickWorkers(t, r.a, r.rt.Host)
+ }
+ if n := w.launchCount("jobs"); n != 0 {
+ t.Fatalf("B's jobs was prepared %d times after its release ended badly", n)
+ }
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ if e := r.a.entries[r.rt.Host]; e != nil && e.rootfsWorkers["jobs"] != nil {
+ t.Fatal("B's jobs is registered after its release ended badly")
+ }
+ }
+ t.Run("a cold wake's lease lost", func(t *testing.T) {
+ r, w := coldWorkers(t)
+ ch := r.wake(r.a)
+ u := r.nextUnit(t)
+ l := r.b.lastLease()
+ until, _ := l.SafeUntil()
+ l.lose(lease.ErrLost)
+ coldReleaseCancelled(t, r, u, until, waitErr(t, ch))
+ noneOfB(t, r, w)
+ })
+ t.Run("a cold wake's release refused", func(t *testing.T) {
+ r, w := coldWorkers(t)
+ r.b.rmu.Lock()
+ r.b.onRead = func(release.StagedIdentity) {
+ if r.b.acquireCount() > 0 {
+ raiseFence(r.a, r.rt.Host)
+ }
+ }
+ r.b.rmu.Unlock()
+ if err := waitErr(t, r.wake(r.a)); err == nil || verdictOf(err) != gateNoOwnership {
+ t.Fatalf("the wake = %v, want a NoOwnership refusal", err)
+ }
+ r.noUnit(t, "a fenced wake")
+ noneOfB(t, r, w)
+ })
+ t.Run("a cold wake's release failed", func(t *testing.T) {
+ r, w := coldWorkers(t)
+ ch := r.wake(r.a)
+ r.nextUnit(t).done("exited", "1", "exit-code")
+ if err := waitErr(t, ch); err != nil {
+ t.Fatalf("the waiting request was not served by the good build: %v", err)
+ }
+ if g, ok := r.a.Current(r.rt.Host); !ok || g.Build != "v1" {
+ t.Fatalf("Current = %+v %v, want A serving", g, ok)
+ }
+ noneOfB(t, r, w)
+ // The tick does start A's own set: B's absence is not a dead tick.
+ if n := w.launchCount("mailer"); n != 1 {
+ t.Fatalf("A's mailer was prepared %d times, want once by the tick", n)
+ }
+ })
+ t.Run("an overlap's release failed", func(t *testing.T) {
+ h := newHandoverFixture(t, "jobs")
+ procs := releaseDeclared()
+ procs["jobs"] = release.Process{Command: []string{"/app/jobs"}}
+ h.rb.rmu.Lock()
+ h.rb.procs["v2"] = procs
+ h.rb.rmu.Unlock()
+ before := len(h.b.events())
+ g1 := h.w.lastWorker(t, "jobs")
+ ch := h.swapAsync(h.attempt(ModeOverlap))
+ h.nextUnit(t).done("1", "1", "exit-code")
+ if res := waitSwap(t, ch); res.Outcome != SwapFailed {
+ t.Fatalf("Swap = %+v, want failed", res)
+ }
+ for range 3 {
+ h.clk.advance(sidecarRestartBase)
+ h.tick(t)
+ }
+ for _, ev := range h.b.events()[before:] {
+ if strings.HasPrefix(ev, "start jobs") || strings.HasPrefix(ev, "gone jobs") || strings.HasPrefix(ev, "switch:") {
+ t.Fatalf("after a failed release: %q; order %v", ev, h.b.events()[before:])
+ }
+ }
+ if g1.Exited() || h.w.launchCount("jobs") != 1 {
+ t.Fatalf("gen 1's jobs was touched (exited %v, prepared %d times)", g1.Exited(), h.w.launchCount("jobs"))
+ }
+ if got, want := registered(h.a, h.host), []string{fmt.Sprintf("jobs gen%d started", h.incumbent.N)}; !slices.Equal(got, want) {
+ t.Fatalf("registered %v, want %v", got, want)
+ }
+ })
+}
+
+// wakeWorkerBackend is wakeRelBackend with W1b's fake worker verbs, sharing
+// its order log.
+type wakeWorkerBackend struct {
+ *wakeRelBackend
+ w *fakeWorkerBackend
+}
+
+func (b *wakeWorkerBackend) LaunchRootfsWorker(ctx context.Context, rt registry.Route, name string, g Gen, web Proc) (Proc, error) {
+ return b.w.LaunchRootfsWorker(ctx, rt, name, g, web)
+}
+
+func (b *wakeWorkerBackend) RootfsWorkerGone(ctx context.Context, rt registry.Route, name string) error {
+ return b.w.RootfsWorkerGone(ctx, rt, name)
+}
+
+func (b *wakeWorkerBackend) removeRootfsWorkerFiles(rt registry.Route, name string) {
+ b.w.removeRootfsWorkerFiles(rt, name)
+}
+
+var _ RootfsWorkerBackend = (*wakeWorkerBackend)(nil)
+
+// rootfsWorkerFixture is the rootfs swap fixture (the real ExecBackend over
+// fakeControl) whose incumbent is a staged rootfs v1 declaring procs1 and
+// whose attempt's v2 declares procs2, gen 1's workers registered and
+// started by the tick through the real backend.
+func rootfsWorkerFixture(t *testing.T, procs1, procs2 map[string]release.Process) (*swapFixture, *rootfsLaunch, *stagedRootfsCtl, Attempt) {
+ t.Helper()
+ f, lb, ctl, at := rootfsSwapFixture(t, ModeOverlap)
+ v1 := stagedRootfsIdentity(t, lb.eb, "v1")
+ writeDeclaredManifest(t, lb.eb, "v1", v1.Digest, procs1, nil)
+ writeDeclaredManifest(t, lb.eb, "v2", at.Digest, procs2, nil)
+ ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
+ f.a.mu.Lock()
+ e := f.a.entries[f.host]
+ e.gen.Build, e.gen.StagedPath, e.gen.Digest = v1.Version, v1.StagedPath, v1.Digest
+ f.incumbent = e.gen
+ // v2 is the row's good build: its release, if declared, is not due.
+ e.route.GoodVersion, e.route.GoodDigest = "v2", at.Digest
+ f.a.mu.Unlock()
+ f.a.handOverRootfsWorkers(e)
+ tickWorkers(t, f.a, f.host)
+ for n := range procs1 {
+ if release.ValidWorkerName(n) {
+ ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+lb.rt.Host+" "+n+" ")
+ }
+ }
+ return f, lb, ctl, at
+}
+
+// W2 rule 6: a config attempt onto the same build reaches step 8 and hands
+// over the same way, so the new set runs the new generation's environment:
+// each worker's launch file carries the value the config attempt's web
+// launched with. Through the real ExecBackend over fakeControl.
+func TestConfigAttemptHandsOverWorkers(t *testing.T) {
+ procs := workerProcs("jobs")
+ f, lb, ctl, at := rootfsWorkerFixture(t, workerProcs(), procs)
+ writeInstanceEnv(t, lb.eb, lb.rt, "SHOP_MODE=one\n")
+ res := f.a.Swap(context.Background(), at, f.newest)
+ if res.Outcome != SwapDone {
+ t.Fatalf("v1 to v2 = %+v; calls:\n%s", res, ctl.joined())
+ }
+ tickWorkers(t, f.a, f.host)
+ jobsMode := func() string {
+ l := readLaunchNamed(t, lb.eb, lb.rt, instancectl.WorkerLaunchFileName("jobs"))
+ return envMap(t, l.Env)["SHOP_MODE"]
+ }
+ if m := jobsMode(); m != "one" {
+ t.Fatalf("jobs launched with SHOP_MODE=%q, want one", m)
+ }
+ before := len(ctl.callList())
+
+ writeInstanceEnv(t, lb.eb, lb.rt, "SHOP_MODE=two\n")
+ f.rev.Add(1)
+ config := f.attempt(ModeOverlap)
+ config.StagedPath, config.Digest = at.StagedPath, at.Digest
+ config.Cause, config.ConfigRev = CauseConfig, "cfg-2"
+ res2 := f.a.Swap(context.Background(), config, f.newest)
+ if res2.Outcome != SwapDone || res2.Gen.Build != "v2" || res2.Gen.N == res.Gen.N {
+ t.Fatalf("the config attempt = %+v (first %+v); calls:\n%s", res2, res, ctl.joined())
+ }
+ if got, want := registered(f.a, f.host), []string{fmt.Sprintf("jobs gen%d pending", res2.Gen.N)}; !slices.Equal(got, want) {
+ t.Fatalf("registered %v after the config swap, want %v", got, want)
+ }
+ tickWorkers(t, f.a, f.host)
+ calls := ctl.callList()[before:]
+ stopAt := slices.IndexFunc(calls, func(c string) bool {
+ return strings.HasPrefix(c, "stop-rootfs "+lb.rt.Host+" role=worker gen=0 worker=jobs kill=false")
+ })
+ startAt := slices.IndexFunc(calls, func(c string) bool { return strings.HasPrefix(c, "start-rootfs-worker "+lb.rt.Host+" jobs ") })
+ if stopAt < 0 || startAt < stopAt {
+ t.Fatalf("the old jobs' stop (%d) and the new one's start (%d): want the stop first; calls:\n%s", stopAt, startAt, strings.Join(calls, "\n"))
+ }
+ if m := jobsMode(); m != "two" {
+ t.Fatalf("after the config attempt jobs launched with SHOP_MODE=%q, want two (the new generation's)", m)
+ }
+}
+
+// The one registration path never drops a handle: a worker still holding
+// one where a set is registered (none should be left by then) becomes a
+// stray, re-proven at once, and the registered worker starts only after
+// that proof. Otherwise its handle would be lost and a second worker of
+// the name would start beside it.
+func TestRegistrationNeverDropsAHandle(t *testing.T) {
+ r := newWorkerRig(t, workerHost(), "jobs")
+ e := r.wake(t)
+ old := r.b.lastWorker(t, "jobs")
+ g := r.gen()
+ r.a.registerRootfsWorkers(e, r.rt, g, func() bool { return true })
+ if s := r.strays(); !slices.Equal(s, []string{"jobs"}) {
+ t.Fatalf("strays %v after registering over a live handle, want jobs", s)
+ }
+ from := len(r.b.events())
+ for i := 0; r.b.count(fmt.Sprintf("start jobs gen%d", g.N)) < 2; i++ {
+ if i == 5 {
+ t.Fatalf("the registered jobs never started; order %v", r.b.events())
+ }
+ r.clk.advance(sidecarRestartBase)
+ r.tick(t)
+ }
+ ev := r.b.events()
+ start := index(ev, fmt.Sprintf("start jobs gen%d", g.N), from)
+ if p := index(ev, "proven jobs", from); p < 0 || p > start {
+ t.Fatalf("the new jobs started (%d) before the old handle's proof (%d); order %v", start, p, ev[from:])
+ }
+ if !old.Exited() || r.b.alive() != 1 {
+ t.Fatalf("the old handle exited %v, %d alive; want it gone and one jobs", old.Exited(), r.b.alive())
+ }
+}
diff --git a/internal/activator/rootfs_install_guard_test.go b/internal/activator/rootfs_install_guard_test.go
index bcaf75598..154862d50 100644
--- a/internal/activator/rootfs_install_guard_test.go
+++ b/internal/activator/rootfs_install_guard_test.go
@@ -471,3 +471,36 @@ func TestRootfsWorkerNeverStartsInsideDoWake(t *testing.T) {
})
}
}
+
+// Paul's ruling, as the W2 addendum applies it: nothing an overlap swap
+// reaches launches or installs a worker, its step 8 handover included
+// (it stops the old set and only registers the new one; the tick starts
+// it). The walk is from swapOverlap, the whole overlap, over the same
+// graph and forbidden list as doWake's guard (interfaces resolved,
+// StartRootfsWorker named). Its controls: the walk reaches the handover,
+// its stop and its registration, so a walk that resolves nothing cannot
+// pass.
+func TestRootfsWorkerNeverStartsInsideTheSwapHandover(t *testing.T) {
+ pkg, err := loadVerbGuardPackage()
+ if err != nil {
+ t.Fatal(err)
+ }
+ g, byName := funcGraph(pkg, false)
+ for _, root := range []string{"swapOverlap", "handOverRootfsWorkers"} {
+ t.Run(root, func(t *testing.T) {
+ fn := byName["(*github.com/carlosframework/platform/internal/activator.Service)."+root]
+ if fn == nil {
+ t.Fatalf("%s not resolved: the guard proves nothing", root)
+ }
+ from := reachable(g, fn)
+ for _, want := range []string{"handOverRootfsWorkers", "stopRootfsWorkersWhere", "proveWorkerGone", "registerRootfsWorkers"} {
+ if reachedNamed(from, want) == nil {
+ t.Fatalf("%s does not reach %s: the walk resolves nothing", root, want)
+ }
+ }
+ for _, v := range wakeStartViolations(g, fn) {
+ t.Errorf("%s reaches a worker start, %s", root, v)
+ }
+ })
+ }
+}
diff --git a/internal/activator/rootfs_processes_test.go b/internal/activator/rootfs_processes_test.go
index 4be738475..fc4a66657 100644
--- a/internal/activator/rootfs_processes_test.go
+++ b/internal/activator/rootfs_processes_test.go
@@ -11,6 +11,7 @@ import (
"encoding/hex"
"encoding/json"
"errors"
+ "fmt"
"log"
"maps"
"os"
@@ -19,6 +20,7 @@ import (
"sync"
"testing"
+ "github.com/carlosframework/platform/internal/instancectl"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
)
@@ -298,9 +300,10 @@ func onlyWebAsked(t *testing.T, ctl *stagedRootfsCtl) {
}
}
-// D8, as Group R leaves it: the workers a build declares are logged and
-// not run; its release process is run by every wake and swap site (R1 to
-// R3), so the hook no longer logs it [pf R1.17]. Here the release is the
+// D8, as Groups R and W leave it: the workers a build declares are run
+// (W1 at a wake, W2 at an overlap swap's handover; the tick starts both)
+// and D8's workers line is gone; its release process is run by every wake
+// and swap site (R1 to R3), so no line names it either [pf R1.17, W2.5]. Here the release is the
// row's good build's, not due, so nothing of it runs either. Not
// parallel: it captures the standard logger.
func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
@@ -370,26 +373,65 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
})
t.Run("swap", func(t *testing.T) {
logs := captureLogLines(t)
- f, lb, ctl, at := rootfsSwapFixture(t, ModeOverlap)
- // v2's manifest, the image the attempt names, declares jobs and
- // release for this box; v2 is the row's good build, so its release
- // is not due.
- writeDeclaredManifest(t, lb.eb, "v2", at.Digest, declaredProcs(), nil)
- f.a.mu.Lock()
- f.a.entries[f.host].route.GoodVersion, f.a.entries[f.host].route.GoodDigest = "v2", at.Digest
- f.a.mu.Unlock()
- ctl.setServe(serveVersions(t, lb.eb, lb.rt, 0, "v2"))
+ // Group W (W2, with Paul's ruling): the incumbent (a staged
+ // rootfs v1) runs jobs; v2, the attempt's build, declares jobs
+ // and release, and is the row's good build, so its release is not
+ // due. Step 8 stops and proves v1's jobs before it registers
+ // v2's, launches nothing, and the next tick starts v2's jobs.
+ f, lb, ctl, at := rootfsWorkerFixture(t, declaredProcs(), declaredProcs())
+ g1 := f.incumbent.N
+ var regMu sync.Mutex
+ var atStop []string
+ ctl.fakeControl.stopHook = func(_ string, role instancectl.Role) {
+ if role == instancectl.RoleWorker {
+ reg := registered(f.a, f.host)
+ regMu.Lock()
+ atStop = append(atStop, reg...)
+ regMu.Unlock()
+ }
+ }
+ before := len(ctl.callList())
res := f.a.Swap(context.Background(), at, f.newest)
if res.Outcome != SwapDone {
t.Fatalf("Swap = %+v, want done; calls:\n%s", res, ctl.joined())
}
onlyStart(t, ctl, release.StagedIdentity{Version: "v2", StagedPath: at.StagedPath, Digest: at.Digest})
- onlyWebAsked(t, ctl)
if g, _ := f.a.genStateForTest(f.host); g.Build != "v2" {
t.Fatalf("serving %+v, want v2", g)
}
- if n := logs.count(workersLine(f.host, "v2", "jobs")); n != 1 {
- t.Errorf("the workers line was logged %d times, want once; logs:\n%s", n, logs)
+ calls := ctl.callList()[before:]
+ if slices.ContainsFunc(calls, func(c string) bool { return strings.HasPrefix(c, "start-rootfs-worker ") }) {
+ t.Fatalf("the swap launched a worker; the tick alone starts them; calls:\n%s", strings.Join(calls, "\n"))
+ }
+ if !slices.Contains(calls, "stop-rootfs "+lb.rt.Host+" role=worker gen=0 worker=jobs kill=false") {
+ t.Fatalf("v1's jobs was not stopped; calls:\n%s", strings.Join(calls, "\n"))
+ }
+ regMu.Lock()
+ stopSaw := slices.Clone(atStop)
+ regMu.Unlock()
+ // Root is asked twice per proof (the stop, then the handle's own
+ // listener close); each time only v1's jobs is registered.
+ want := fmt.Sprintf("jobs gen%d started", g1)
+ if len(stopSaw) == 0 || slices.ContainsFunc(stopSaw, func(r string) bool { return r != want }) {
+ t.Errorf("at v1's jobs' stop the entry had %v registered, want %q alone: the new set registered before the old was proven", stopSaw, want)
+ }
+ if got, want := registered(f.a, f.host), []string{fmt.Sprintf("jobs gen%d pending", res.Gen.N)}; !slices.Equal(got, want) {
+ t.Fatalf("registered %v after the swap, want %v", got, want)
+ }
+ if s := strayNames(f.a, f.host); len(s) != 0 {
+ t.Fatalf("strays %v: v1's jobs was not proven", s)
+ }
+ tickWorkers(t, f.a, f.host)
+ calls = ctl.callList()[before:]
+ if !slices.ContainsFunc(calls, func(c string) bool {
+ return strings.HasPrefix(c, "start-rootfs-worker "+lb.rt.Host+" jobs ") && strings.HasSuffix(c, "process=jobs version=v2")
+ }) {
+ t.Fatalf("the tick did not start v2's jobs; calls:\n%s", strings.Join(calls, "\n"))
+ }
+ noBinaryStart(t, ctl)
+ noCallStarts(t, ctl.fakeControl, "cmd-rootfs")
+ if n := logs.count(workersLine(f.host, "v2", "jobs")) + logs.matching(f.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, f.host)
})
@@ -471,19 +513,26 @@ func TestProcessesThroughTheProductionBackend(t *testing.T) {
t.Errorf("a unit-backed row: %v, want errNoRootfsControl", err)
}
- // The hook reads through the same seam.
+ // The workers' registration (a wake's or a swap's handover) reads
+ // through the same seam. An entry that is not the host's registers
+ // nothing, so only the read and its diagnostics run. A readable
+ // declaration logs no line (D8's workers line is gone).
g := Gen{N: 3, Build: id.Version, StagedPath: id.StagedPath, Digest: id.Digest}
- a.rootfsProcessesHook(context.Background(), nil, rt, g)
- if n := logs.count(workersLine(rt.Host, "v2", "jobs")); n != 1 {
- t.Errorf("the workers line through the production backend: %d, want 1; logs:\n%s", n, logs)
+ declare := func(rt registry.Route, g Gen) {
+ a.registerRootfsWorkers(&actEntry{host: rt.Host}, rt, g, func() bool { return true })
+ }
+ quiet := logs.matching(rt.Host)
+ declare(rt, g)
+ if n := logs.count(workersLine(rt.Host, "v2", "jobs")) + logs.matching(rt.Host) - quiet; n != 0 {
+ t.Errorf("a readable declaration through the production backend logged %d lines; logs:\n%s", n, logs)
}
noReleaseLine(t, logs, rt.Host)
- a.rootfsProcessesHook(context.Background(), nil, unit, g)
+ declare(unit, g)
if n := logs.matching("activator: "+rt.Host+": build v2", "declared processes", "rootfs"); n != 1 {
t.Errorf("a unit-backed row's refused read: %d lines, want 1; logs:\n%s", n, logs)
}
// A partial generation is refused before any read, and logs once.
- a.rootfsProcessesHook(context.Background(), nil, rt, Gen{N: 4, Build: "v2"})
+ declare(rt, Gen{N: 4, Build: "v2"})
if n := logs.matching("activator: "+rt.Host+": build v2", "declared processes", "names no staged image"); n != 1 {
t.Errorf("a partial generation's refused read: %d lines, want 1; logs:\n%s", n, logs)
}
@@ -491,7 +540,7 @@ func TestProcessesThroughTheProductionBackend(t *testing.T) {
bin := rt
bin.Runtime = ""
before := logs.matching(rt.Host)
- a.rootfsProcessesHook(context.Background(), nil, bin, g)
+ declare(bin, g)
if n := logs.matching(rt.Host); n != before {
t.Errorf("a binary row logged; logs:\n%s", logs)
}
diff --git a/internal/activator/rootfsworkers.go b/internal/activator/rootfsworkers.go
index 562585be4..a7afb1fe6 100644
--- a/internal/activator/rootfsworkers.go
+++ b/internal/activator/rootfsworkers.go
@@ -158,7 +158,7 @@ func (a *Service) workerHeadroom(rep Rep) error {
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).
+// longer the entry's current one (a swap's handover stops it instead).
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
@@ -206,54 +206,107 @@ func workerNames(procs map[string]release.Process) ([]string, error) {
}
// declareRootfsWorkers is doWake's last step (spec §5.4; Paul's ruling, W1
-// round 2): it starts nothing. It reads the workers the wake's generation
-// declares (the generation wake installs as e.gen, never the live link)
-// and registers each as pending, so the resident tick's first pass after
-// the entry is awake, under its lease watch, starts it through workerGate.
-// A declaration that cannot be read or is not valid registers none and
-// logs once; web serves. The caller does not hold a.mu: the read is file
-// I/O.
+// round 2): it starts nothing. It registers the workers the wake's
+// generation declares (the generation wake installs as e.gen, never the
+// live link) as pending, while the entry is still waking, so the resident
+// tick's first pass after the entry is awake, under its lease watch,
+// starts them through workerGate. The caller does not hold a.mu.
func (a *Service) declareRootfsWorkers(e *actEntry, rt registry.Route, w *wokenInstance) {
+ a.registerRootfsWorkers(e, rt, w.gen, func() bool { return e.state == actWaking })
+}
+
+// registerRootfsWorkers is the one place a generation's declared workers
+// are registered (doWake's last step, and an overlap swap's handover): it
+// reads the workers g declares and, under a.mu, registers each as pending
+// on e while e is still the host's and still() holds. It starts nothing:
+// the tick's first pass starts each through workerGate. A declaration that
+// cannot be read or is not valid registers none and logs once; web serves.
+// A worker of the same name still holding a handle or a start (none
+// should be left by then) becomes a stray, due at once, so its handle is
+// never lost and the stray rule keeps the new set from starting beside it.
+// The caller does not hold a.mu: the read is file I/O.
+func (a *Service) registerRootfsWorkers(e *actEntry, rt registry.Route, g Gen, still func() bool) {
if !rt.Rootfs() || e.worker {
return
}
- procs, err := a.declaredProcesses(rt, w.gen)
+ procs, err := a.declaredProcesses(rt, g)
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)
+ log.Printf("activator: %s: build %s: its declared processes cannot be read, so this box runs web alone: %v", rt.Host, g.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)
+ log.Printf("activator: %s: build %s: its declared processes are not valid, so this box runs no worker of it: %v", rt.Host, g.Build, err)
return
}
if len(names) == 0 {
return
}
if _, ok := a.backend.(RootfsWorkerBackend); !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, ", "))
+ log.Printf("activator: %s: build %s declares workers (%s); this backend cannot run them, so web runs alone", rt.Host, g.Build, strings.Join(names, ", "))
return
}
- build, err := stagedIdentityOf(w.gen)
+ build, err := stagedIdentityOf(g)
if err != nil {
- log.Printf("activator: %s: build %s: no worker registered: %v", rt.Host, w.gen.Build, err)
+ log.Printf("activator: %s: build %s: no worker registered: %v", rt.Host, g.Build, err)
return
}
a.mu.Lock()
defer a.mu.Unlock()
- if a.entries[e.host] != e || e.state != actWaking {
+ if a.entries[e.host] != e || !still() {
return
}
if e.rootfsWorkers == nil {
e.rootfsWorkers = map[string]*rootfsWorker{}
}
for _, name := range names {
- e.rootfsWorkers[name] = &rootfsWorker{name: name, gen: w.gen.N, build: build, pending: true}
+ if old := e.rootfsWorkers[name]; old != nil && (old.starting || old.proc != nil) {
+ old.strayAt, old.unproven = time.Time{}, old.proc
+ if !slices.Contains(e.strayRootfsWorkers, old) {
+ e.strayRootfsWorkers = append(e.strayRootfsWorkers, old)
+ }
+ }
+ e.rootfsWorkers[name] = &rootfsWorker{name: name, gen: g.N, build: build, pending: true}
}
}
-// workerGate is every worker start's gate (a first start, a restart; W2's
-// handover), asked
+// handOverRootfsWorkers is an overlap swap's step 8 for a rootfs row (spec
+// §5.2, §5.4; W2, under Paul's ruling that only the tick starts a worker):
+// with the new web serving and the retiring generation dropped, every
+// worker of the entry not of the switched generation (and every stray of
+// one) is stopped and proven gone through stopRootfsWorkers's parallel
+// stop and proof, a starting one once its start has ended. Only then is
+// the switched generation's set read and registered as pending
+// (registerRootfsWorkers, as doWake registers a woken one). It launches
+// nothing: the tick starts the new set through workerGate, whose stray
+// rule refuses each of its starts while an old worker is a stray, so two
+// generations' workers never run at once. A config or restart attempt
+// onto the same build hands over the same way, so the new set runs the
+// new generation's environment. An entry no longer awake is the stop
+// path's: it stops every worker itself. Never call it with a.mu held.
+func (a *Service) handOverRootfsWorkers(e *actEntry) {
+ a.mu.Lock()
+ if a.entries[e.host] != e || !e.route.Rootfs() || e.worker || e.state != actAwake {
+ a.mu.Unlock()
+ return
+ }
+ g, rt := e.gen, e.route
+ retiring := func(gen uint64) bool { return gen != g.N }
+ old := len(workerNamesWhereLocked(e, retiring)) > 0
+ a.mu.Unlock()
+ if old {
+ if !a.stopRootfsWorkersWhere(e, retiring) {
+ log.Printf("activator: %s: a worker of an earlier generation is not proven stopped; generation %d's workers start once it is", rt.Host, g.N)
+ }
+ // The proven old workers' pins go; a stray's stay until it is
+ // proven.
+ _ = a.persistGenerations()
+ }
+ a.registerRootfsWorkers(e, rt, g, func() bool { return e.state == actAwake && e.gen.N == g.N })
+}
+
+// workerGate is every worker start's gate (a first start, including a
+// handed-over set's, or a restart; all from the tick), 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
@@ -492,6 +545,12 @@ func (a *Service) superviseRootfsLocked(e *actEntry) {
if wk.starting || e.workerProofs[name] != nil {
continue
}
+ if wk.gen != e.gen.N {
+ // Retiring: a swap switched past its generation, and the
+ // swap's handover stops and proves it. Its exit is not noted
+ // and it is not restarted.
+ continue
+ }
if wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc) {
continue // running
}
@@ -614,8 +673,8 @@ func (a *Service) restartRootfsWorkerLocked(e *actEntry, wk *rootfsWorker) {
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.
+ // The entry's generation moved on (a swap; its handover stops
+ // this worker): not a crash, asked again after the backoff.
wk.retryAt = a.now().Add(max(wk.backoff, sidecarRestartBase))
return
}
@@ -772,17 +831,23 @@ func (a *Service) proveWorkerNames(e *actEntry, names []string) {
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 {
+ // An awake entry's worker of its current generation is the
+ // not-yet-restarted replacement of a stray (proc unset): the
+ // supervisor starts it. A retiring one is forgotten.
+ if wk := e.rootfsWorkers[n]; wk != nil && !wk.starting && workerRetiringLocked(e, wk) {
delete(e.rootfsWorkers, n)
}
a.dropProvenStraysLocked(e, n)
} else {
- if wk := e.rootfsWorkers[n]; wk != nil && !wk.starting && e.state != actAwake {
+ if wk := e.rootfsWorkers[n]; wk != nil && !wk.starting && workerRetiringLocked(e, wk) {
delete(e.rootfsWorkers, n)
- wk.strayAt, wk.unproven = now, wk.proc
- e.strayRootfsWorkers = append(e.strayRootfsWorkers, wk)
+ // On an awake entry (a handover), a retiring worker with no
+ // handle ran nothing of its own: the strays of its name
+ // carry the proof, and no stray is added for it.
+ if e.state != actAwake || wk.proc != nil {
+ wk.strayAt, wk.unproven = now, wk.proc
+ e.strayRootfsWorkers = append(e.strayRootfsWorkers, wk)
+ }
}
for _, s := range e.strayRootfsWorkers {
if s.name == n {
@@ -810,6 +875,19 @@ func workerNamesLocked(e *actEntry) []string {
return names
}
+// workerNamesWhereLocked is every name whose worker, or a stray of it,
+// runs a generation pick chooses, sorted. The caller holds a.mu.
+func workerNamesWhereLocked(e *actEntry, pick func(gen uint64) bool) []string {
+ var names []string
+ for _, n := range workerNamesLocked(e) {
+ if wk := e.rootfsWorkers[n]; (wk != nil && pick(wk.gen)) ||
+ slices.ContainsFunc(e.strayRootfsWorkers, func(s *rootfsWorker) bool { return s.name == n && pick(s.gen) }) {
+ names = append(names, n)
+ }
+ }
+ return names
+}
+
// stopRootfsWorkers is a stop's first step [pf W1.8, W1.9]: every worker
// of the entry (and every stray) is stopped and proven gone, in parallel,
// a starting one once its start has ended; an unproven one is a
@@ -817,6 +895,15 @@ func workerNamesLocked(e *actEntry) []string {
// 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 {
+ return a.stopRootfsWorkersWhere(e, func(uint64) bool { return true })
+}
+
+// stopRootfsWorkersWhere is stopRootfsWorkers over the names whose worker,
+// or a stray of it, runs a generation pick chooses: every name for a stop;
+// every generation but the switched one for a swap's handover. It reports
+// whether no worker or stray of a chosen generation is left. Never call it
+// with a.mu held.
+func (a *Service) stopRootfsWorkersWhere(e *actEntry, pick func(gen uint64) bool) bool {
// Every worker not starting is stopped and proven at once, in
// parallel; a worker whose start is in flight is proven once that
// start has ended (by then what it started is installed, proven or a
@@ -830,7 +917,7 @@ func (a *Service) stopRootfsWorkers(e *actEntry) bool {
a.dropUnlaunchedLocked(e)
var waits []chan struct{}
var starting, now []string
- for _, n := range workerNamesLocked(e) {
+ for _, n := range workerNamesWhereLocked(e, pick) {
if wk := e.rootfsWorkers[n]; wk != nil && wk.starting {
waits = append(waits, wk.startDone)
starting = append(starting, n)
@@ -852,7 +939,7 @@ func (a *Service) stopRootfsWorkers(e *actEntry) bool {
a.mu.Lock()
// A start that ended having run nothing leaves nothing to prove.
a.dropUnlaunchedLocked(e)
- known := workerNamesLocked(e)
+ known := workerNamesWhereLocked(e, pick)
starting = slices.DeleteFunc(starting, func(n string) bool { return !slices.Contains(known, n) })
later, busyLater := claimWorkerNamesLocked(e, starting)
a.mu.Unlock()
@@ -863,27 +950,32 @@ func (a *Service) stopRootfsWorkers(e *actEntry) bool {
}
a.mu.Lock()
defer a.mu.Unlock()
- return len(e.rootfsWorkers) == 0 && len(e.strayRootfsWorkers) == 0
+ return len(workerNamesWhereLocked(e, pick)) == 0
}
-// dropUnlaunchedLocked forgets, on an entry no longer awake, every worker
+// dropUnlaunchedLocked forgets every retiring worker (workerRetiringLocked)
// that cannot be running: no start in flight, no handle and no stray of
// its name. That is a pending declaration never started (Astra W1 r3), a
// start refused before root or one that ran nothing, or a start already
// proven gone. Every launch that may have run is a handle or a stray, so
// it keeps its proof. It asks root nothing. The caller holds a.mu.
func (a *Service) dropUnlaunchedLocked(e *actEntry) {
- if e.state == actAwake {
- return
- }
for n, wk := range e.rootfsWorkers {
- if wk.starting || wk.proc != nil || slices.ContainsFunc(e.strayRootfsWorkers, func(s *rootfsWorker) bool { return s.name == n }) {
+ if !workerRetiringLocked(e, wk) || wk.starting || wk.proc != nil || slices.ContainsFunc(e.strayRootfsWorkers, func(s *rootfsWorker) bool { return s.name == n }) {
continue
}
delete(e.rootfsWorkers, n)
}
}
+// workerRetiringLocked reports whether wk is on its way out: its entry is
+// no longer awake (a stop), or it runs a generation other than the
+// entry's current one (a swap switched past it, and the handover stops
+// it). The caller holds a.mu.
+func workerRetiringLocked(e *actEntry, wk *rootfsWorker) bool {
+ return e.state != actAwake || wk.gen != e.gen.N
+}
+
// 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
diff --git a/internal/activator/swap.go b/internal/activator/swap.go
index 7bd05aec5..239bcf581 100644
--- a/internal/activator/swap.go
+++ b/internal/activator/swap.go
@@ -749,9 +749,11 @@ func (a *Service) swapOverlap(ctx context.Context, gb SwapBackend, at Attempt, n
res.Reason = "retiring generation not yet proven stopped; the sweep finishes it"
}
// Step 8: a legacy co-spawned sidecar moves onto the new generation,
- // and a rootfs build's declared processes beside web are logged, never
- // started (Plan 3 Task D, D8). W2 hands the workers over here.
+ // and a rootfs row's workers are handed over (Group W, W2): the
+ // retiring generation's are stopped and proven gone, then the new
+ // generation's are registered for the tick to start. Nothing here
+ // launches a worker.
a.replaceSidecar(e)
- a.rootfsProcessesHook(ctx, e, rt, m.gen)
+ a.handOverRootfsWorkers(e)
return res
}