carlos / platform Public

activator: always-on rootfs instances: boot start, crash restart with backoff, four starts at a time, no idle sleep

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev 79759366e82686da1563d989c29994b7ef01f64f parent 63bdb6f
7 files changed, +1,236 −10
  • approved_rootfs_copy_test.go +3 −0
  • internal/activator/activator.go +60 −0
  • internal/activator/rootfs_gate_test.go +28 −10
  • internal/activator/rootfs_invariants_test.go +4 −0
  • internal/activator/rootfs_resident_test.go +771 −0
  • internal/activator/rootfs_service.go +365 −0
  • internal/rolloutwords/words.go +5 −0
diff --git a/approved_rootfs_copy_test.go b/approved_rootfs_copy_test.go
index a9774f751..7794547bc 100644
--- a/approved_rootfs_copy_test.go
+++ b/approved_rootfs_copy_test.go
@@ -184,6 +184,9 @@ var rootfsCopyBuilt = []string{
// (internal/rolloutwords/words.go), the served-never-empty reason
// (internal/activator/rootfs_service.go)
"RFS-3-C12", "RFS-3-C14", "RFS-3-C15",
+ // Plan 3 Task 8: the resident restart event (internal/rolloutwords/words.go)
+ // and the resident backoff's 503 body (internal/activator/activator.go)
+ "RFS-3-C11", "RFS-3-C16",
}
func mustParseRootfsRecord(t *testing.T) []copyRow {
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 32cd4716d..6af0ac598 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -474,6 +474,12 @@ type actEntry struct {
// the whole admission for any other (rootfsWakeRefusal). Set at
// construction, before the wake goroutine starts; never written again.
rootfsAdmittedKey string
+ // resident marks a proactive wake of a resident row the resident tick
+ // made (residentJob, Plan 3 Task 8): its outcome gives back the tick's
+ // reservation (noteResidentWakeLocked). Set at construction, before the
+ // wake goroutine starts; never written again. A request's wake of a
+ // resident row leaves it false.
+ resident bool
// probe is set for an entry ProbeWake made (moves Plan 3 Task 5): the
// claim path runs with the probe's policy, and the entry is held for
// the move while its registry row is.
@@ -1305,6 +1311,17 @@ type Service struct {
rootfsGateMu sync.Mutex
rootfsGateRuns map[string]*rootfsGateRun
rootfsRefusedSeen map[string]string
+ // Residency (Plan 3 Task 8, rootfs_service.go). residentLister is the
+ // DueStore read as a ResidentLister at New (nil: no residents).
+ // residents is each listed resident's backoff and reservation, by host;
+ // residentStarting counts the proactive starts in flight (reserved by
+ // rootfsTick, given back by residentJob or the wake's outcome), at most
+ // residentStartCeiling. residentJitter is the backoff's jitter (nil:
+ // production's). residents and residentStarting are under a.mu.
+ residentLister ResidentLister
+ residents map[string]*residentState
+ residentStarting int
+ residentJitter func() float64
// cacheGens is host -> *atomic.Uint64, the newest generation that has
// been current for that host (CacheGen). A sync.Map, never under a.mu:
// the edge cache reads it while holding the cache's own lock.
@@ -1451,6 +1468,11 @@ func New(cfg Config, backend Backend, due DueStore) *Service {
entries: make(map[string]*actEntry),
gens: GenerationsEnabled(),
}
+ // The resident listing (Plan 3 Task 8): the registry in production. A
+ // DueStore without it (a test double) has no residents.
+ if l, ok := due.(ResidentLister); ok {
+ a.residentLister = l
+ }
// The service lifetime, cancelled by Shutdown. Only work that a shutdown
// should ABANDON hangs off it — today that is exactly the supervised
// worker respawn's exec. Everything a shutdown must still FINISH (the
@@ -1559,6 +1581,15 @@ func (a *Service) begin(ctx context.Context, rt registry.Route, stamp bool, req
admitted := gated
gated = ""
if e == nil {
+ // A resident inside its backoff (Plan 3 Task 8) is not started
+ // by a request either: the answer is 503 with Retry-After, and
+ // the resident tick starts it once the backoff has passed.
+ if rt.Resident() {
+ if d := a.residentDelayLocked(rt.Host); d > 0 {
+ a.mu.Unlock()
+ return nil, &errResidentBackoff{retryAfter: d}
+ }
+ }
// The rootfs admission (Plan 3 Task 7, INV-3), before an entry
// is made, so a refused row never reaches Acquire, Restore or
// the live link: the locked half here; for a rootfs row, the
@@ -2048,6 +2079,10 @@ func (a *Service) wake(e *actEntry) {
go a.OnWake(rt)
}
}
+ // Residency's view of the outcome (Plan 3 Task 8): a proactive wake
+ // gives back its reservation, and a resident's failure counts toward
+ // its backoff only when it is the build's (residentFailure).
+ a.noteResidentWakeLocked(e, err)
if w != nil && w.pend != 0 {
// The cold wake's pending build (step 2b): the generation installed
// above, or the failed wake retained as unproven, now names it
@@ -4565,6 +4600,9 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) {
a.rememberStopLocked(e.host, outcome)
republish := e.worker || a.publishesLocked(e)
delete(a.entries, e.host)
+ // A resident's stop, as it is forgotten (Plan 3 Task 8): a crash or a
+ // lost lease backs off; any other stop is restarted on the next tick.
+ a.noteResidentStopLocked(e)
retired := e.gen
// The canonical link goes with the last generation (spec §7.1). Under
// a.mu, the lock the awake transition creates links under, so a new
@@ -4628,6 +4666,7 @@ func (a *Service) Start() {
if interval > 30*time.Second {
interval = 30 * time.Second
}
+ poll := residentPoll
go func() {
defer close(a.sweepDone)
if a.Startup != nil {
@@ -4639,6 +4678,12 @@ func (a *Service) Start() {
}
t := time.NewTicker(interval)
defer t.Stop()
+ // The resident tick (Plan 3 Task 8) on its own ticker in this
+ // goroutine, so Shutdown's stop of the sweeper stops it too. It
+ // reserves and hands every gate's I/O to its own jobs, so it never
+ // holds this goroutine for longer than its listing read.
+ rt := time.NewTicker(poll)
+ defer rt.Stop()
for {
select {
case <-a.sweepStop:
@@ -4646,6 +4691,8 @@ func (a *Service) Start() {
case <-t.C:
a.sweepOnce()
a.lastSweep.Store(time.Now().UnixNano())
+ case <-rt.C:
+ a.rootfsTick()
}
}
}()
@@ -4846,6 +4893,12 @@ func (a *Service) sweepOnce() {
continue
}
hibernates := !e.worker || e.route.Hibernate
+ // A resident (Plan 3 Task 8, spec §5.6) is never stopped for
+ // idleness, and neither the plans idle hook nor the continuous-awake
+ // ceiling below can reach it.
+ if e.route.Resident() {
+ hibernates = false
+ }
// A held probe entry (ProbeWake) gets no traffic: the edge routes no
// held row. It is not idle until the target's open marks it open
// (OpenProbeEntry, Plan 3 Task 7).
@@ -5652,9 +5705,16 @@ func (a *Service) serve(w http.ResponseWriter, r *http.Request, rt registry.Rout
func (a *Service) serveWakeError(w http.ResponseWriter, r *http.Request, rt registry.Route, err error) bool {
var held *errLeaseHeld
var refused *errConfigRefused
+ var backoff *errResidentBackoff
switch {
case errors.Is(err, ErrFenced):
maintenanceResponse(w, r)
+ case errors.As(err, &backoff):
+ // A resident inside its backoff (Plan 3 Task 8): the tick starts it
+ // when the backoff has passed, so the answer names that time.
+ w.Header().Set("Retry-After", strconv.Itoa(retryAfterSeconds(backoff.retryAfter)))
+ edge.MarkAnswered(r)
+ http.Error(w, "instance is restarting; retry shortly", http.StatusServiceUnavailable) // RFS-3-C16
case errors.As(err, &refused):
// Quiet by design: the config guard logs once per host and
// publishes the refusal in the box's status snapshot. A line per
diff --git a/internal/activator/rootfs_gate_test.go b/internal/activator/rootfs_gate_test.go
index 88abfceae..23f2155ca 100644
--- a/internal/activator/rootfs_gate_test.go
+++ b/internal/activator/rootfs_gate_test.go
@@ -211,10 +211,12 @@ func rootfsGateCases(t *testing.T) []gateCase {
// lease, through begin (a request, and ServeHTTP's answer) and through
// doWake (a wake that did not come through begin): no Acquire, no
// Restore, no live link materialized or captured, no build state
-// recorded, no start, no entry left. Task 8 adds rootfsTick's rows.
+// recorded, no start, no entry left. Task 8 adds rootfsTick's rows: the
+// same row as a resident, three ticks, the refusal recorded once and no
+// failure counted.
func TestRootfsRefusalPrecedesTheLease(t *testing.T) {
for _, c := range rootfsGateCases(t) {
- for _, path := range []string{"begin", "doWake", "ServeHTTP"} {
+ for _, path := range []string{"begin", "doWake", "ServeHTTP", "rootfsTick"} {
t.Run(c.name+"/"+path, func(t *testing.T) {
a, b, _, records := gateService(t)
rt := rootfsGateRoute("shop.example.com")
@@ -232,15 +234,31 @@ func TestRootfsRefusalPrecedesTheLease(t *testing.T) {
t.Fatalf("ServeHTTP = %d %q, want 503 instance failed to wake", rec.Code, rec.Body.String())
}
_, err = a.beginRequest(context.Background(), rt) // the error the answer was for
+ case "rootfsTick":
+ res := rt
+ res.Hibernate, res.Status = false, "ready"
+ a.residentLister = &fakeResidents{routes: []registry.Route{res}}
+ for i := 0; i < 3; i++ {
+ tickSettled(t, a)
+ }
+ st, _ := a.residentOf(rt.Host)
+ if !strings.Contains(st.refused, c.want) {
+ t.Fatalf("the tick recorded refusal %q, want one saying %q", st.refused, c.want)
+ }
+ if st.failures != 0 || !st.retryAt.IsZero() || st.starting {
+ t.Fatalf("a refused resident's state %+v: a refusal counts no failure", st)
+ }
}
- if err == nil || !strings.Contains(err.Error(), c.want) {
- t.Fatalf("err = %v, want a refusal saying %q", err, c.want)
- }
- if !errors.Is(err, errRootfsRefused) || !errors.Is(err, errRootfsNotAdmitted) {
- t.Fatalf("err = %v is not marked a refusal before the lease", err)
- }
- if v := verdictOf(err); v != gateNoOwnership {
- t.Errorf("verdictOf = %d, want gateNoOwnership", v)
+ if path != "rootfsTick" {
+ if err == nil || !strings.Contains(err.Error(), c.want) {
+ t.Fatalf("err = %v, want a refusal saying %q", err, c.want)
+ }
+ if !errors.Is(err, errRootfsRefused) || !errors.Is(err, errRootfsNotAdmitted) {
+ t.Fatalf("err = %v is not marked a refusal before the lease", err)
+ }
+ if v := verdictOf(err); v != gateNoOwnership {
+ t.Errorf("verdictOf = %d, want gateNoOwnership", v)
+ }
}
if got := b.gateCounts(); got != (gateCounts{}) {
t.Fatalf("a refused wake touched %+v; want nothing", got)
diff --git a/internal/activator/rootfs_invariants_test.go b/internal/activator/rootfs_invariants_test.go
index 509b7f6ef..43c85ef1a 100644
--- a/internal/activator/rootfs_invariants_test.go
+++ b/internal/activator/rootfs_invariants_test.go
@@ -899,6 +899,10 @@ func TestRootfsRefusalsAreNotBuildFailures(t *testing.T) {
if s := classifyStep(nil, c.err); s != stepStale {
t.Errorf("%s: classifyStep = %d, want stepStale (never stepFailed): %v", c.name, s, c.err)
}
+ // Task 8: a resident's failure count reads the same classification.
+ if residentFailure(c.err) {
+ t.Errorf("%s: residentFailure = true, want false (never the resident's failure): %v", c.name, c.err)
+ }
}
}
diff --git a/internal/activator/rootfs_resident_test.go b/internal/activator/rootfs_resident_test.go
new file mode 100644
index 000000000..ae7707c07
--- /dev/null
+++ b/internal/activator/rootfs_resident_test.go
@@ -0,0 +1,771 @@
+package activator
+
+// Rootfs apps Plan 3 Task 8: residency, the always-on rootfs instance
+// (spec §5.6). Started at boot with no request, restarted after a crash or
+// a lost lease with a backoff a request cannot bypass, never stopped for
+// idleness, at most four starts in flight, and every start through the
+// same admission and wake as a request's (INV-3, INV-4). Not parallel:
+// several tests shrink residentPoll or capture the log.
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "strconv"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/registry"
+ "github.com/carlosframework/platform/internal/rolloutwords"
+)
+
+// fakeResidents is a ResidentLister a test drives: the rows it lists, or an
+// error, and how often it was asked.
+type fakeResidents struct {
+ mu sync.Mutex
+ routes []registry.Route
+ err error
+ calls int
+}
+
+func (f *fakeResidents) ResidentInstances() ([]registry.Route, error) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.calls++
+ if f.err != nil {
+ return nil, f.err
+ }
+ return append([]registry.Route(nil), f.routes...), nil
+}
+
+func (f *fakeResidents) set(routes ...registry.Route) {
+ f.mu.Lock()
+ f.routes, f.err = routes, nil
+ f.mu.Unlock()
+}
+
+func (f *fakeResidents) fail(err error) {
+ f.mu.Lock()
+ f.err = err
+ f.mu.Unlock()
+}
+
+func (f *fakeResidents) asked() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.calls
+}
+
+// residentRoute is a resident row of host: a rootfs instance that does not
+// hibernate.
+func residentRoute(host string) registry.Route {
+ rt := rootfsGateRoute(host)
+ rt.Hibernate = false
+ rt.Status = "ready"
+ return rt
+}
+
+// residentService is a Service over fakeBackend with generations on, its
+// rootfs admission open, no backoff jitter, a sink for member events and a
+// fake lister of routes. shut is its one Shutdown (the cleanup's too).
+func residentService(t *testing.T, idle time.Duration, routes ...registry.Route) (a *Service, b *fakeBackend, clk *fakeClock, l *fakeResidents, sink *rootfsSink, shut func(context.Context)) {
+ t.Helper()
+ a, b, clk, _ = testActivator(t, idle)
+ a.gens = true
+ armRootfsForTest(a)
+ a.residentJitter = func() float64 { return 0 }
+ l = &fakeResidents{routes: routes}
+ a.residentLister = l
+ sink = &rootfsSink{}
+ a.Logs = sink
+ var once sync.Once
+ shut = func(ctx context.Context) { once.Do(func() { a.Shutdown(ctx) }) }
+ t.Cleanup(func() { shut(context.Background()) })
+ return a, b, clk, l, sink, shut
+}
+
+// shrinkResidentPoll sets residentPoll for one test. Start reads it once.
+func shrinkResidentPoll(t *testing.T, d time.Duration) {
+ t.Helper()
+ old := residentPoll
+ residentPoll = d
+ t.Cleanup(func() { residentPoll = old })
+}
+
+// residentOf is a copy of host's residency state (zero when none).
+func (a *Service) residentOf(host string) (residentState, bool) {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ st := a.residents[host]
+ if st == nil {
+ return residentState{}, false
+ }
+ return *st, true
+}
+
+func (a *Service) startingNow() int {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.residentStarting
+}
+
+func (a *Service) awakeEntry(host string) *actEntry {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if e := a.entries[host]; e != nil && e.state == actAwake {
+ return e
+ }
+ return nil
+}
+
+func (a *Service) hasEntry(host string) bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.entries[host] != nil
+}
+
+func (b *fakeBackend) acquireCount() int {
+ b.mu.Lock()
+ defer b.mu.Unlock()
+ return b.acquires
+}
+
+// tickSettled runs one resident tick and waits until every job and
+// proactive wake it reserved has given its reservation back.
+func tickSettled(t *testing.T, a *Service) {
+ t.Helper()
+ a.rootfsTick()
+ waitFor(t, "the tick's jobs to settle", func() bool { return a.startingNow() == 0 })
+}
+
+// startResident ticks host awake and returns its entry.
+func startResident(t *testing.T, a *Service, host string) *actEntry {
+ t.Helper()
+ tickSettled(t, a)
+ e := a.awakeEntry(host)
+ if e == nil {
+ t.Fatalf("%s is not awake after a tick", host)
+ }
+ return e
+}
+
+// crashResident makes host's process exit and lets the tick stop it.
+func crashResident(t *testing.T, a *Service, b *fakeBackend, host string) {
+ t.Helper()
+ b.lastProc().exit()
+ a.rootfsTick()
+ waitFor(t, host+"'s stop", func() bool { return !a.hasEntry(host) })
+}
+
+// retryIn is how far host's retry time is from now.
+func retryIn(a *Service, clk *fakeClock, host string) time.Duration {
+ st, _ := a.residentOf(host)
+ return st.retryAt.Sub(clk.now())
+}
+
+// The resident starts at boot: Service.Start through the registry's own
+// ResidentInstances (New reads it from the DueStore), with no request.
+func TestResidentStartsAtBootWithNoRequest(t *testing.T) {
+ shrinkResidentPoll(t, 10*time.Millisecond)
+ a, b, _, reg := testActivator(t, time.Hour)
+ if a.residentLister == nil {
+ t.Fatal("New did not read the registry as the resident lister")
+ }
+ a.gens = true
+ armRootfsForTest(a)
+ rt := residentRoute("shop.example.com")
+ if err := reg.Upsert(rt); err != nil {
+ t.Fatal(err)
+ }
+ startup := make(chan struct{})
+ a.Startup = startup
+ t.Cleanup(func() { a.Shutdown(context.Background()) })
+ a.Start()
+ time.Sleep(50 * time.Millisecond)
+ if n := b.startCount(); n != 0 {
+ t.Fatalf("%d starts before Startup closed", n)
+ }
+ close(startup)
+ deadline := time.Now().Add(time.Second)
+ for b.startCount() != 1 {
+ if time.Now().After(deadline) {
+ t.Fatalf("starts = %d one second after Startup, want 1", b.startCount())
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ waitFor(t, "the resident to be awake", func() bool { return a.awakeEntry(rt.Host) != nil })
+}
+
+// A resident is never stopped for idleness, whatever the plans idle hook
+// says; a hibernating rootfs row in the same service sleeps.
+func TestResidentNeverIdles(t *testing.T) {
+ a, b, clk, _, _, _ := residentService(t, time.Minute, residentRoute("shop.example.com"))
+ a.SetIdleFor(func(registry.Route) time.Duration { return time.Second })
+ startResident(t, a, "shop.example.com")
+ sleeper := rootfsGateRoute("blog.example.com")
+ done, err := a.beginRequest(context.Background(), sleeper)
+ if err != nil {
+ t.Fatal(err)
+ }
+ done()
+ clk.advance(10 * time.Minute)
+ a.sweepOnce()
+ waitFor(t, "the hibernating row to sleep", func() bool { return !a.hasEntry(sleeper.Host) })
+ a.sweepOnce()
+ if a.awakeEntry("shop.example.com") == nil {
+ t.Fatal("the resident was stopped by the idle sweep")
+ }
+ if n := b.startCount(); n != 2 {
+ t.Fatalf("starts = %d, want 2", n)
+ }
+}
+
+// Seven crashes in a row, each in the process's first second: the next
+// start is held for 1, 2, 4, 8, 16, 32, then 60 s of fake time, and never
+// begins a nanosecond earlier.
+func TestResidentCrashBacksOff(t *testing.T) {
+ host := "shop.example.com"
+ a, b, clk, _, sink, _ := residentService(t, time.Hour, residentRoute(host))
+ startResident(t, a, host)
+ for i, want := range []time.Duration{1, 2, 4, 8, 16, 32, 60} {
+ want *= time.Second
+ crashResident(t, a, b, host)
+ if got := retryIn(a, clk, host); got != want {
+ t.Fatalf("crash %d: retry in %s, want %s", i+1, got, want)
+ }
+ msgs := sink.msgs()
+ if last := msgs[len(msgs)-1]; last != fmt.Sprintf(rolloutwords.EventResidentExited, want.String()) {
+ t.Fatalf("crash %d: event %q", i+1, last)
+ }
+ starts := b.startCount()
+ clk.advance(want - time.Nanosecond)
+ tickSettled(t, a)
+ if a.hasEntry(host) || b.startCount() != starts {
+ t.Fatalf("crash %d: started %s into a %s backoff", i+1, want-time.Nanosecond, want)
+ }
+ clk.advance(time.Nanosecond)
+ startResident(t, a, host)
+ if b.startCount() != starts+1 {
+ t.Fatalf("crash %d: starts %d, want %d", i+1, b.startCount(), starts+1)
+ }
+ }
+ if st, _ := a.residentOf(host); st.failures != 7 || st.restarts != 7 {
+ t.Fatalf("state %+v, want 7 failures and 7 restarts", st)
+ }
+ if got := fmt.Sprintf(rolloutwords.EventResidentExited, "1s"); got != "instance exited. starting it again in 1s" {
+ t.Fatalf("RFS-3-C11 = %q", got)
+ }
+}
+
+// A run of 61 s resets the count: after three quick crashes (1, 2, 4 s),
+// the exit of a long run is held for 1 s again.
+func TestResidentHealthyRunResetsBackoff(t *testing.T) {
+ host := "shop.example.com"
+ a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ startResident(t, a, host)
+ for _, d := range []time.Duration{1, 2, 4} {
+ crashResident(t, a, b, host)
+ clk.advance(d * time.Second)
+ startResident(t, a, host)
+ }
+ clk.advance(61 * time.Second)
+ crashResident(t, a, b, host)
+ if got := retryIn(a, clk, host); got != time.Second {
+ t.Fatalf("after a healthy run: retry in %s, want 1s", got)
+ }
+ if st, _ := a.residentOf(host); st.failures != 1 || st.restarts != 4 {
+ t.Fatalf("state %+v, want 1 failure and 4 restarts", st)
+ }
+}
+
+// Inside the backoff a request gets 503, Retry-After of at least the
+// remaining whole seconds and RFS-3-C16, and starts nothing.
+func TestResidentRequestsCannotBypassBackoff(t *testing.T) {
+ host := "shop.example.com"
+ rt := residentRoute(host)
+ a, b, clk, _, _, _ := residentService(t, time.Hour, rt)
+ startResident(t, a, host)
+ for _, d := range []time.Duration{1, 2} {
+ crashResident(t, a, b, host)
+ clk.advance(d * time.Second)
+ startResident(t, a, host)
+ }
+ crashResident(t, a, b, host) // a 4 s backoff
+ clk.advance(1500 * time.Millisecond)
+ starts, acquires := b.startCount(), b.acquireCount()
+ for i := 0; i < 5; i++ {
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler())
+ if rec.Code != http.StatusServiceUnavailable {
+ t.Fatalf("request %d: %d, want 503", i, rec.Code)
+ }
+ if body := strings.TrimSpace(rec.Body.String()); body != "instance is restarting; retry shortly" {
+ t.Fatalf("request %d: body %q, want RFS-3-C16", i, body)
+ }
+ ra, err := strconv.Atoi(rec.Header().Get("Retry-After"))
+ if err != nil || ra < 3 {
+ t.Fatalf("request %d: Retry-After %q, want at least 3 (2.5 s left, rounded up)", i, rec.Header().Get("Retry-After"))
+ }
+ }
+ if b.startCount() != starts || b.acquireCount() != acquires || a.hasEntry(host) {
+ t.Fatal("a request inside the backoff started the resident")
+ }
+ clk.advance(2500 * time.Millisecond)
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler())
+ if rec.Code != http.StatusOK {
+ t.Fatalf("after the backoff: %d, want 200", rec.Code)
+ }
+}
+
+// Ten residents with their starts held: exactly four wakes in flight; once
+// released the rest start on later ticks, and no sample ever sees more
+// than four reserved.
+func TestResidentStartCeilingIsFour(t *testing.T) {
+ var routes []registry.Route
+ for i := 0; i < 10; i++ {
+ routes = append(routes, residentRoute(fmt.Sprintf("r%d.example.com", i)))
+ }
+ a, b, _, _, _, _ := residentService(t, time.Hour, routes...)
+ gate := make(chan struct{})
+ b.mu.Lock()
+ b.startGate = gate
+ b.mu.Unlock()
+ var maxSeen atomic.Int64
+ stop := make(chan struct{})
+ sampled := make(chan struct{})
+ go func() {
+ defer close(sampled)
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ if n := int64(a.startingNow()); n > maxSeen.Load() {
+ maxSeen.Store(n)
+ }
+ time.Sleep(100 * time.Microsecond)
+ }
+ }()
+ a.rootfsTick()
+ waitFor(t, "four starts", func() bool { return b.startCount() == 4 })
+ for i := 0; i < 5; i++ {
+ a.rootfsTick()
+ }
+ time.Sleep(50 * time.Millisecond)
+ if n, s := b.startCount(), a.startingNow(); n != 4 || s != 4 {
+ t.Fatalf("with starts held: %d starts, %d reserved; want 4 and 4", n, s)
+ }
+ close(gate)
+ for i := 0; i < 50 && b.startCount() < 10; i++ {
+ a.rootfsTick()
+ if s := a.startingNow(); s > residentStartCeiling {
+ t.Fatalf("%d reserved after a tick", s)
+ }
+ time.Sleep(5 * time.Millisecond)
+ }
+ waitFor(t, "every resident awake", func() bool {
+ for _, rt := range routes {
+ if a.awakeEntry(rt.Host) == nil {
+ return false
+ }
+ }
+ return true
+ })
+ close(stop)
+ <-sampled
+ if n := b.startCount(); n != 10 {
+ t.Fatalf("starts = %d, want 10", n)
+ }
+ if m := maxSeen.Load(); m > residentStartCeiling {
+ t.Fatalf("saw %d starts reserved at once, want at most %d", m, residentStartCeiling)
+ }
+}
+
+// An adoption's cycle (ConvergeAdopted) stops the resident; the next tick
+// starts it again with no backoff and no failure counted.
+func TestResidentRestartsAfterAdoptionAtOnce(t *testing.T) {
+ host := "shop.example.com"
+ a, b, _, _, sink, _ := residentService(t, time.Hour, residentRoute(host))
+ var cur atomic.Value
+ cur.Store("v1")
+ b.mu.Lock()
+ b.execVerFn = func() string { return cur.Load().(string) }
+ b.mu.Unlock()
+ a.liveVer = func(string) (string, error) { return cur.Load().(string), nil }
+ startResident(t, a, host)
+ cur.Store("v2")
+ if !a.ConvergeAdopted(host, "v2") {
+ t.Fatal("ConvergeAdopted did not cycle the resident")
+ }
+ waitFor(t, "the cycle's stop", func() bool { return !a.hasEntry(host) })
+ if st, _ := a.residentOf(host); st.failures != 0 || st.restarts != 0 {
+ t.Fatalf("an adoption counted as a failure: %+v", st)
+ }
+ e := startResident(t, a, host)
+ if b.startCount() != 2 || e.spawnVersion != "v2" {
+ t.Fatalf("starts %d on %q, want 2 on v2", b.startCount(), e.spawnVersion)
+ }
+ for _, m := range sink.msgs() {
+ if strings.HasPrefix(m, "instance exited") {
+ t.Fatalf("an adoption sent %q", m)
+ }
+ }
+}
+
+// What stops a resident for good: its row going away, a fence (until it is
+// lifted) and the agent's shutdown, after which the tick has stopped too.
+func TestResidentNotRestartedWhenRetiredFencedOrShutDown(t *testing.T) {
+ host := "shop.example.com"
+ t.Run("retired", func(t *testing.T) {
+ a, b, _, l, _, _ := residentService(t, time.Hour, residentRoute(host))
+ startResident(t, a, host)
+ l.set()
+ a.RetireExcept(map[string]bool{})
+ waitFor(t, "the retirement's stop", func() bool { return !a.hasEntry(host) })
+ for i := 0; i < 5; i++ {
+ tickSettled(t, a)
+ }
+ if _, ok := a.residentOf(host); ok || b.startCount() != 1 || a.hasEntry(host) {
+ t.Fatalf("a retired resident was started again (starts %d)", b.startCount())
+ }
+ })
+ t.Run("fenced", func(t *testing.T) {
+ a, b, _, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ startResident(t, a, host)
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if _, err := a.FenceAndStop(ctx, host, 1); err != nil {
+ t.Fatal(err)
+ }
+ if st, _ := a.residentOf(host); st.failures != 0 {
+ t.Fatalf("a fence's stop counted as a failure: %+v", st)
+ }
+ for i := 0; i < 5; i++ {
+ tickSettled(t, a)
+ }
+ if b.startCount() != 1 || a.hasEntry(host) {
+ t.Fatalf("a fenced resident was started (starts %d)", b.startCount())
+ }
+ if !a.LiftFence(host, 1) {
+ t.Fatal("LiftFence")
+ }
+ startResident(t, a, host)
+ if b.startCount() != 2 {
+ t.Fatalf("starts %d after the fence lifted, want 2", b.startCount())
+ }
+ })
+ t.Run("shutdown", func(t *testing.T) {
+ shrinkResidentPoll(t, 10*time.Millisecond)
+ a, b, _, l, _, shut := residentService(t, time.Hour, residentRoute(host))
+ a.Start()
+ waitFor(t, "the boot start", func() bool { return a.awakeEntry(host) != nil })
+ shut(context.Background())
+ select {
+ case <-a.sweepDone:
+ default:
+ t.Fatal("the sweeper, and with it the tick, is still running after Shutdown")
+ }
+ asked := l.asked()
+ time.Sleep(100 * time.Millisecond)
+ if b.startCount() != 1 || a.hasEntry(host) || l.asked() != asked {
+ t.Fatalf("after Shutdown: starts %d, entry %v, lister asked %d more times", b.startCount(), a.hasEntry(host), l.asked()-asked)
+ }
+ })
+}
+
+// Twenty failed listings stop and forget nothing: the awake resident keeps
+// its entry, its replica and its state.
+func TestResidentListingFailureStopsNothing(t *testing.T) {
+ host := "shop.example.com"
+ a, _, _, l, _, _ := residentService(t, time.Hour, residentRoute(host))
+ e := startResident(t, a, host)
+ rep := e.rep.(*fakeRep)
+ l.fail(errors.New("registry: database is locked"))
+ for i := 0; i < 20; i++ {
+ tickSettled(t, a)
+ }
+ if a.awakeEntry(host) != e || rep.isClosed() {
+ t.Fatal("a failed listing stopped the resident")
+ }
+ if _, ok := a.residentOf(host); !ok {
+ t.Fatal("a failed listing forgot the resident")
+ }
+}
+
+// The awake resident's replication is the activator's: the replica the
+// fake lease's Replicate handed the wake, under the lease it took.
+func TestResidentReplicationIsTheActivators(t *testing.T) {
+ host := "shop.example.com"
+ a, b, _, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ e := startResident(t, a, host)
+ if !e.route.ActivatorLeased() {
+ t.Fatal("a resident row is not activator-leased")
+ }
+ if e.rep != Rep(b.lastRep()) || b.acquireCount() != 1 {
+ t.Fatalf("the resident's replica %p is not its lease's %p (acquires %d)", e.rep, b.lastRep(), b.acquireCount())
+ }
+}
+
+// A refusal of the backend's gates for 20 ticks counts no failure, takes no
+// lease and logs once; once it clears, the next tick starts the resident
+// with no backoff.
+func TestResidentRefusalCountsNoFailure(t *testing.T) {
+ host := "shop.example.com"
+ a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ var buf syncBuffer
+ prev := log.Writer()
+ log.SetOutput(&buf)
+ t.Cleanup(func() { log.SetOutput(prev) })
+ b.mu.Lock()
+ b.startable = func(context.Context, registry.Route) error {
+ return refuseRootfs(errors.New("this box is shared"))
+ }
+ b.mu.Unlock()
+ for i := 0; i < 20; i++ {
+ tickSettled(t, a)
+ }
+ st, _ := a.residentOf(host)
+ if st.failures != 0 || !st.retryAt.IsZero() || !strings.Contains(st.refused, "this box is shared") {
+ t.Fatalf("state after refusals %+v", st)
+ }
+ if got := b.gateCounts(); got != (gateCounts{}) {
+ t.Fatalf("a refused resident touched %+v", got)
+ }
+ if n := strings.Count(buf.String(), "refused before the lease"); n != 1 {
+ t.Fatalf("%d refusal log lines, want 1:\n%s", n, buf.String())
+ }
+ b.mu.Lock()
+ b.startable = nil
+ b.mu.Unlock()
+ startResident(t, a, host)
+ if st, _ := a.residentOf(host); st.refused != "" || st.failures != 0 || st.retryAt.After(clk.now()) {
+ t.Fatalf("state after the refusal cleared %+v", st)
+ }
+}
+
+// [Astra R1 11] residentFailure over every INV-4 case (false) and the
+// build's own failures (true); then through the tick: a wake failing with
+// each false case leaves failures at 0, and an Acquire failing on a store
+// outage backs off.
+func TestResidentFailureClassification(t *testing.T) {
+ notCounted := []struct {
+ name string
+ err error
+ }{
+ {"a refusal before the lease", notAdmitted(refuseRootfs(errors.New("this box is shared")))},
+ {"a refusal inside the start", refuseRootfs(errors.New("root refused the start"))},
+ {"a served row with no replica", refuseRootfs(fmt.Errorf("x: %w", errRootfsReplicaMissing))},
+ {"errSwapLeaseLost", fmt.Errorf("x: %w", errSwapLeaseLost)},
+ {"errSwapBusy", fmt.Errorf("x: %w", errSwapBusy)},
+ {"errWakeUnproven", fmt.Errorf("x: refusing to wake: %w", errWakeUnproven)},
+ {"ErrFenced", ErrFenced},
+ {"shutdown", errShuttingDown},
+ {"cancelled", fmt.Errorf("x: %w", context.Canceled)},
+ {"superseded", fmt.Errorf("x: %w", errSwapSuperseded)},
+ }
+ counted := []struct {
+ name string
+ err error
+ }{
+ {"a health failure", errors.New("start shop.example.com: health: socket never accepted")},
+ {"a crash at start", errors.New("start shop.example.com: process exited during startup")},
+ {"an Acquire store error", errors.New("acquire: s3: 503 SlowDown")},
+ }
+ for _, c := range notCounted {
+ if residentFailure(c.err) {
+ t.Errorf("%s: residentFailure = true, want false (INV-4)", c.name)
+ }
+ }
+ for _, c := range counted {
+ if !residentFailure(c.err) {
+ t.Errorf("%s: residentFailure = false, want true", c.name)
+ }
+ }
+ host := "shop.example.com"
+ for _, c := range notCounted {
+ t.Run(c.name, func(t *testing.T) {
+ a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ b.mu.Lock()
+ b.startErr = c.err
+ b.mu.Unlock()
+ tickSettled(t, a)
+ if st, _ := a.residentOf(host); st.failures != 0 || st.retryAt.After(clk.now()) {
+ t.Fatalf("a wake failing with %v: %+v, want no failure and no backoff", c.err, st)
+ }
+ })
+ }
+ t.Run("an Acquire store error", func(t *testing.T) {
+ a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ b.mu.Lock()
+ b.acquireErr = errors.New("s3: 503 SlowDown")
+ b.mu.Unlock()
+ tickSettled(t, a)
+ if st, _ := a.residentOf(host); st.failures != 1 || retryIn(a, clk, host) != time.Second {
+ t.Fatalf("a store outage: %+v, want one failure and a 1 s backoff", st)
+ }
+ tickSettled(t, a)
+ if n := b.acquireCount(); n != 1 {
+ t.Fatalf("acquires %d inside the backoff, want 1", n)
+ }
+ })
+}
+
+// [Astra R3 1] Through the real Start: ten residents whose gates block
+// never put more than four jobs in flight, and the sweeper still stops
+// another entry whose lease is lost on its next sweep. Shutdown with a
+// 200 ms deadline returns within it, cancels the blocked gates, and nothing
+// starts after.
+func TestSlowResidentGateNeverStallsTheSweeper(t *testing.T) {
+ shrinkResidentPoll(t, 10*time.Millisecond)
+ a, b, _, _ := testActivator(t, 400*time.Millisecond)
+ a.gens = true
+ armRootfsForTest(a)
+ a.residentJitter = func() float64 { return 0 }
+ var routes []registry.Route
+ for i := 0; i < 10; i++ {
+ routes = append(routes, residentRoute(fmt.Sprintf("r%d.example.com", i)))
+ }
+ a.residentLister = &fakeResidents{routes: routes}
+ var inFlight, maxInFlight, ended atomic.Int64
+ b.startable = func(ctx context.Context, rt registry.Route) error {
+ n := inFlight.Add(1)
+ for {
+ m := maxInFlight.Load()
+ if n <= m || maxInFlight.CompareAndSwap(m, n) {
+ break
+ }
+ }
+ <-ctx.Done()
+ inFlight.Add(-1)
+ ended.Add(1)
+ return ctx.Err()
+ }
+ blog := testRoute("blog.example.com")
+ done, err := a.beginRequest(context.Background(), blog)
+ if err != nil {
+ t.Fatal(err)
+ }
+ done()
+ other := a.awakeEntry(blog.Host)
+ a.Start()
+ waitFor(t, "four blocked gates", func() bool { return inFlight.Load() == 4 })
+ lost := time.Now()
+ other.rep.(*fakeRep).setErr(errors.New("lease renewal failed"))
+ waitFor(t, "the lease-lost entry's stop", func() bool { return !a.hasEntry(blog.Host) })
+ if took := time.Since(lost); took > time.Second {
+ t.Fatalf("the sweeper took %s to stop a lost lease behind blocked resident gates", took)
+ }
+ a.mu.Lock()
+ why := other.stopWhy
+ a.mu.Unlock()
+ if why != StopLeaseLost {
+ t.Fatalf("stopped for %q, want StopLeaseLost", why)
+ }
+ time.Sleep(100 * time.Millisecond)
+ if m, s := maxInFlight.Load(), a.startingNow(); m > residentStartCeiling || s > residentStartCeiling {
+ t.Fatalf("%d gates in flight at most, %d reserved; want at most %d", m, s, residentStartCeiling)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
+ defer cancel()
+ began := time.Now()
+ a.Shutdown(ctx)
+ if took := time.Since(began); took > 300*time.Millisecond {
+ t.Fatalf("Shutdown took %s with a 200 ms deadline", took)
+ }
+ waitFor(t, "the blocked gates to end", func() bool { return inFlight.Load() == 0 && ended.Load() >= 4 })
+ waitFor(t, "the jobs to give back their reservations", func() bool { return a.startingNow() == 0 })
+ time.Sleep(50 * time.Millisecond)
+ if n := b.startCount(); n != 1 {
+ t.Fatalf("starts = %d, want only the binary request's", n)
+ }
+ for _, rt := range routes {
+ if a.hasEntry(rt.Host) {
+ t.Fatalf("%s has an entry after Shutdown", rt.Host)
+ }
+ }
+}
+
+// RACE: fifty requests for a cold resident while the tick runs every
+// millisecond: one lease, one start.
+func TestResidentRequestAndTickRaceOneWake(t *testing.T) {
+ shrinkResidentPoll(t, time.Millisecond)
+ host := "shop.example.com"
+ rt := residentRoute(host)
+ a, b, _, _, _, _ := residentService(t, time.Hour, rt)
+ a.Start()
+ var wg sync.WaitGroup
+ codes := make(chan int, 50)
+ for i := 0; i < 50; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ rec := httptest.NewRecorder()
+ a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler())
+ codes <- rec.Code
+ }()
+ }
+ wg.Wait()
+ close(codes)
+ for c := range codes {
+ if c != http.StatusOK {
+ t.Fatalf("a request answered %d", c)
+ }
+ }
+ time.Sleep(50 * time.Millisecond)
+ if a.awakeEntry(host) == nil {
+ t.Fatal("the resident is not awake")
+ }
+ if acq, st := b.acquireCount(), b.startCount(); acq != 1 || st != 1 {
+ t.Fatalf("acquires %d, starts %d; want one of each", acq, st)
+ }
+}
+
+// RACE: the process exits while a Bounce is stopping the entry: one stop,
+// counted as the bounce's (no failure), and one restart.
+func TestResidentCrashDuringStopIsOneStop(t *testing.T) {
+ host := "shop.example.com"
+ a, b, _, _, _, _ := residentService(t, time.Hour, residentRoute(host))
+ startResident(t, a, host)
+ proc := b.lastProc()
+ gate := make(chan struct{})
+ proc.setStopGate(gate)
+ if !a.Bounce(host) {
+ t.Fatal("Bounce did not stop the awake resident")
+ }
+ waitFor(t, "the bounce's Stop to begin", func() bool { return proc.stopEntered() == 1 })
+ var wg sync.WaitGroup
+ wg.Add(3)
+ go func() { defer wg.Done(); proc.exit() }()
+ for g := 0; g < 2; g++ {
+ go func() {
+ defer wg.Done()
+ for i := 0; i < 20; i++ {
+ a.rootfsTick()
+ }
+ }()
+ }
+ wg.Wait()
+ close(gate)
+ waitFor(t, "the stop", func() bool { return !a.hasEntry(host) })
+ if n := proc.stopEntered(); n != 1 {
+ t.Fatalf("the process was stopped %d times, want once", n)
+ }
+ if st, _ := a.residentOf(host); st.failures != 0 || st.restarts != 0 {
+ t.Fatalf("the exit during the bounce's stop counted: %+v", st)
+ }
+ startResident(t, a, host)
+ for i := 0; i < 5; i++ {
+ tickSettled(t, a)
+ }
+ if n := b.startCount(); n != 2 {
+ t.Fatalf("starts = %d, want 2 (one restart)", n)
+ }
+}
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index b975a44d0..67d1d09da 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -10,6 +10,9 @@ import (
"errors"
"fmt"
"log"
+ "math/rand/v2"
+ "slices"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/registry"
@@ -330,3 +333,365 @@ func syncRootfsPlaceholder(ctx context.Context, host string, rep Rep) {
log.Printf("activator: %s: first database placed; its first upload is not confirmed yet: %v", host, err)
}
}
+
+// ---- Residency (Plan 3 Task 8, spec §5.6) ---------------------------------
+//
+// A resident is an always-awake rootfs instance (registry.Route.Resident):
+// the activator starts it at boot with no request, restarts it after a
+// crash or a lost lease with a backoff, never stops it for idleness, and
+// starts at most residentStartCeiling of them at a time. What stops one,
+// and nothing else does: its row going away (RetireExcept), a fence, a lost
+// lease (restarted under a fresh lease after the backoff), the agent's
+// shutdown, and the stops it restarts from (a crash, a release cycle, a
+// bounce). Every start goes through the same admission as a request's
+// (rootfsRefusalLocked, then the backend's gates through
+// rootfsStartRefusal) and the same wake (wake, doWake): there is no
+// second gate.
+
+// ResidentLister lists the resident instances this box carries.
+// *registry.Registry satisfies it. New reads it from the DueStore: a
+// DueStore without it (a test double) has no residents.
+type ResidentLister interface {
+ ResidentInstances() ([]registry.Route, error)
+}
+
+// residentPoll is the resident tick's period: a crash is seen, and a
+// resident due a start is started, within it. A var so tests can shrink it.
+var residentPoll = 2 * time.Second
+
+// residentStartCeiling bounds the proactive starts in flight on a box, gate
+// checks and wakes together: each takes a lease and restores a database.
+const residentStartCeiling = 4
+
+// residentHealthyRun is how long a resident must have run for its exit to
+// count as the first failure again (the backoff resets).
+const residentHealthyRun = 60 * time.Second
+
+// residentBackoff is the delay before a resident's next start after its
+// failures-th failure in a row: 1, 2, 4, 8, 16, 32 seconds, then 60, times
+// (1 + jitter), jitter in [0, 0.2) (clamped into it).
+func residentBackoff(failures int, jitter float64) time.Duration {
+ d := 60 * time.Second
+ if failures < 1 {
+ failures = 1
+ }
+ if failures <= 6 {
+ d = time.Second << (failures - 1)
+ }
+ if jitter < 0 {
+ jitter = 0
+ }
+ if jitter > 0.2 {
+ jitter = 0.2
+ }
+ return time.Duration(float64(d) * (1 + jitter))
+}
+
+// defaultResidentJitter is residentBackoff's jitter in production.
+func defaultResidentJitter() float64 { return rand.Float64() * 0.2 }
+
+// residentState is the Service's view of one resident, by host, under a.mu.
+type residentState struct {
+ failures int // failures in a row (residentFailure, a crash, a lost lease)
+ retryAt time.Time // no start, proactive or by request, before it
+ starting bool // a proactive wake of this host is in flight
+ restarts int // restarts after a crash or a lost lease
+ refused string // the current refusal's text, "" when none: logged once per change
+}
+
+// errResidentBackoff is begin's answer for a resident inside its backoff:
+// a request never starts what the backoff holds back. serveWakeError
+// answers it 503 with Retry-After.
+type errResidentBackoff struct{ retryAfter time.Duration }
+
+func (e *errResidentBackoff) Error() string {
+ return fmt.Sprintf("activator: the resident instance is backing off after a failed start; next start in %s", e.retryAfter)
+}
+
+// retryAfterSeconds is d in whole seconds, rounded up, at least 1.
+func retryAfterSeconds(d time.Duration) int {
+ s := int((d + time.Second - 1) / time.Second)
+ if s < 1 {
+ s = 1
+ }
+ return s
+}
+
+// residentFailure reports whether a resident's failed wake counts toward its
+// backoff. Never for an ownership end or a refusal (INV-4): a fence
+// (ErrFenced), the agent shutting down, a cancelled wake, anything verdictOf
+// reads as gateNoOwnership or superseded (every rootfs refusal, a lost
+// lease), another generation operation in flight (errSwapBusy), or a host
+// latched by an unproven earlier wake (errWakeUnproven, which holds the host
+// until its record is proven; a backoff would only add to it). The build's
+// own failures (a health failure, a crash at start) and anything
+// unclassified (an Acquire failing on a store outage) count, so a store
+// outage backs off instead of retrying every tick. Group R extends it
+// through classifyRelease.
+func residentFailure(err error) bool {
+ switch {
+ case err == nil:
+ return false
+ case errors.Is(err, ErrFenced), errors.Is(err, errShuttingDown), errors.Is(err, context.Canceled),
+ errors.Is(err, errSwapBusy), errors.Is(err, errWakeUnproven):
+ return false
+ }
+ switch verdictOf(err) {
+ case gateNoOwnership, gateSuperseded:
+ return false
+ }
+ return true
+}
+
+// residentLocked is host's state, made on first use. The caller holds a.mu.
+func (a *Service) residentLocked(host string) *residentState {
+ st := a.residents[host]
+ if st == nil {
+ if a.residents == nil {
+ a.residents = map[string]*residentState{}
+ }
+ st = &residentState{}
+ a.residents[host] = st
+ }
+ return st
+}
+
+// residentDelayLocked is how long host's backoff still holds a start back,
+// 0 for none. The caller holds a.mu.
+func (a *Service) residentDelayLocked(host string) time.Duration {
+ st := a.residents[host]
+ if st == nil {
+ return 0
+ }
+ if d := st.retryAt.Sub(a.now()); d > 0 {
+ return d
+ }
+ return 0
+}
+
+// residentJitterLocked is the configured jitter, or production's.
+func (a *Service) residentJitterLocked() float64 {
+ if a.residentJitter != nil {
+ return a.residentJitter()
+ }
+ return defaultResidentJitter()
+}
+
+// residentHeldLocked reports why host may not start now beside what the
+// backoff says: a fence, a live entry, or an uncertainty latch (a failed
+// wake or a legacy sidecar not proven stopped; Group R adds its release
+// record). The caller holds a.mu.
+func (a *Service) residentHeldLocked(rt registry.Route) bool {
+ if a.fences[rt.Host] != 0 || a.entries[rt.Host] != nil {
+ return true
+ }
+ if _, latched := a.unprovenWakes[rt.Host]; latched || len(a.straySidecars[rt.Host]) > 0 {
+ return true
+ }
+ return a.disabled(rt)
+}
+
+// residentShaped reports whether rt is a row the tick may start: an
+// instance with a runtime that does not hibernate. A rootfs-v1 row is a
+// resident; any other runtime is refused by rootfsRefusalLocked, so it is
+// reported and never started.
+func residentShaped(rt registry.Route) bool {
+ return rt.Kind == "instance" && !rt.Hibernate && rt.Runtime != ""
+}
+
+// noteResidentRefusalLocked records a refusal of a resident's admission: it
+// counts no failure and moves no retry time. One log line per change of
+// its text, and for unarmed one member event (RFS-3-C12 with RFS-3-C14),
+// through noteRootfsRefusal, which a request's refusal shares. The caller
+// holds a.mu (noteRootfsRefusal takes only the leaf rootfsGateMu).
+func (a *Service) noteResidentRefusalLocked(rt registry.Route, st *residentState, err error) {
+ msg := err.Error()
+ if st.refused == msg {
+ return
+ }
+ st.refused = msg
+ a.noteRootfsRefusal(rt, err)
+}
+
+// unreserveResidentLocked gives back a proactive start's reservation: the
+// job's own state and its slot under the ceiling. The caller holds a.mu.
+func (a *Service) unreserveResidentLocked(st *residentState) {
+ st.starting = false
+ a.residentStarting--
+}
+
+// rootfsTick is the resident tick, on its own residentPoll ticker in the
+// sweeper goroutine (Start), so Shutdown's stop of the sweeper stops it. It
+// reserves and never does a gate's I/O: every awake entry depends on the
+// sweeper's lease check, and Shutdown waits for the sweeper before it stops
+// anything [Astra R3 1]. The one read it makes, the listing, is off a.mu.
+//
+// 1. The listing. An error logs and ends the tick: it is never read as "no
+// residents", so nothing is stopped and nothing forgotten.
+// 2. Every awake rootfs entry whose process exited is stopped as the
+// sweep's crash arm stops one (StopExited), so a crash is seen within
+// residentPoll rather than the sweep's 30 s; then
+// superviseRootfsLocked for every awake rootfs entry.
+// 3. A host no longer listed is forgotten. Each listed row, in host
+// order, not held (residentHeldLocked), not starting, past its retry
+// time, under the ceiling, and admitted by rootfsRefusalLocked is
+// reserved and handed to residentJob.
+func (a *Service) rootfsTick() {
+ var routes []registry.Route
+ if a.residentLister != nil {
+ var err error
+ if routes, err = a.residentLister.ResidentInstances(); err != nil {
+ log.Printf("activator: resident instances: %v; nothing stopped or forgotten this tick", err)
+ return
+ }
+ }
+ slices.SortFunc(routes, func(x, y registry.Route) int { return strings.Compare(x.Host, y.Host) })
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ if a.shuttingDown {
+ return
+ }
+ for _, e := range a.entries {
+ if !e.route.Rootfs() || e.state != actAwake || e.probeHeld || e.workerRespawning || a.fences[e.host] != 0 {
+ continue
+ }
+ if e.proc != nil && e.proc.Exited() {
+ log.Printf("activator: rootfs instance %s exited; stopping it", e.host)
+ // Not an intentional stop: a first wake's observation reads it
+ // as the build's failure (spec §6.4), as the sweep's arm does.
+ e.unexpectedExit = true
+ a.beginStopLocked(e, StopExited)
+ continue
+ }
+ a.superviseRootfsLocked(e)
+ }
+ listed := make(map[string]bool, len(routes))
+ for _, rt := range routes {
+ listed[rt.Host] = true
+ }
+ for host := range a.residents {
+ if !listed[host] {
+ delete(a.residents, host)
+ }
+ }
+ now := a.now()
+ for _, rt := range routes {
+ if !residentShaped(rt) {
+ continue
+ }
+ st := a.residentLocked(rt.Host)
+ if a.residentHeldLocked(rt) || st.starting || now.Before(st.retryAt) {
+ continue
+ }
+ if a.residentStarting >= residentStartCeiling {
+ break
+ }
+ if err := a.rootfsRefusalLocked(rt); err != nil {
+ a.noteResidentRefusalLocked(rt, st, notAdmitted(err))
+ continue
+ }
+ st.starting = true
+ a.residentStarting++
+ go a.residentJob(a.lifeCtx, rt, st)
+ }
+}
+
+// residentJob is one reserved proactive start, off the sweeper: the
+// admission's gates (rootfsStartRefusal) under ctx, the Service's
+// lifetime, so a blocked readiness ask or owner read ends when Shutdown
+// begins; then, under a.mu, admission is checked again from the top before
+// anything is published: st still this host's and reserved, not shutting
+// down, not held (a fence, a live entry, a latch, turned off), and
+// rootfsRefusalLocked. A refusal clears the reservation and counts no
+// failure. Otherwise the job publishes a waking entry marked resident and
+// runs the ordinary wake, whose outcome gives the reservation back
+// (noteResidentWakeLocked). Shutdown does not wait for a job still in its
+// gates: its re-check finds a.shuttingDown and starts nothing.
+func (a *Service) residentJob(ctx context.Context, rt registry.Route, st *residentState) {
+ err := a.rootfsStartRefusal(ctx, rt)
+ a.mu.Lock()
+ if a.residents[rt.Host] != st || !st.starting || a.shuttingDown || a.residentHeldLocked(rt) {
+ a.unreserveResidentLocked(st)
+ a.mu.Unlock()
+ return
+ }
+ if err == nil {
+ err = notAdmitted(a.rootfsRefusalLocked(rt))
+ }
+ if err != nil {
+ a.unreserveResidentLocked(st)
+ if errors.Is(err, errRootfsNotAdmitted) {
+ a.noteResidentRefusalLocked(rt, st, err)
+ }
+ a.mu.Unlock()
+ return
+ }
+ st.refused = ""
+ // The gates just passed for this very row: doWake asks only the locked
+ // half again (rootfsWakeRefusal), as for a request begin admitted.
+ e := &actEntry{host: rt.Host, route: rt, state: actWaking, ready: make(chan struct{}), resident: true,
+ rootfsAdmittedKey: rootfsGateKey(rt)}
+ a.entries[rt.Host] = e
+ a.mu.Unlock()
+ log.Printf("activator: %s: always-on rootfs instance is not running; starting it", rt.Host)
+ a.wake(e)
+}
+
+// superviseRootfsLocked is the resident tick's supervision hook for an awake
+// rootfs entry. A no-op in group A; W1 fills it with worker supervision.
+func (a *Service) superviseRootfsLocked(e *actEntry) {}
+
+// noteResidentWakeLocked is a wake's outcome for residency, in wake's final
+// critical section. A proactive wake (e.resident) gives back its
+// reservation. For any wake of a resident row, proactive or by request, a
+// failure counts only when residentFailure says so: failures++ and the
+// backoff. Anything else (a refusal, an ownership end) sets the retry time
+// to now and counts nothing [Astra R1 11]. The caller holds a.mu.
+func (a *Service) noteResidentWakeLocked(e *actEntry, err error) {
+ if e.resident {
+ a.residentStarting--
+ if st := a.residents[e.host]; st != nil {
+ st.starting = false
+ }
+ }
+ if err == nil || !e.route.Resident() {
+ return
+ }
+ st := a.residentLocked(e.host)
+ now := a.now()
+ if !residentFailure(err) {
+ st.retryAt = now
+ return
+ }
+ st.failures++
+ st.retryAt = now.Add(residentBackoff(st.failures, a.residentJitterLocked()))
+}
+
+// noteResidentStopLocked is a stop's outcome for residency, in finishStop as
+// the entry is forgotten. A crash (StopExited) or a lost lease
+// (StopLeaseLost) is a failure: a run of residentHealthyRun or more resets
+// the count first; then failures++, restarts++, the backoff, and the
+// member's event (RFS-3-C11) with the delay. Any other reason (a release
+// cycle, a bounce, retirement, a fence, shutdown) sets the retry time to
+// now and counts nothing: a resident is back on the next tick after an
+// adoption or a carlos restart. The caller holds a.mu.
+func (a *Service) noteResidentStopLocked(e *actEntry) {
+ if !e.route.Resident() {
+ return
+ }
+ st := a.residentLocked(e.host)
+ now := a.now()
+ if e.stopWhy != StopExited && e.stopWhy != StopLeaseLost {
+ st.retryAt = now
+ return
+ }
+ if now.Sub(e.spawnedAt) >= residentHealthyRun {
+ st.failures = 0
+ }
+ st.failures++
+ st.restarts++
+ delay := residentBackoff(st.failures, a.residentJitterLocked())
+ st.retryAt = now.Add(delay)
+ wait := time.Duration(retryAfterSeconds(delay)) * time.Second
+ emitEvent(a.Logs, e.route, "error", fmt.Sprintf(rolloutwords.EventResidentExited, wait.String()))
+}
diff --git a/internal/rolloutwords/words.go b/internal/rolloutwords/words.go
index 58313fe4e..c5860fded 100644
--- a/internal/rolloutwords/words.go
+++ b/internal/rolloutwords/words.go
@@ -77,6 +77,11 @@ const (
RootfsRefusedUnarmed = "overlap swaps are not armed here" // RFS-3-C14, fills RFS-3-C12
)
+// The resident restart event (rootfs apps Plan 3 Task 8), approved in the
+// same deck: an always-on rootfs instance whose process exited or lost its
+// lease, filled with the delay before it is started again.
+const EventResidentExited = "instance exited. starting it again in %s" // RFS-3-C11
+
// States: the REASON column of `carlos instances list` (spec §9.1).
const (
StateHeld = "held: build %s failed on this box"