carlos / platform Public

activator: no rootfs worker starts inside doWake; the tick starts them under the lease watch (W1 fix round 2)

Astra's W1 round 2 found the C7 finding only partly resolved: wake-time
workers ran while the entry was still waking, before the resident lease
watch started. Stopping rule 2 applied, and Paul chose the cut: no worker
starts inside doWake.

doWake's step 7 now only registers each declared worker as pending
(declareRootfsWorkers), reading the wake's generation, never the live
link. A refused or too-large declaration registers none, logs once, and
web serves. The tick's first pass on the awake entry starts every pending
worker through workerGate, with no backoff and no crash counted: the 82 s
headroom, the stray rule, the release record, and the install's
lease-watch condition. The install point no longer accepts a waking
entry. workerWakeGate and the wake-time start are gone. A pending worker
reports as restarting. Cost, as Paul accepted: workers start up to about
2 s after web is healthy.

TestRootfsWorkerNeverStartsInsideDoWake walks the package's static call
graph from doWake and fails if any worker start or install is reachable.
The deadline regression is now deterministic: the headroom is read on
Service.leaseNow, a frozen clock the test moves. The stop and the start's
answer are synchronised on channels. The check is the C7 inequality on
production bounds.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev a8ea6162bfb46cab1bcce1a93175ee865512e6bd parent 3576d00
6 files changed, +519 −337
  • internal/activator/activator.go +15 −9
  • internal/activator/backend_rootfs.go +3 −3
  • internal/activator/rootfs_install_guard_test.go +96 −0
  • internal/activator/rootfs_processes_test.go +25 −4
  • internal/activator/rootfsworkers.go +81 −95
  • internal/activator/rootfsworkers_test.go +299 −226
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 3e43f1b60..bfedb62c8 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -835,10 +835,10 @@ type actEntry struct {
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
+ // registered by doWake (declareRootfsWorkers), started and 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
@@ -1243,6 +1243,11 @@ type Service struct {
now func() time.Time // a seam for the unit tests' clock
liveVer func(string) (string, error) // live/<host> symlink target; a seam for tests
+ // leaseNow is the clock a worker start's headroom is read against the
+ // lease's safety deadline on (workerHeadroom): nil is the real clock,
+ // as the lease runs. A seam for the unit tests, set before any start.
+ leaseNow func() time.Time
+
// Routes, when non-nil, is read by doWake before Acquire (design §6.8)
// to refresh the route against the registry's committed row rather than
// spawning against the copy the edge cached at request time. Nil (every
@@ -3031,11 +3036,12 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro
w.steps.mark(a.now(), "sidecar")
}
// 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)
+ // §5.4), once web is started, healthy and replicating: registered,
+ // never started here. The resident tick starts them once wake() has
+ // installed the entry awake under its lease watch (Paul's ruling, W1
+ // round 2). This stays the last step of doWake and doWake returns nil
+ // after it: a worker is never a failure of this wake.
+ a.declareRootfsWorkers(e, rt, w)
return w, nil
}
diff --git a/internal/activator/backend_rootfs.go b/internal/activator/backend_rootfs.go
index 82a28b53e..6720b99b2 100644
--- a/internal/activator/backend_rootfs.go
+++ b/internal/activator/backend_rootfs.go
@@ -86,9 +86,9 @@ func (b *ExecBackend) Processes(rt registry.Route, id release.StagedIdentity) (m
// 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
+// 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
diff --git a/internal/activator/rootfs_install_guard_test.go b/internal/activator/rootfs_install_guard_test.go
index 911f44678..f43fc13bb 100644
--- a/internal/activator/rootfs_install_guard_test.go
+++ b/internal/activator/rootfs_install_guard_test.go
@@ -272,3 +272,99 @@ func TestResidentProcessInstallsGoThroughOnePlace(t *testing.T) {
})
}
}
+
+// workerStartFuncs is every function through which a rootfs worker is
+// started or installed: none may be reachable from doWake (Paul's ruling,
+// W1 round 2: no worker starts inside doWake; the tick starts them).
+var workerStartFuncs = []string{"superviseRootfsLocked", "restartRootfsWorkerLocked", "runWorkerStart",
+ "installRootfsWorkerLocked", "LaunchRootfsWorker", "rootfsTick"}
+
+// funcGraph is the package's static reference graph: for each function or
+// method declared in a non-test file, every package function or method
+// (an interface's included, by its abstract method) its body names, called
+// or not, function literals and goroutines included. It over-approximates
+// what a call may reach, never under.
+func funcGraph(pkg *packages.Package) (edges map[*types.Func][]*types.Func, byName map[string]*types.Func) {
+ edges, byName = map[*types.Func][]*types.Func{}, map[string]*types.Func{}
+ for base, f := range packageFiles(pkg) {
+ if strings.HasPrefix(base, verbGuardFixturePrefix) || strings.HasSuffix(base, "_test.go") {
+ continue
+ }
+ for _, d := range f.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ fn, ok := pkg.TypesInfo.Defs[fd.Name].(*types.Func)
+ if !ok {
+ continue
+ }
+ byName[fn.FullName()] = fn
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ if id, ok := n.(*ast.Ident); ok {
+ if callee, ok := pkg.TypesInfo.Uses[id].(*types.Func); ok && callee.Pkg() == pkg.Types {
+ edges[fn] = append(edges[fn], callee)
+ }
+ }
+ return true
+ })
+ }
+ }
+ return edges, byName
+}
+
+// reachable is every function reachable from root in g, each with the
+// path that first reached it.
+func reachable(g map[*types.Func][]*types.Func, root *types.Func) map[*types.Func][]string {
+ seen := map[*types.Func][]string{root: {root.Name()}}
+ queue := []*types.Func{root}
+ for len(queue) > 0 {
+ fn := queue[0]
+ queue = queue[1:]
+ for _, c := range g[fn] {
+ if _, ok := seen[c]; ok {
+ continue
+ }
+ seen[c] = append(slices.Clone(seen[fn]), c.Name())
+ queue = append(queue, c)
+ }
+ }
+ return seen
+}
+
+// Paul's ruling (W1 round 2): nothing doWake reaches starts or installs a
+// worker. Its controls: the walk reaches doWake's own worker step
+// (declareRootfsWorkers), and from the resident tick it does reach a
+// worker start, so a guard that resolved nothing cannot pass.
+func TestRootfsWorkerNeverStartsInsideDoWake(t *testing.T) {
+ pkg, err := loadVerbGuardPackage()
+ if err != nil {
+ t.Fatal(err)
+ }
+ g, byName := funcGraph(pkg)
+ root := byName["(*github.com/carlosframework/platform/internal/activator.Service).doWake"]
+ tick := byName["(*github.com/carlosframework/platform/internal/activator.Service).rootfsTick"]
+ if root == nil || tick == nil {
+ t.Fatal("doWake or rootfsTick not resolved: the guard proves nothing")
+ }
+ fromWake := reachable(g, root)
+ named := func(m map[*types.Func][]string, name string) []string {
+ for fn, path := range m {
+ if fn.Name() == name {
+ return path
+ }
+ }
+ return nil
+ }
+ if named(fromWake, "declareRootfsWorkers") == nil {
+ t.Fatal("doWake does not reach declareRootfsWorkers: the walk resolves nothing")
+ }
+ if named(reachable(g, tick), "runWorkerStart") == nil {
+ t.Fatal("the tick does not reach runWorkerStart: the walk resolves nothing")
+ }
+ for _, name := range workerStartFuncs {
+ if path := named(fromWake, name); path != nil {
+ t.Errorf("doWake reaches %s, a worker start: %s", name, strings.Join(path, " -> "))
+ }
+ }
+}
diff --git a/internal/activator/rootfs_processes_test.go b/internal/activator/rootfs_processes_test.go
index 6dce1fc8b..4be738475 100644
--- a/internal/activator/rootfs_processes_test.go
+++ b/internal/activator/rootfs_processes_test.go
@@ -321,10 +321,28 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
done()
evs.wait(t, GenHealthy)
onlyStart(t, ctl, next)
- // 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.
+ // Group W (W1.12; Paul's ruling, W1 round 2): the wake starts no
+ // worker; the tick's first pass on the awake entry starts the
+ // declared workers, through root's worker start, and D8's workers
+ // line is no longer logged. No command, no binary start, and
+ // root's images are web's, then the two workers' (in either
+ // order: the tick starts them side by side).
+ noCallStarts(t, ctl.fakeControl, "start-rootfs-worker")
+ a.rootfsTick()
+ waitFor(t, "the tick's worker starts", func() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[rt.Host]
+ if e == nil {
+ return false
+ }
+ for _, wk := range e.rootfsWorkers {
+ if wk.starting || wk.proc == nil {
+ return false
+ }
+ }
+ return len(e.rootfsWorkers) == 2
+ })
noBinaryStart(t, ctl)
noCallStarts(t, ctl.fakeControl, "cmd-rootfs")
for _, w := range []string{"jobs", "mailer"} {
@@ -336,6 +354,9 @@ func TestDeclaredProcessesAreLoggedNotRun(t *testing.T) {
procs = append(procs, img.Process)
}
ctl.fakeControl.mu.Unlock()
+ if len(procs) > 1 {
+ slices.Sort(procs[1:]) // the tick starts the workers side by side
+ }
if want := []string{release.ProcessWeb, "jobs", "mailer"}; !slices.Equal(procs, want) {
t.Errorf("root's images ran %v, want %v", procs, want)
}
diff --git a/internal/activator/rootfsworkers.go b/internal/activator/rootfsworkers.go
index c58228308..3a7599377 100644
--- a/internal/activator/rootfsworkers.go
+++ b/internal/activator/rootfsworkers.go
@@ -1,8 +1,10 @@
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,
+// instance's workers (spec §5.4). The workers a build declares are
+// registered by doWake's last step and started by the resident tick once
+// the entry is awake under its lease watch (Paul's ruling, W1 round 2: no
+// worker starts inside doWake), run beside web 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
@@ -15,10 +17,11 @@ package activator
// 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.
+// start (a first start or a restart, both from the tick) holds starting
+// and startDone, and a stop or a stray's re-proof holds the name's claim
+// (workerProofs). A stop proves a starting name once its start has ended;
+// the lease-loss stop and the stray re-proof skip a name that is starting,
+// whose own cleanup proves what it started.
import (
"context"
@@ -74,6 +77,10 @@ type rootfsWorker struct {
// strayAt is when a stray's stop was last tried: the sweep re-tries it
// at most every actStopTimeout.
strayAt time.Time
+ // pending: declared by the wake and never started on this entry. The
+ // tick's first pass starts it, with no backoff and no crash counted
+ // (Paul's ruling, W1 round 2).
+ pending bool
// 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
@@ -101,9 +108,9 @@ const (
// The termination proof is RootfsWorkerGone's, on its own bounds.
const workerListenerWait = 2 * time.Second
-// workerStartBound bounds one worker start (doWake's or a restart's), from
-// its preparation to root's answer: one control request. A var so tests
-// shrink it.
+// workerStartBound bounds one worker start (a first start or a restart),
+// from its preparation to root's answer: one control request. A var so
+// tests shrink it.
var workerStartBound = instancectl.DeadlineControl
// workerProofBound is how long a worker's stop takes to be proven at most:
@@ -123,18 +130,23 @@ func workerStartLead() time.Duration { return workerStartBound + workerProofBoun
// stopped and proven before the lease's safety deadline.
var errWorkerNoHeadroom = errors.New("activator: the instance's lease is too close to its safety deadline to start a worker")
-// workerHeadroom is the gates' lease deadline check, read as runRelease
-// reads it (watchOf, SafeUntil, on the real clock as the lease runs): nil
-// when rep's safety deadline is more than workerStartLead away, or when rep
-// has no lease signal (the tick's rep.Err check is then its only line, as
-// for its web). Never call it with a.mu held.
-func workerHeadroom(rep Rep) error {
+// workerHeadroom is the gate's lease deadline check, read as runRelease
+// reads it (watchOf, SafeUntil, on the real clock as the lease runs, or
+// a.leaseNow when a test sets it): nil when rep's safety deadline is more
+// than workerStartLead away, or when rep has no lease signal (the tick's
+// rep.Err check is then its only line, as for its web). Never call it with
+// a.mu held.
+func (a *Service) workerHeadroom(rep Rep) error {
held := watchOf(rep)
if held == nil {
return nil
}
until, err := held.SafeUntil()
- if err != nil || time.Until(until) <= workerStartLead() {
+ now := time.Now
+ if a.leaseNow != nil {
+ now = a.leaseNow
+ }
+ if err != nil || until.Sub(now()) <= workerStartLead() {
return fmt.Errorf("%w: %w", errSwapLeaseLost, errWorkerNoHeadroom)
}
return nil
@@ -193,13 +205,15 @@ func workerNames(procs map[string]release.Process) ([]string, error) {
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) {
+// 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.
+func (a *Service) declareRootfsWorkers(e *actEntry, rt registry.Route, w *wokenInstance) {
if !rt.Rootfs() || e.worker {
return
}
@@ -216,68 +230,30 @@ func (a *Service) startRootfsWorkers(ctx context.Context, e *actEntry, rt regist
if len(names) == 0 {
return
}
- wb, ok := a.backend.(RootfsWorkerBackend)
- if !ok {
+ 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, ", "))
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)
+ log.Printf("activator: %s: build %s: no worker registered: %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()
- sctx, cancel := context.WithTimeout(ctx, workerStartBound)
- a.runWorkerStart(sctx, wb, e, rt, wk, w.gen, w.proc, a.workerWakeGate(e, w.gen, w.rep, name))
- cancel()
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.entries[e.host] != e || e.state != actWaking {
+ return
}
-}
-
-// 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; the stray rule; and the lease's
-// safety deadline far enough away to start, stop and prove the worker
-// (workerHeadroom, C7).
-func (a *Service) workerWakeGate(e *actEntry, g Gen, rep Rep, name string) func() error {
- return func() error {
- if err := workerHeadroom(rep); err != nil {
- return err
- }
- 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)
+ 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}
}
}
-// workerGate is every later start's gate (a restart; W2's handover), asked
+// workerGate is every worker start's gate (a first start, 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
@@ -292,7 +268,7 @@ func (a *Service) workerGate(e *actEntry, wk *rootfsWorker) func() error {
if err != nil {
return err
}
- return workerHeadroom(rep)
+ return a.workerHeadroom(rep)
}
}
@@ -330,22 +306,20 @@ func workerStrayRuleLocked(e *actEntry, gen uint64, name string) error {
// 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
+// still the entry's, while the entry is awake and owned; a resident only
+// with its lease watch present (or a replica with no lease signal, which
+// the tick watches). A waking entry installs none: no worker starts inside
+// doWake (Paul's ruling, W1 round 2). 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:
+ if e.state != actAwake || a.ownedLocked(e, false) != nil {
+ return false
+ }
+ if e.route.Resident() && !residentWatchedLocked(e) {
return false
}
wk.proc = proc
@@ -364,8 +338,8 @@ func residentWatchedLocked(e *actEntry) bool {
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
+// runWorkerStart is one start of wk, off a.mu, from the tick (a first
+// start or 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) {
@@ -379,7 +353,7 @@ func (a *Service) runWorkerStart(ctx context.Context, wb RootfsWorkerBackend, e
now := a.now()
switch {
case installed:
- wk.started, wk.retryAt, wk.startFailed = now, time.Time{}, false
+ wk.started, wk.retryAt, wk.startFailed, wk.pending = now, time.Time{}, false, false
case refused:
// Not a crash: the exit is treated as noted, and the start is
// asked again after the current backoff.
@@ -391,13 +365,13 @@ func (a *Service) runWorkerStart(ctx context.Context, wb RootfsWorkerBackend, e
// (C10) advance before any stray's replacement takes its pacing
// (Review Focus 3). started is cleared first: a failed start
// is no healthy run.
- wk.started, wk.retryAt, wk.startFailed = time.Time{}, time.Time{}, true
+ wk.started, wk.retryAt, wk.startFailed, wk.pending = time.Time{}, time.Time{}, true, false
a.noteWorkerExitLocked(e, wk, now)
}
switch {
case stray:
a.strayWorkerLocked(e, wk, now, started)
- case started != nil && !workerEnded(started) && (e.state == actAwake || e.state == actWaking):
+ case started != nil && !workerEnded(started) && e.state == actAwake:
// 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].
@@ -436,7 +410,7 @@ func (a *Service) runWorkerStart(ctx context.Context, wb RootfsWorkerBackend, e
installed = a.installRootfsWorkerLocked(e, wk, p)
a.mu.Unlock()
if !installed {
- // The entry left waking or awake (a stop, a lost lease) while root
+ // The entry stopped or lost its 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
@@ -492,7 +466,7 @@ func (a *Service) strayWorkerLocked(e *actEntry, wk *rootfsWorker, now time.Time
return
}
delete(e.rootfsWorkers, wk.name)
- if e.state == actAwake || e.state == actWaking {
+ if e.state == actAwake {
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}
@@ -500,7 +474,9 @@ func (a *Service) strayWorkerLocked(e *actEntry, wk *rootfsWorker, now time.Time
}
// 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
+// resident tick (W1.22), under a.mu, with no I/O. Every worker start is
+// begun here: a pending worker's first start on the first pass, with no
+// backoff and no crash. 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
@@ -519,6 +495,14 @@ func (a *Service) superviseRootfsLocked(e *actEntry) {
if wk.proc != nil && !wk.startFailed && !workerEnded(wk.proc) {
continue // running
}
+ if wk.pending {
+ // Its first start: no exit to note, no backoff (a refused
+ // first start waits its retryAt).
+ if wk.retryAt.IsZero() || !now.Before(wk.retryAt) {
+ a.restartRootfsWorkerLocked(e, wk)
+ }
+ continue
+ }
if wk.retryAt.IsZero() {
a.noteWorkerExitLocked(e, wk, now)
continue
@@ -615,7 +599,8 @@ func workerExitStatus(p Proc) (int, bool) {
return 0, false
}
-// restartRootfsWorkerLocked restarts wk as a goroutine, in the sidecar
+// restartRootfsWorkerLocked starts wk (its first start, or a restart) 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
@@ -970,7 +955,8 @@ func rootfsWorkersLiveLocked(e *actEntry) bool {
// 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.
+// in the loop, restarting otherwise (a pending worker not yet started by
+// the tick reads restarting: it is about to start).
func (a *Service) RootfsWorkers(host string) []WorkerReport {
a.mu.Lock()
defer a.mu.Unlock()
diff --git a/internal/activator/rootfsworkers_test.go b/internal/activator/rootfsworkers_test.go
index 29e16e4d5..100ed7c04 100644
--- a/internal/activator/rootfsworkers_test.go
+++ b/internal/activator/rootfsworkers_test.go
@@ -122,6 +122,31 @@ type fakeWorkerBackend struct {
// returns, at provenAt.
goneDelay time.Duration
provenAt map[string][]time.Time
+ // clock, when set, stamps "start", "gone" and "proven" events into at
+ // (the rig's lease clock).
+ clock func() time.Time
+ at map[string][]time.Time
+}
+
+// stamp records ev into the order log and, with a clock, its time.
+func (b *fakeWorkerBackend) stamp(ev string) {
+ b.record(ev)
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ if b.clock == nil {
+ return
+ }
+ if b.at == nil {
+ b.at = map[string][]time.Time{}
+ }
+ b.at[ev] = append(b.at[ev], b.clock())
+}
+
+// stampsOf is every time ev was stamped.
+func (b *fakeWorkerBackend) stampsOf(ev string) []time.Time {
+ b.wmu.Lock()
+ defer b.wmu.Unlock()
+ return slices.Clone(b.at[ev])
}
func (b *fakeWorkerBackend) LaunchRootfsWorker(ctx context.Context, _ registry.Route, name string, g Gen, _ Proc) (Proc, error) {
@@ -138,7 +163,7 @@ func (b *fakeWorkerBackend) LaunchRootfsWorker(ctx context.Context, _ registry.R
if err := runExecGate(ctx); err != nil {
return nil, err
}
- b.record(fmt.Sprintf("start %s gen%d", name, g.N))
+ b.stamp(fmt.Sprintf("start %s gen%d", name, g.N))
b.wmu.Lock()
block, entered := b.block, b.entered
b.wmu.Unlock()
@@ -147,6 +172,7 @@ func (b *fakeWorkerBackend) LaunchRootfsWorker(ctx context.Context, _ registry.R
entered <- name
}
<-block
+ b.record("returned " + name)
}
p := &fakeWorkerProc{name: name}
b.wmu.Lock()
@@ -179,7 +205,7 @@ func (b *fakeWorkerBackend) launchCount(name string) int {
}
func (b *fakeWorkerBackend) RootfsWorkerGone(_ context.Context, _ registry.Route, name string) error {
- b.record("gone " + name)
+ b.stamp("gone " + name)
b.wmu.Lock()
f, delay := b.goneErr, b.goneDelay
b.wmu.Unlock()
@@ -191,7 +217,7 @@ func (b *fakeWorkerBackend) RootfsWorkerGone(_ context.Context, _ registry.Route
return err
}
}
- b.record("proven " + name)
+ b.stamp("proven " + name)
b.wmu.Lock()
defer b.wmu.Unlock()
if b.provenAt == nil {
@@ -309,14 +335,30 @@ func (s *stampedSink) with(prefix string) []stampedEvent {
// 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
+ a *Service
+ b *fakeWorkerBackend
+ clk *fakeClock
+ lease *leaseClock
+ sink *stampedSink
+ rt registry.Route
+ host string
+}
+
+// leaseClock is the clock a rig's worker headroom is read on
+// (Service.leaseNow): frozen at the rig's creation and moved only by the
+// test, so a deadline comparison never depends on how fast the box runs.
+// The lease's own deadline is on the real clock, far enough out (or
+// timer-free) that it never fires inside a test that uses this clock.
+type leaseClock struct {
+ t0 time.Time
+ offset atomic.Int64
}
+func (l *leaseClock) now() time.Time { return l.t0.Add(time.Duration(l.offset.Load())) }
+
+// set moves the clock to t0 plus d.
+func (l *leaseClock) set(d time.Duration) { l.offset.Store(int64(d)) }
+
func newWorkerRig(t *testing.T, rt registry.Route, workers ...string) *workerRig {
t.Helper()
kb := &killBackend{fakeBackend: &fakeBackend{}}
@@ -328,6 +370,9 @@ func newWorkerRig(t *testing.T, rt registry.Route, workers ...string) *workerRig
}
a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, wb, reg)
a.now = clk.now
+ lc := &leaseClock{t0: time.Now()}
+ a.leaseNow = lc.now
+ wb.clock = lc.now
a.gens = true
armRootfsForTest(a)
startsFromStagedIdentity(kb.fakeBackend)
@@ -361,11 +406,12 @@ func newWorkerRig(t *testing.T, rt registry.Route, workers ...string) *workerRig
defer cancel()
a.Shutdown(ctx)
})
- return &workerRig{a: a, b: wb, clk: clk, sink: sink, rt: rt, host: rt.Host}
+ return &workerRig{a: a, b: wb, clk: clk, lease: lc, sink: sink, rt: rt, host: rt.Host}
}
-// wake wakes the rig's host by a request.
-func (r *workerRig) wake(t *testing.T) *actEntry {
+// wakeOnly wakes the rig's host by a request: doWake registers the
+// declared workers and starts none.
+func (r *workerRig) wakeOnly(t *testing.T) *actEntry {
t.Helper()
arrangeAwake(t, r.a, r.rt)
e := r.a.awakeEntry(r.host)
@@ -375,6 +421,15 @@ func (r *workerRig) wake(t *testing.T) *actEntry {
return e
}
+// wake wakes the rig's host and runs the tick's first pass, which starts
+// the declared workers (Paul's ruling, W1 round 2).
+func (r *workerRig) wake(t *testing.T) *actEntry {
+ t.Helper()
+ e := r.wakeOnly(t)
+ r.tick(t)
+ 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) {
@@ -463,17 +518,33 @@ func openReleaseRecord(a *Service, host string) {
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.
+// Spec §5.4, Paul's ruling (W1 round 2): workers start once web is
+// started, healthy and replicating, and only from the tick's first pass on
+// the awake entry, never during doWake; in name order, each with RFS-3-C08;
+// before that pass they report restarting, with no restart counted. A
+// failed web start starts none.
func TestRootfsWorkersStartAfterWebHealthy(t *testing.T) {
r := newWorkerRig(t, workerHost(), "mailer", "jobs")
- r.wake(t)
+ r.wakeOnly(t)
+ for _, e := range r.b.events() {
+ if strings.HasPrefix(e, "start jobs") || strings.HasPrefix(e, "start mailer") {
+ t.Fatalf("a worker started during the wake: %v", r.b.events())
+ }
+ }
+ if n := r.b.launchCount("jobs") + r.b.launchCount("mailer"); n != 0 {
+ t.Fatalf("%d worker preparations during the wake", n)
+ }
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerRestarting, 0}, {"mailer", WorkerRestarting, 0}}) {
+ t.Errorf("report before the tick %+v, want both restarting with no restart counted", got)
+ }
+ r.b.record("tick")
+ r.tick(t)
g := r.gen()
ev := r.b.events()
- web, rep := index(ev, "start v1", 0), index(ev, "replicate", 0)
+ web, rep, tick := index(ev, "start v1", 0), index(ev, "replicate", 0), index(ev, "tick", 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)
+ if web < 0 || rep < web || tick < rep || jobs < tick || mailer < tick {
+ t.Fatalf("order %v: want web's start, its replica, the tick, 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 {
@@ -492,6 +563,8 @@ func TestRootfsWorkersStartAfterWebHealthy(t *testing.T) {
if _, err := f.a.beginRequest(context.Background(), f.rt); err == nil {
t.Fatal("the wake of a web that failed to start succeeded")
}
+ f.a.rootfsTick()
+ waitFor(t, "the tick", f.settled)
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())
@@ -699,6 +772,13 @@ func TestRootfsWorkerUnprovenKeepsItsFiles(t *testing.T) {
}
done()
evs.wait(t, GenHealthy)
+ a.rootfsTick() // the first pass starts the declared worker
+ waitFor(t, "the worker's start", func() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ e := a.entries[rt.Host]
+ return e != nil && e.rootfsWorkers["jobs"] != nil && !e.rootfsWorkers["jobs"].starting && e.rootfsWorkers["jobs"].proc != nil
+ })
ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+lb.rt.Host+" jobs ")
p := lb.eb.pathsFor(lb.rt)
launch := filepath.Join(p.dataDir, instancectl.WorkerLaunchFileName("jobs"))
@@ -891,8 +971,18 @@ func residentWorkerRig(t *testing.T) (*workerRig, func() *ownedRep) {
}
// residentWorkerRigUntil is residentWorkerRig whose replica's safety
-// deadline is safe after its creation (on the real clock, as the lease's).
+// deadline is safe after its creation (on the real clock, as the lease's),
+// after the tick's first pass over the awake entry.
func residentWorkerRigUntil(t *testing.T, safe time.Duration) (*workerRig, func() *ownedRep) {
+ t.Helper()
+ r, rep := residentWokenRig(t, safe)
+ r.tick(t) // the first pass starts the declared workers
+ return r, rep
+}
+
+// residentWokenRig is the resident rig woken by the tick, its workers
+// declared and not yet started (no worker tick has run).
+func residentWokenRig(t *testing.T, safe time.Duration) (*workerRig, func() *ownedRep) {
t.Helper()
shrinkResidentPoll(t, time.Hour) // the test ticks by hand
rt := residentRoute("shop.example.com")
@@ -1199,79 +1289,82 @@ func TestWorkerGateRefusesAtTheLastMoment(t *testing.T) {
}
}
-// 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.
+// Paul's ruling (W1 round 2), through the real wake(): (a) during a cold
+// wake root is asked for no worker; once wake() has installed e.gen and
+// the resident's lease watch, the tick's first pass starts it, of that
+// generation, through workerGate; (b) a lease lost before that tick, with
+// or without the lease's signal, starts none.
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
+ t.Run("the tick after the wake starts it", func(t *testing.T) {
+ r, _ := residentWokenRig(t, time.Hour)
+ if n := r.b.launchCount("jobs") + r.b.launchCount("mailer"); n != 0 {
+ t.Fatalf("root was asked for %d worker starts by the cold wake", n)
+ }
+ type seen struct {
+ state actState
+ watched bool
+ gen uint64
+ asked uint64
+ }
+ var mu sync.Mutex
+ var prepared []seen
r.b.setPrepare(func(_ string, g Gen) {
r.a.mu.Lock()
- state = r.a.entries[r.host].state
+ e := r.a.entries[r.host]
+ sn := seen{state: e.state, watched: e.ownerDone != nil, gen: e.gen.N, asked: g.N}
r.a.mu.Unlock()
- asked = g
+ mu.Lock()
+ prepared = append(prepared, sn)
+ mu.Unlock()
})
- r.wake(t)
- r.b.setPrepare(nil)
+ r.tick(t)
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)
+ mu.Lock()
+ defer mu.Unlock()
+ if len(prepared) != 2 {
+ t.Fatalf("%d worker starts on the first tick, want jobs and mailer", len(prepared))
}
- 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)
+ for _, sn := range prepared {
+ if sn.state != actAwake || !sn.watched || sn.asked != g.N || sn.gen != g.N || g.N == 0 {
+ t.Fatalf("a worker was started in %+v; want awake, under the lease watch, with the installed generation %d", sn, g.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())
+ for _, w := range []string{"jobs", "mailer"} {
+ if n := r.b.count(fmt.Sprintf("start %s gen%d", w, g.N)); n != 1 {
+ t.Fatalf("%s started %d times, want once", w, n)
+ }
}
})
- t.Run("the lease lost in its preparation", func(t *testing.T) {
- logs := captureLogLines(t)
+ t.Run("a lease lost before the tick, no lease signal", func(t *testing.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())
+ r.wakeOnly(t)
+ r.b.lastRep().setErr(lease.ErrLost)
+ r.a.rootfsTick()
+ waitFor(t, "the tick", r.settled)
+ if n := len(r.b.workers("jobs")); n != 0 {
+ t.Fatalf("root was asked for %d worker starts after the lease was lost", n)
}
- if n := r.b.alive(); n != 1 {
- t.Fatalf("%d workers run, want the new wake's one", n)
+ })
+ t.Run("a lease lost before the tick, its watch running", func(t *testing.T) {
+ r, rep := residentWokenRig(t, time.Hour)
+ rep().lose(lease.ErrLost)
+ waitFor(t, "the loss's stop", func() bool {
+ r.a.mu.Lock()
+ defer r.a.mu.Unlock()
+ e := r.a.entries[r.host]
+ return e == nil || e.state != actAwake
+ })
+ r.a.rootfsTick()
+ waitFor(t, "the tick", r.settled)
+ if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 0 {
+ t.Fatalf("root was asked for %d worker starts after the lease was lost", 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.
+// [pf W1.23] A wake and its workers' first starts (now from the tick,
+// never under the wake's context: Paul's ruling, W1 round 2) write one
+// pending record, web's.
func TestWorkerStartWritesNoPendingRecord(t *testing.T) {
r := newWorkerRig(t, workerHost(), "jobs", "mailer")
var records atomic.Int32
@@ -1295,13 +1388,25 @@ func TestRootfsWorkersReport(t *testing.T) {
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)
+ // Woken, its workers declared and not yet started by the tick: about
+ // to start, so restarting, with no restart counted.
+ e := r.wakeOnly(t)
+ if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerRestarting, 0}}) {
+ t.Errorf("awake before the first tick: %+v", got)
+ }
+ // A waking entry (doWake registers its workers before wake() makes it
+ // awake): every known name stopped.
+ r.a.mu.Lock()
+ e.state = actWaking
+ r.a.mu.Unlock()
+ waking := r.a.RootfsWorkers(r.host)
+ r.a.mu.Lock()
+ e.state = actAwake
+ r.a.mu.Unlock()
if !slices.Equal(waking, []WorkerReport{{"jobs", WorkerStopped, 0}}) {
t.Errorf("waking: %+v", waking)
}
+ r.tick(t)
if got := r.a.RootfsWorkers(r.host); !slices.Equal(got, []WorkerReport{{"jobs", WorkerRunning, 0}}) {
t.Errorf("awake: %+v", got)
}
@@ -1326,8 +1431,10 @@ func TestRootfsWorkersReport(t *testing.T) {
}
}
-// 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.
+// The workers start and are proven gone through productionBackend: the
+// entry's declaration registered as doWake does, the tick's first pass
+// starts the worker through the real backend over the staged control
+// fake, and the stop proves it and removes its launch file.
func TestWorkersThroughTheProductionBackendInTheService(t *testing.T) {
b, ctl, rt, units := newWorkerBackend(t)
pb := productionBackend(t, b)
@@ -1344,20 +1451,26 @@ func TestWorkersThroughTheProductionBackendInTheService(t *testing.T) {
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.declareRootfsWorkers(e, rt, &wokenInstance{gen: g, proc: web, rep: &fakeRep{}})
+ noCallStarts(t, ctl, "start-rootfs-worker")
a.mu.Lock()
- wk := e.rootfsWorkers["jobs"]
- installed := wk != nil && wk.proc != nil
- e.state = actStopping
+ e.state, e.gen, e.proc, e.rep = actAwake, g, web, &fakeRep{}
+ a.superviseRootfsLocked(e)
a.mu.Unlock()
- if !installed {
- t.Fatal("the worker was not installed through the production backend")
- }
+ waitFor(t, "the first start", func() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ wk := e.rootfsWorkers["jobs"]
+ return wk != nil && !wk.starting && wk.proc != nil
+ })
+ ctl.mustHaveCallPrefix(t, "start-rootfs-worker "+rt.Host+" jobs ")
launch := workerLaunchPath(b, rt, "jobs")
if _, err := os.Stat(launch); err != nil {
t.Fatalf("the worker's launch file: %v", err)
}
+ a.mu.Lock()
+ e.state = actStopping
+ a.mu.Unlock()
if !a.stopRootfsWorkers(e) {
t.Fatal("the worker was not proven gone through the production backend")
}
@@ -1489,48 +1602,6 @@ func TestRootfsWorkersStopAtLeaseLossUnwatched(t *testing.T) {
}
}
-// [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.
@@ -1562,9 +1633,10 @@ func TestWorkerGateStrayRule(t *testing.T) {
}
// [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).
+// for a worker still the entry's, while it is awake and owned (never
+// waking: Paul's ruling, W1 round 2), and a 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))
@@ -1580,7 +1652,7 @@ func TestRootfsWorkerInstallNeedsTheLeaseWatch(t *testing.T) {
other bool // another entry is the host's
install bool
}{
- {"waking", residentRoute("shop.example.com"), actWaking, nil, false, false, true},
+ {"waking (no start inside doWake)", residentRoute("shop.example.com"), actWaking, signal, true, false, false},
{"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},
@@ -1620,30 +1692,26 @@ func shrinkWorkerBounds(t *testing.T, start, proof time.Duration) {
t.Cleanup(func() { workerStartBound, workerProofBound = oldStart, oldProof })
}
-// sleepUntil waits on the real clock, as the lease runs.
-func sleepUntil(at time.Time) {
- if d := time.Until(at); d > 0 {
- time.Sleep(d)
- }
-}
-
-// [C7, Astra W1 r1 P1] Every worker is stopped and proven before the
-// lease's safety deadline, a worker whose start is in flight included, and
-// no worker start is admitted without the headroom to start, stop and
-// prove it first (workerStartLead, read from the lease's SafeUntil as a
-// release's is). On the real clock: lead 1.6 s (start 1 s, proof 600 ms),
-// each worker's drain 200 ms.
+// [C7; Astra W1 r1 P1, r2 P2] Every worker is stopped and proven before
+// the lease's safety deadline, a worker whose start is in flight included,
+// and no worker start is admitted without the headroom to end on its bound
+// and then be stopped and proven first: workerStartLead (start 30 s, proof
+// 52 s, production values), read against the lease's SafeUntil as a
+// release's is. Deterministic: the headroom is read on the rig's lease
+// clock, which moves only when the test moves it; the drain and the start's
+// answer happen when the test makes them, synchronised on channels; the
+// lease's own deadline (100 s out on the real clock) and its timers never
+// fire inside the test.
func TestRootfsWorkerStartsFitBeforeTheLeaseDeadline(t *testing.T) {
- shrinkWorkerBounds(t, time.Second, 600*time.Millisecond)
-
- // A restart admitted with 2 s left, whose response never comes in
- // time: it waits out its 1 s bound, past the moment the lease's drain
- // begins (1.3 s before the deadline), and the lease then expires. The
- // other worker is proven at once, not behind the start; the started
- // one once its start ends; all before the deadline.
- t.Run("a delayed start in flight at the drain", func(t *testing.T) {
- shrinkDrainBudget(t, 1300*time.Millisecond)
- r, rep := residentWorkerRigUntil(t, 3*time.Second)
+ const safe = 100 * time.Second
+
+ // A restart admitted with 83 s left (the lead is 82 s), whose answer
+ // takes its whole 30 s bound. A stop of the instance begins while it
+ // is in flight. The other worker is proven at once, not behind the
+ // start; the started one when its start ends; every proof begins early
+ // enough to end, on its bound, before the deadline.
+ t.Run("a delayed start in flight when the stop begins", func(t *testing.T) {
+ r, rep := residentWorkerRigUntil(t, safe)
until, err := rep().SafeUntil()
if err != nil {
t.Fatal(err)
@@ -1651,47 +1719,68 @@ func TestRootfsWorkerStartsFitBeforeTheLeaseDeadline(t *testing.T) {
if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 2 {
t.Fatalf("%d workers started, want 2", n)
}
- r.b.wmu.Lock()
- r.b.goneDelay = 200 * time.Millisecond
- r.b.wmu.Unlock()
+ g := r.gen()
r.b.lastWorker(t, "jobs").exit("exited", "1")
r.tick(t)
r.clk.advance(sidecarRestartBase)
- sleepUntil(until.Add(-2 * time.Second))
+ admitted := until.Add(-(workerStartLead() + time.Second))
+ r.lease.set(admitted.Sub(r.lease.t0))
+ block, entered := make(chan struct{}), make(chan string, 1)
r.b.wmu.Lock()
- r.b.hang = true
+ r.b.block, r.b.entered = block, entered
r.b.wmu.Unlock()
r.a.rootfsTick()
- waitFor(t, "the restart to reach root", func() bool { return len(r.b.workers("jobs")) == 2 })
+ select {
+ case <-entered:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the restart never reached root")
+ }
+ // The stop begins 8 s later, the start still in root.
+ r.lease.set(admitted.Add(8 * time.Second).Sub(r.lease.t0))
+ e := r.a.awakeEntry(r.host)
+ if e == nil {
+ t.Fatal("the instance is not awake")
+ }
+ r.a.residentLeaseShort(e, until.Sub(r.lease.now()))
+ waitFor(t, "mailer's proof while jobs' start is still in root", func() bool { return r.b.count("proven mailer") == 1 })
+ if index(r.b.events(), "returned jobs", 0) >= 0 {
+ t.Fatal("jobs' start returned before the test let it")
+ }
+ // The start answers at its bound.
+ r.lease.set(admitted.Add(workerStartBound).Sub(r.lease.t0))
+ r.b.wmu.Lock()
+ close(block)
+ r.b.block = nil
+ r.b.wmu.Unlock()
waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
ev := r.b.events()
returned := index(ev, "returned jobs", 0)
- if mailer := index(ev, "proven mailer", 0); returned < 0 || mailer < 0 || mailer > returned {
- t.Fatalf("order %v: mailer's proof waited behind jobs' start in flight", ev)
- }
if index(ev, "proven jobs", returned) < 0 {
t.Fatalf("order %v: the started worker was not proven after its start ended", ev)
}
- r.b.wmu.Lock()
- defer r.b.wmu.Unlock()
- for name, ats := range r.b.provenAt {
- if last := ats[len(ats)-1]; !last.Before(until) {
- t.Errorf("worker %s proven %s after the lease's safety deadline", name, last.Sub(until))
+ for _, name := range []string{"jobs", "mailer"} {
+ for _, began := range r.b.stampsOf("gone " + name) {
+ if began.Add(workerProofBound).After(until) {
+ t.Errorf("a proof of %s began %s before the deadline, less than its %s bound", name, until.Sub(began), workerProofBound)
+ }
}
}
- for _, p := range r.b.wprocs {
+ for _, at := range r.b.stampsOf(fmt.Sprintf("start jobs gen%d", g.N)) {
+ if at.Add(workerStartLead()).After(until) {
+ t.Errorf("a start of jobs was admitted %s before the deadline, inside the %s lead", until.Sub(at), workerStartLead())
+ }
+ }
+ for _, p := range r.b.workers("jobs") {
if !p.Exited() {
- t.Errorf("worker %s runs after the stop", p.name)
+ t.Error("a jobs worker runs after the stop")
}
}
})
- // A restart due with 1.4 s left (less than the 1.6 s lead) is not
- // admitted: root is asked nothing, and the drain proves the rest before
- // the deadline.
+ // A restart due with 80 s left (inside the 82 s lead) is not admitted:
+ // root is asked nothing.
t.Run("a restart without the headroom", func(t *testing.T) {
- shrinkDrainBudget(t, 1300*time.Millisecond)
- r, rep := residentWorkerRigUntil(t, 3*time.Second)
+ r, rep := residentWorkerRigUntil(t, safe)
until, err := rep().SafeUntil()
if err != nil {
t.Fatal(err)
@@ -1699,64 +1788,48 @@ func TestRootfsWorkerStartsFitBeforeTheLeaseDeadline(t *testing.T) {
r.b.lastWorker(t, "jobs").exit("exited", "1")
r.tick(t)
r.clk.advance(sidecarRestartBase)
- sleepUntil(until.Add(-1400 * time.Millisecond))
- r.a.rootfsTick()
- waitFor(t, "the restart to finish", r.settled)
+ r.lease.set(until.Add(-(workerStartLead() - 2*time.Second)).Sub(r.lease.t0))
+ r.tick(t)
if n := len(r.b.workers("jobs")); n != 1 {
- t.Fatalf("root was asked for %d worker starts with 1.4 s left of a 1.6 s lead", n-1)
+ t.Fatalf("root was asked for %d worker starts inside the lead", n-1)
}
- waitFor(t, "the stop to finish", func() bool { return !r.a.hasEntry(r.host) })
- r.b.wmu.Lock()
- defer r.b.wmu.Unlock()
- if ats := r.b.provenAt["mailer"]; len(ats) == 0 || !ats[len(ats)-1].Before(until) {
- t.Errorf("mailer proven at %v, deadline %v", ats, until)
+ })
+
+ // The first start of a freshly woken instance asks the same.
+ t.Run("a first start without the headroom", func(t *testing.T) {
+ r, rep := residentWokenRig(t, safe)
+ until, err := rep().SafeUntil()
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.lease.set(until.Add(-(workerStartLead() - 2*time.Second)).Sub(r.lease.t0))
+ r.tick(t)
+ if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 0 {
+ t.Fatalf("root was asked for %d worker starts inside the lead", n)
}
})
- // The doWake start is bounded the same way: a start whose response
- // never comes ends on workerStartBound, the wake completes, web serves
- // and the worker is left for the supervisor, proven gone.
- t.Run("the wake's start is bounded", func(t *testing.T) {
+ // A start whose answer never comes ends on workerStartBound (shrunk to
+ // 200 ms here, generous against the 5 s wait) and is proven gone.
+ t.Run("a start response that never comes is bounded", func(t *testing.T) {
+ shrinkWorkerBounds(t, 200*time.Millisecond, workerProofBound)
r := newWorkerRig(t, workerHost(), "jobs")
+ r.wake(t)
+ r.b.lastWorker(t, "jobs").exit("exited", "1")
+ r.tick(t)
+ r.clk.advance(sidecarRestartBase)
r.b.wmu.Lock()
r.b.hang = true
r.b.wmu.Unlock()
- woke := make(chan struct{})
- go func() {
- defer close(woke)
- if release, err := r.a.beginRequest(context.Background(), r.rt); err == nil {
- release()
- }
- }()
- select {
- case <-woke:
- case <-time.After(4 * time.Second):
- t.Fatal("the wake waited past its worker start's bound")
- }
+ r.a.rootfsTick()
+ waitFor(t, "the bounded start to end and be proven", func() bool {
+ ev := r.b.events()
+ returned := index(ev, "returned jobs", 0)
+ return returned >= 0 && index(ev, "proven jobs", returned) >= 0
+ })
if !entryAwake(r.a, r.host) {
t.Fatal("web does not serve after its worker's start timed out")
}
- ev := r.b.events()
- if index(ev, "proven jobs", index(ev, "returned jobs", 0)) < 0 {
- t.Fatalf("order %v: the timed-out start was not proven gone", ev)
- }
- })
-
- // The doWake start asks the same: a wake whose lease has less than the
- // lead left starts no worker, and web serves.
- t.Run("the wake's start without the headroom", func(t *testing.T) {
- shrinkDrainBudget(t, 100*time.Millisecond)
- r, rep := residentWorkerRigUntil(t, 1200*time.Millisecond)
- if n := len(r.b.workers("jobs")) + len(r.b.workers("mailer")); n != 0 {
- t.Fatalf("root was asked for %d worker starts with less than the lead left", n)
- }
- // The lease's drain then stops it (and the watch reads its budget
- // for the last time before that, under a.mu's order).
- until, err := rep().SafeUntil()
- if err == nil {
- sleepUntil(until.Add(-50 * time.Millisecond))
- }
- waitFor(t, "the drain's stop", func() bool { return !r.a.hasEntry(r.host) })
})
}