activator: a resident is watched on its lease's own signal and killed at loss; fair resident ticks; retirement ends a pending admission; ownership refusals paced apart from failures (Task 8 round 1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
5 files changed,
+733
−19
internal/activator/activator.go+37 −0internal/activator/activator_test.go+8 −0internal/activator/rootfs_resident_lease_test.go+384 −0internal/activator/rootfs_service.go+295 −19internal/activator/swap.go+9 −0
diff --git a/internal/activator/activator.go b/internal/activator/activator.go| index 6af0ac598..e699e2623 100644 |
| --- a/internal/activator/activator.go |
| +++ b/internal/activator/activator.go |
| @@ -480,6 +480,10 @@ type actEntry struct { |
| // wake goroutine starts; never written again. A request's wake of a |
| // resident row leaves it false. |
| resident bool |
| + // ownerDone ends a resident's lease watch (watchResidentLeaseLocked, |
| + // Astra Task 8 R1 1): made at the awake transition, closed by |
| + // finishStop as the entry is forgotten. Under a.mu. |
| + ownerDone chan struct{} |
| // 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. |
| @@ -1322,6 +1326,12 @@ type Service struct { |
| residents map[string]*residentState |
| residentStarting int |
| residentJitter func() float64 |
| + // residentCursor is the host the tick last reserved: the next tick |
| + // begins after it (residentOrderLocked). Under a.mu. |
| + residentCursor string |
| + // residentGatesPassed, when set, is called by a resident job as its |
| + // gates return, before its re-check: a test seam (nil in production). |
| + residentGatesPassed func(host string) |
| // 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. |
| @@ -2069,6 +2079,11 @@ func (a *Service) wake(e *actEntry) { |
| e.bounceAfterWake = false |
| a.bounceLocked(e) |
| } |
| + if e.state == actAwake && e.route.Resident() { |
| + // A resident's lease is watched on its own signal from here, |
| + // not only by the idle sweep (Astra Task 8 R1 1). |
| + a.watchResidentLeaseLocked(e) |
| + } |
| if a.OnWake != nil && e.state == actAwake { |
| // Fire-and-forget, off this goroutine: e.route is read once here, |
| // before this goroutine can be reused for anything else — the |
| @@ -2297,6 +2312,15 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| // come through begin's own ask: due wakes, planned and pinned wakes, |
| // workers and probes. The refusal holds no lease, so nothing waits on a |
| // TTL. Plan 2's gates still run inside Start as the second line. |
| + // 0.35. A proactive resident wake (Plan 3 Task 8, Astra R1 3) runs only |
| + // while the row just read is still one the resident listing returns: a |
| + // retirement, a hold or a move that landed while its admission was |
| + // pending takes nothing. |
| + if e.resident { |
| + if err := residentRunnable(rt); err != nil { |
| + return w, notAdmitted(err) |
| + } |
| + } |
| if err := a.rootfsWakeRefusal(ctx, e, rt); err != nil { |
| return w, err |
| } |
| @@ -2379,6 +2403,11 @@ func (a *Service) doWake(ctx context.Context, e *actEntry) (*wokenInstance, erro |
| return w, err |
| } |
| } |
| + if e.resident { |
| + if err := residentRunnable(rt); err != nil { |
| + return w, notAdmitted(err) |
| + } |
| + } |
| } |
| } |
| @@ -4603,6 +4632,10 @@ func (a *Service) finishStop(e *actEntry, outcome *stopObservation) { |
| // 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) |
| + if e.ownerDone != nil { |
| + close(e.ownerDone) |
| + e.ownerDone = nil |
| + } |
| 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 |
| @@ -5363,6 +5396,10 @@ func (a *Service) RetireExcept(keep map[string]bool) { |
| // Already on its way out. |
| } |
| } |
| + // A resident's pending admission ends with its retirement too (Plan 3 |
| + // Task 8, Astra R1 3): a job still in its gates finds its reservation |
| + // gone and starts nothing. |
| + a.forgetResidentsLocked(keep) |
| a.mu.Unlock() |
| for _, e := range waking { |
| go func(e *actEntry) { |
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go| index 939448dd6..21b7fde52 100644 |
| --- a/internal/activator/activator_test.go |
| +++ b/internal/activator/activator_test.go |
| @@ -266,7 +266,11 @@ func (l *fakeLease) Replicate(_ context.Context, _ string, syncInterval time.Dur |
| if l.b != nil { |
| l.b.mu.Lock() |
| l.b.syncIntervals = append(l.b.syncIntervals, syncInterval) |
| + wrap := l.b.repWrap |
| l.b.mu.Unlock() |
| + if wrap != nil { |
| + return wrap(l.rep), nil |
| + } |
| } |
| return l.rep, nil |
| } |
| @@ -516,6 +520,10 @@ type fakeBackend struct { |
| startableAsks map[string]int |
| placeholders int |
| placeErr error |
| + |
| + // repWrap, when set, wraps the replica each lease's Replicate hands |
| + // back (Plan 3 Task 8: a replica with the lease's own loss signal). |
| + repWrap func(*fakeRep) Rep |
| } |
| // Layout is fakeBackend's Classifier implementation, always present so |
diff --git a/internal/activator/rootfs_resident_lease_test.go b/internal/activator/rootfs_resident_lease_test.go| new file mode 100644 |
| index 000000000..0df7f7c9d |
| --- /dev/null |
| +++ b/internal/activator/rootfs_resident_lease_test.go |
| @@ -0,0 +1,384 @@ |
| +package activator |
| + |
| +// Rootfs apps Plan 3 Task 8, Astra round 1: a resident's lease watched on |
| +// the lease's own signal (P1 1, C7), fairness across ticks (P1 2), a |
| +// retirement ending a pending admission (P1 3), the backoff re-checked |
| +// before publishing (P2 4) and ownership refusals paced apart from the |
| +// build's failures (P2 5). Not parallel: residentPoll and |
| +// residentDrainBudget are package vars. |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "path/filepath" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/lease" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +// ownedRep is a replica with the lease's own signal (*lease.Replicator's |
| +// Lost and SafeUntil): until is the safety deadline the last renewal set; |
| +// at it, or at lose, Lost closes and every read answers the loss. Err is |
| +// the embedded fakeRep's, which lose sets too. |
| +type ownedRep struct { |
| + *fakeRep |
| + mu sync.Mutex |
| + until time.Time |
| + err error |
| + lost chan struct{} |
| + timer *time.Timer |
| +} |
| + |
| +func newOwnedRep(r *fakeRep, until time.Time) *ownedRep { |
| + o := &ownedRep{fakeRep: r, until: until, lost: make(chan struct{})} |
| + o.timer = time.AfterFunc(time.Until(until), func() { o.lose(lease.ErrLost) }) |
| + return o |
| +} |
| + |
| +func (o *ownedRep) Lost() <-chan struct{} { return o.lost } |
| + |
| +func (o *ownedRep) SafeUntil() (time.Time, error) { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + if o.err != nil { |
| + return time.Time{}, o.err |
| + } |
| + return o.until, nil |
| +} |
| + |
| +// lose latches the loss once, as the renewer does. |
| +func (o *ownedRep) lose(err error) { |
| + o.mu.Lock() |
| + defer o.mu.Unlock() |
| + if o.err != nil { |
| + return |
| + } |
| + o.err = err |
| + o.fakeRep.setErr(err) |
| + close(o.lost) |
| +} |
| + |
| +// killBackend is fakeBackend with the generation kill (genKiller): each |
| +// call is counted with its time, and onKill models what a kill does to the |
| +// process. |
| +type killBackend struct { |
| + *fakeBackend |
| + kmu sync.Mutex |
| + kills []time.Time |
| + onKill func(n uint64) |
| +} |
| + |
| +func (k *killBackend) KillGen(_ context.Context, _ registry.Route, n uint64) error { |
| + k.kmu.Lock() |
| + k.kills = append(k.kills, time.Now()) |
| + hook := k.onKill |
| + k.kmu.Unlock() |
| + k.record(fmt.Sprintf("kill:%d", n)) |
| + if hook != nil { |
| + hook(n) |
| + } |
| + return nil |
| +} |
| + |
| +func (k *killBackend) killTimes() []time.Time { |
| + k.kmu.Lock() |
| + defer k.kmu.Unlock() |
| + return append([]time.Time(nil), k.kills...) |
| +} |
| + |
| +// residentKillService is residentService over a killBackend. |
| +func residentKillService(t *testing.T, routes ...registry.Route) (*Service, *killBackend, *fakeClock, *fakeResidents) { |
| + t.Helper() |
| + kb := &killBackend{fakeBackend: &fakeBackend{}} |
| + clk := &fakeClock{t: time.Unix(1_700_000_000, 0)} |
| + reg, err := registry.Open(filepath.Join(t.TempDir(), "registry.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := New(Config{Bucket: "test-bucket", Idle: time.Hour}, kb, reg) |
| + a.now = clk.now |
| + a.gens = true |
| + armRootfsForTest(a) |
| + a.residentJitter = func() float64 { return 0 } |
| + l := &fakeResidents{routes: routes} |
| + a.residentLister = l |
| + t.Cleanup(func() { a.Shutdown(context.Background()) }) |
| + return a, kb, clk, l |
| +} |
| + |
| +func shrinkDrainBudget(t *testing.T, d time.Duration) { |
| + t.Helper() |
| + old := residentDrainBudget |
| + residentDrainBudget = d |
| + t.Cleanup(func() { residentDrainBudget = old }) |
| +} |
| + |
| +func indexWithPrefix(events []string, prefix string) int { |
| + for i, ev := range events { |
| + if len(ev) >= len(prefix) && ev[:len(prefix)] == prefix { |
| + return i |
| + } |
| + } |
| + return -1 |
| +} |
| + |
| +// [Astra R1 1, C7] A renewal that hangs: the safety deadline the last |
| +// renewal set comes 600 ms later, and the idle sweep (every 30 s at this |
| +// idle window) will not run before it. The watch begins a graceful stop |
| +// while the drain budget still fits; the drain hangs; at the deadline the |
| +// generation is killed and proven gone, and only then is the lease given |
| +// back. Nothing waited for the sweep. |
| +func TestResidentLeaseHangStopsBeforeTheDeadline(t *testing.T) { |
| + shrinkResidentPoll(t, 10*time.Millisecond) |
| + shrinkDrainBudget(t, 200*time.Millisecond) |
| + host := "shop.example.com" |
| + a, kb, _, _ := residentKillService(t, residentRoute(host)) |
| + deadline := time.Now().Add(600 * time.Millisecond) |
| + var rep *ownedRep |
| + kb.mu.Lock() |
| + kb.repWrap = func(r *fakeRep) Rep { |
| + r.setOnClose(func() { kb.record("close") }) |
| + rep = newOwnedRep(r, deadline) |
| + return rep |
| + } |
| + kb.mu.Unlock() |
| + a.Start() |
| + waitFor(t, "the boot start", func() bool { return a.awakeEntry(host) != nil }) |
| + e := a.awakeEntry(host) |
| + proc := kb.lastProc() |
| + drain := make(chan struct{}) // a SIGTERM drain that never finishes on its own |
| + stopBegan := make(chan time.Time, 1) |
| + proc.mu.Lock() |
| + proc.stopGate = drain |
| + proc.onStopEnter = func() { stopBegan <- time.Now() } |
| + proc.mu.Unlock() |
| + var killOnce sync.Once |
| + kb.kmu.Lock() |
| + kb.onKill = func(uint64) { killOnce.Do(func() { proc.exit(); close(drain) }) } // SIGKILL ends the drain |
| + kb.kmu.Unlock() |
| + |
| + var began time.Time |
| + select { |
| + case began = <-stopBegan: |
| + case <-time.After(2 * time.Second): |
| + t.Fatal("no stop began before the lease's safety deadline") |
| + } |
| + if !began.Before(deadline) { |
| + t.Fatalf("the stop began %s after the safety deadline", began.Sub(deadline)) |
| + } |
| + waitFor(t, "the kill", func() bool { return len(kb.killTimes()) > 0 }) |
| + killed := kb.killTimes()[0] |
| + if killed.Before(deadline.Add(-50*time.Millisecond)) || killed.After(deadline.Add(time.Second)) { |
| + t.Fatalf("killed %s from the deadline; want at the loss, well inside the 5 s margin", killed.Sub(deadline)) |
| + } |
| + waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(host) }) |
| + ev := kb.events() |
| + if k, c := indexWithPrefix(ev, "kill:"), indexWithPrefix(ev, "close"); k < 0 || c < 0 || c < k { |
| + t.Fatalf("order %v: the lease was given back before the kill proved the generation gone", ev) |
| + } |
| + a.mu.Lock() |
| + why := e.stopWhy |
| + a.mu.Unlock() |
| + if why != StopLeaseLost { |
| + t.Fatalf("stopped for %q, want StopLeaseLost", why) |
| + } |
| + if !rep.isClosed() { |
| + t.Fatal("the replica was never closed") |
| + } |
| +} |
| + |
| +// A renewal that fails outright (another box took the lock) with time left |
| +// on the deadline: the generation is killed at once, without waiting for a |
| +// drain. |
| +func TestResidentLeaseLossKillsAtOnce(t *testing.T) { |
| + host := "shop.example.com" |
| + a, kb, _, _ := residentKillService(t, residentRoute(host)) |
| + var rep *ownedRep |
| + kb.mu.Lock() |
| + kb.repWrap = func(r *fakeRep) Rep { rep = newOwnedRep(r, time.Now().Add(time.Hour)); return rep } |
| + kb.mu.Unlock() |
| + startResident(t, a, host) |
| + proc := kb.lastProc() |
| + drain := make(chan struct{}) |
| + proc.setStopGate(drain) |
| + kb.kmu.Lock() |
| + kb.onKill = func(uint64) { proc.exit() } |
| + kb.kmu.Unlock() |
| + lostAt := time.Now() |
| + rep.lose(errors.New("renew: the lock was taken")) |
| + waitFor(t, "the kill", func() bool { return len(kb.killTimes()) > 0 }) |
| + if d := kb.killTimes()[0].Sub(lostAt); d > time.Second { |
| + t.Fatalf("killed %s after the loss", d) |
| + } |
| + if proc.stopCalls() != 0 { |
| + t.Fatal("the drain finished before the kill: the kill did not wait for nothing") |
| + } |
| + close(drain) |
| + waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(host) }) |
| + if st, _ := a.residentOf(host); st.failures != 1 { |
| + t.Fatalf("a lost lease: %+v, want one failure", st) |
| + } |
| +} |
| + |
| +// A replica without the lease's signal: the tick's own rep.Err check stops |
| +// the resident and kills its generation within one tick. |
| +func TestResidentTickCatchesALostLease(t *testing.T) { |
| + host := "shop.example.com" |
| + a, kb, _, _ := residentKillService(t, residentRoute(host)) |
| + e := startResident(t, a, host) |
| + e.rep.(*fakeRep).setErr(errors.New("lease renewal failed")) |
| + a.rootfsTick() |
| + waitFor(t, "the kill", func() bool { return len(kb.killTimes()) > 0 }) |
| + waitFor(t, "the stop", func() bool { return !a.hasEntry(host) }) |
| + a.mu.Lock() |
| + why := e.stopWhy |
| + a.mu.Unlock() |
| + if why != StopLeaseLost { |
| + t.Fatalf("stopped for %q", why) |
| + } |
| +} |
| + |
| +// [Astra R1 2] Four residents refused every time ahead of an admissible |
| +// fifth: the fifth starts within a few ticks. |
| +func TestResidentRefusalsDoNotStarveLaterHosts(t *testing.T) { |
| + var routes []registry.Route |
| + for i := 0; i < 5; i++ { |
| + routes = append(routes, residentRoute(fmt.Sprintf("r%d.example.com", i))) |
| + } |
| + a, b, _, _, _, _ := residentService(t, time.Hour, routes...) |
| + b.mu.Lock() |
| + b.startable = func(_ context.Context, rt registry.Route) error { |
| + if rt.Host != "r4.example.com" { |
| + return refuseRootfs(errors.New("this box is shared")) |
| + } |
| + return nil |
| + } |
| + b.mu.Unlock() |
| + for i := 0; i < 3; i++ { |
| + tickSettled(t, a) |
| + } |
| + if a.awakeEntry("r4.example.com") == nil { |
| + t.Fatal("four refused residents starved the fifth") |
| + } |
| + for i := 0; i < 4; i++ { |
| + if st, _ := a.residentOf(fmt.Sprintf("r%d.example.com", i)); st.failures != 0 || st.refused == "" { |
| + t.Fatalf("r%d: %+v, want a refusal and no failure", i, st) |
| + } |
| + } |
| +} |
| + |
| +// [Astra R1 3] A retirement while a resident's gate is blocked: the job |
| +// finds its reservation gone and starts nothing. |
| +func TestRetirementEndsAPendingResidentAdmission(t *testing.T) { |
| + host := "shop.example.com" |
| + a, b, _, _, _, _ := residentService(t, time.Hour, residentRoute(host)) |
| + entered := make(chan struct{}) |
| + release := make(chan struct{}) |
| + var once sync.Once |
| + b.mu.Lock() |
| + b.startable = func(context.Context, registry.Route) error { |
| + once.Do(func() { close(entered) }) |
| + <-release |
| + return nil |
| + } |
| + b.mu.Unlock() |
| + a.rootfsTick() |
| + <-entered |
| + a.RetireExcept(map[string]bool{}) |
| + close(release) |
| + waitFor(t, "the job to give back its reservation", func() bool { return a.startingNow() == 0 }) |
| + if a.hasEntry(host) || b.acquireCount() != 0 || b.startCount() != 0 { |
| + t.Fatalf("a retired resident's pending admission started it (acquires %d)", b.acquireCount()) |
| + } |
| +} |
| + |
| +// [Astra R1 3] The wake reads the row again before the lease: a row no |
| +// longer runnable (a move holds it) takes nothing and counts nothing. |
| +func TestResidentWakeRereadsTheRowBeforeTheLease(t *testing.T) { |
| + host := "shop.example.com" |
| + rt := residentRoute(host) |
| + a, b, _, _, _, _ := residentService(t, time.Hour, rt) |
| + moving := rt |
| + moving.Status = "moving" |
| + a.Routes = &routeTable{rows: map[string]registry.Route{host: moving}} |
| + tickSettled(t, a) |
| + if a.hasEntry(host) || b.acquireCount() != 0 { |
| + t.Fatalf("a row no longer runnable was woken (acquires %d)", b.acquireCount()) |
| + } |
| + if st, _ := a.residentOf(host); st.failures != 0 { |
| + t.Fatalf("a row no longer runnable counted a failure: %+v", st) |
| + } |
| + if err := residentRunnable(rt); err != nil { |
| + t.Fatalf("the listing's row: %v", err) |
| + } |
| +} |
| + |
| +// [Astra R1 4] A request's wake fails while a reserved job is past its |
| +// gates: the backoff it set holds the job back. |
| +func TestResidentJobHonoursABackoffSetMeanwhile(t *testing.T) { |
| + host := "shop.example.com" |
| + rt := residentRoute(host) |
| + a, b, clk, _, _, _ := residentService(t, time.Hour, rt) |
| + passed := make(chan struct{}) |
| + resume := make(chan struct{}) |
| + var once sync.Once |
| + a.residentGatesPassed = func(string) { |
| + once.Do(func() { close(passed); <-resume }) |
| + } |
| + b.mu.Lock() |
| + b.startErr = errors.New("health: socket never accepted") |
| + b.mu.Unlock() |
| + a.rootfsTick() |
| + <-passed |
| + rec := httptest.NewRecorder() |
| + a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler()) |
| + if rec.Code != http.StatusServiceUnavailable { |
| + t.Fatalf("the failing request: %d", rec.Code) |
| + } |
| + if st, _ := a.residentOf(host); st.failures != 1 || !st.retryAt.After(clk.now()) { |
| + t.Fatalf("after the failed request %+v, want a backoff", st) |
| + } |
| + close(resume) |
| + waitFor(t, "the job to give back its reservation", func() bool { return a.startingNow() == 0 }) |
| + if n := b.startCount(); n != 1 || a.hasEntry(host) { |
| + t.Fatalf("starts = %d: the reserved job ignored the backoff the request's failure set", n) |
| + } |
| +} |
| + |
| +// [Astra R1 5] A held lease and refused config are refusals (verdictOf, |
| +// residentFailure); a held lease paces the tick by its own retry-after and |
| +// counts nothing, and a request is not held back by that pacing. |
| +func TestResidentOwnershipRefusalsArePacedNotCounted(t *testing.T) { |
| + for _, err := range []error{&errLeaseHeld{holder: "box-b", retryAfter: 10 * time.Second}, &errConfigRefused{err: errors.New("no key")}} { |
| + if v := verdictOf(fmt.Errorf("x: %w", err)); v != gateNoOwnership { |
| + t.Errorf("%T: verdictOf = %d, want gateNoOwnership", err, v) |
| + } |
| + if residentFailure(fmt.Errorf("x: %w", err)) { |
| + t.Errorf("%T: residentFailure = true", err) |
| + } |
| + } |
| + host := "shop.example.com" |
| + a, b, clk, _, _, _ := residentService(t, time.Hour, residentRoute(host)) |
| + b.mu.Lock() |
| + b.acquireErr = &errLeaseHeld{holder: "box-b", retryAfter: 10 * time.Second} |
| + b.mu.Unlock() |
| + tickSettled(t, a) |
| + tickSettled(t, a) |
| + if st, _ := a.residentOf(host); st.failures != 0 || b.acquireCount() != 1 { |
| + t.Fatalf("a held lease: %+v, acquires %d; want no failure and one ask", st, b.acquireCount()) |
| + } |
| + if _, err := a.beginRequest(context.Background(), residentRoute(host)); err == nil || errors.As(err, new(*errResidentBackoff)) { |
| + t.Fatalf("a request under ownership pacing: %v, want the lease's own answer", err) |
| + } |
| + clk.advance(10 * time.Second) |
| + b.mu.Lock() |
| + b.acquireErr = nil |
| + b.mu.Unlock() |
| + startResident(t, a, host) |
| +} |
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go| index 67d1d09da..409e6c7fd 100644 |
| --- a/internal/activator/rootfs_service.go |
| +++ b/internal/activator/rootfs_service.go |
| @@ -13,8 +13,11 @@ import ( |
| "math/rand/v2" |
| "slices" |
| "strings" |
| + "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/instancectl" |
| + "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/registry" |
| "github.com/carlosframework/platform/internal/rolloutwords" |
| ) |
| @@ -397,6 +400,12 @@ type residentState struct { |
| 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 |
| + // waitUntil is ownership pacing, kept apart from the build's backoff |
| + // [Astra Task 8 R1 5]: a lease another holder still has, or config this |
| + // box cannot provide yet, is no failure of the build, so it counts |
| + // nothing and a request is not held back by it; only the tick waits, so |
| + // it does not ask the store for the lease every residentPoll. |
| + waitUntil time.Time |
| } |
| // errResidentBackoff is begin's answer for a resident inside its backoff: |
| @@ -426,8 +435,10 @@ func retryAfterSeconds(d time.Duration) int { |
| // 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. |
| +// outage backs off instead of retrying every tick. A lease another holder |
| +// has (errLeaseHeld) and refused config (errConfigRefused) are refusals |
| +// through verdictOf; their retry pacing is residentOwnerWait's, never a |
| +// failure. Group R extends it through classifyRelease. |
| func residentFailure(err error) bool { |
| switch { |
| case err == nil: |
| @@ -443,6 +454,21 @@ func residentFailure(err error) bool { |
| return true |
| } |
| +// residentOwnerWait is how long the tick waits before it asks again after |
| +// an ownership refusal: a held lease's own retry-after, or the config |
| +// guard's; 0 for anything else. |
| +func residentOwnerWait(err error) time.Duration { |
| + var held *errLeaseHeld |
| + var refused *errConfigRefused |
| + switch { |
| + case errors.As(err, &held): |
| + return held.retryAfter |
| + case errors.As(err, &refused): |
| + return configRefusedRetryAfter * time.Second |
| + } |
| + return 0 |
| +} |
| + |
| // 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] |
| @@ -480,7 +506,7 @@ func (a *Service) residentJitterLocked() float64 { |
| // 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. |
| +// record), or its plan turned it off. 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 |
| @@ -491,6 +517,13 @@ func (a *Service) residentHeldLocked(rt registry.Route) bool { |
| return a.disabled(rt) |
| } |
| +// residentWaitingLocked reports whether st's time has not come: the build's |
| +// backoff (retryAt) or ownership pacing (waitUntil). The caller holds a.mu. |
| +func (a *Service) residentWaitingLocked(st *residentState) bool { |
| + now := a.now() |
| + return now.Before(st.retryAt) || now.Before(st.waitUntil) |
| +} |
| + |
| // 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 |
| @@ -499,6 +532,24 @@ func residentShaped(rt registry.Route) bool { |
| return rt.Kind == "instance" && !rt.Hibernate && rt.Runtime != "" |
| } |
| +// errResidentNotRunnable refuses a proactive wake whose row, read again |
| +// before the lease, is no longer one the resident listing returns |
| +// (residentRunnable) [Astra Task 8 R1 3]: a retirement, a hold or a move |
| +// that landed while its admission was pending launches nothing. |
| +var errResidentNotRunnable = errors.New("activator: the row is no longer an always-on instance this box runs") |
| + |
| +// residentRunnable is registry.ResidentInstances' filter on one row: a |
| +// rootfs instance that does not hibernate, ready, with no hold or import |
| +// gate, a socket, and neither a unit backing nor a tunnel. |
| +func residentRunnable(rt registry.Route) error { |
| + switch { |
| + case !rt.Resident(), rt.Status != "" && rt.Status != "ready", rt.HoldOp != "", rt.ImportGate != "", |
| + rt.Socket == "", rt.Backing != "", rt.Tunnel != "": |
| + return fmt.Errorf("%s: %w", rt.Host, errResidentNotRunnable) |
| + } |
| + return nil |
| +} |
| + |
| // 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), |
| @@ -520,6 +571,21 @@ func (a *Service) unreserveResidentLocked(st *residentState) { |
| a.residentStarting-- |
| } |
| +// residentOrderLocked is the listing in host order, rotated to begin just |
| +// after the host the tick last reserved (residentCursor) [Astra Task 8 R1 |
| +// 2]: four residents that keep being refused cannot take every slot of |
| +// every tick, so a fifth is reached on the next one. The caller holds a.mu. |
| +func (a *Service) residentOrderLocked(routes []registry.Route) []registry.Route { |
| + slices.SortFunc(routes, func(x, y registry.Route) int { return strings.Compare(x.Host, y.Host) }) |
| + i, _ := slices.BinarySearchFunc(routes, a.residentCursor, func(rt registry.Route, host string) int { |
| + if rt.Host <= host { |
| + return -1 |
| + } |
| + return 1 |
| + }) |
| + return append(routes[i:len(routes):len(routes)], routes[:i]...) |
| +} |
| + |
| // 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 |
| @@ -530,12 +596,16 @@ func (a *Service) unreserveResidentLocked(st *residentState) { |
| // 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. |
| +// residentPoll rather than the sweep's 30 s. An awake resident whose |
| +// replica reports its lease lost is stopped and its generations killed |
| +// (residentLeaseLostLocked), the second line under the lease watch for |
| +// a replica without the lease's own signal. Then superviseRootfsLocked |
| +// for every other awake rootfs entry. |
| +// 3. A host no longer listed is forgotten. Each listed row, from just |
| +// after the last host reserved (residentOrderLocked), not held |
| +// (residentHeldLocked), not starting, not waiting (residentWaitingLocked), |
| +// 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 { |
| @@ -545,7 +615,6 @@ func (a *Service) rootfsTick() { |
| 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 { |
| @@ -563,6 +632,14 @@ func (a *Service) rootfsTick() { |
| a.beginStopLocked(e, StopExited) |
| continue |
| } |
| + if e.route.Resident() && e.rep != nil { |
| + if err := e.rep.Err(); err != nil { |
| + if gens := a.residentLeaseLostLocked(e, err); gens != nil { |
| + go a.killResidentGens(e.route, gens) |
| + } |
| + continue |
| + } |
| + } |
| a.superviseRootfsLocked(e) |
| } |
| listed := make(map[string]bool, len(routes)) |
| @@ -574,13 +651,12 @@ func (a *Service) rootfsTick() { |
| delete(a.residents, host) |
| } |
| } |
| - now := a.now() |
| - for _, rt := range routes { |
| + for _, rt := range a.residentOrderLocked(routes) { |
| if !residentShaped(rt) { |
| continue |
| } |
| st := a.residentLocked(rt.Host) |
| - if a.residentHeldLocked(rt) || st.starting || now.Before(st.retryAt) { |
| + if a.residentHeldLocked(rt) || st.starting || a.residentWaitingLocked(st) { |
| continue |
| } |
| if a.residentStarting >= residentStartCeiling { |
| @@ -592,6 +668,7 @@ func (a *Service) rootfsTick() { |
| } |
| st.starting = true |
| a.residentStarting++ |
| + a.residentCursor = rt.Host |
| go a.residentJob(a.lifeCtx, rt, st) |
| } |
| } |
| @@ -600,17 +677,23 @@ func (a *Service) rootfsTick() { |
| // 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 |
| +// anything is published: st still this host's and reserved (RetireExcept |
| +// and a delisting forget it), not shutting down, not held (a fence, a live |
| +// entry, a latch, turned off), not waiting (a backoff a request's failed |
| +// wake set meanwhile), 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, which reads the row |
| +// again and refuses it unless it is still runnable (residentRunnable) |
| +// before the lease; its 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) |
| + if a.residentGatesPassed != nil { |
| + a.residentGatesPassed(rt.Host) |
| + } |
| a.mu.Lock() |
| - if a.residents[rt.Host] != st || !st.starting || a.shuttingDown || a.residentHeldLocked(rt) { |
| + if a.residents[rt.Host] != st || !st.starting || a.shuttingDown || a.residentHeldLocked(rt) || a.residentWaitingLocked(st) { |
| a.unreserveResidentLocked(st) |
| a.mu.Unlock() |
| return |
| @@ -637,6 +720,196 @@ func (a *Service) residentJob(ctx context.Context, rt registry.Route, st *reside |
| a.wake(e) |
| } |
| +// forgetResidentsLocked drops the residency state, and with it any pending |
| +// reservation, of every host not in keep (RetireExcept) [Astra Task 8 R1 |
| +// 3]: a job still in its gates finds its state gone and starts nothing. |
| +// The caller holds a.mu. |
| +func (a *Service) forgetResidentsLocked(keep map[string]bool) { |
| + for host := range a.residents { |
| + if !keep[host] { |
| + delete(a.residents, host) |
| + } |
| + } |
| +} |
| + |
| +// ---- A resident's lease (Astra Task 8 R1 1, C7) --------------------------- |
| +// |
| +// A resident never sleeps, so the idle sweep's lease check (every Idle/4, up |
| +// to 30 s) is too slow a guard for it: the lease package latches loss at its |
| +// safety deadline (SafeUntil), lease.RenewMargin (5 s) before the lease can |
| +// pass to another box. Each awake resident is watched on the lease's own |
| +// signal: a graceful stop begins while the safe time left can still cover |
| +// one (residentDrainBudget), and at loss every generation of the entry is |
| +// killed outright (KillGen, which returns once its cgroup is proven empty) |
| +// whatever the stop is doing. The lease is released, and the entry |
| +// forgotten, only by the stop path, after its own termination proof |
| +// (releasable); until then the live entry keeps the tick and requests off |
| +// the host. |
| + |
| +// residentOwnership is the lease's own signal on the replica handle |
| +// (*lease.Replicator): Lost closes on a failed renewal or at the safety |
| +// deadline; SafeUntil is that deadline while ownership holds. |
| +type residentOwnership interface { |
| + Lost() <-chan struct{} |
| + SafeUntil() (time.Time, error) |
| +} |
| + |
| +// The production replica is lease.Held's *lease.Replicator (execLease. |
| +// Replicate): pinned, so a change to its signal fails the build. |
| +var _ residentOwnership = (*lease.Replicator)(nil) |
| + |
| +// residentDrainBudget is the safe time a graceful stop needs: the next-due |
| +// probe (5 s), the SIGTERM drain (actStopTimeout, 20 s) and the proof. With |
| +// less than this left before the safety deadline the resident is stopped at |
| +// once; a var so tests can shrink it. |
| +var residentDrainBudget = 30 * time.Second |
| + |
| +// watchResidentLeaseLocked starts e's lease watch, at its awake transition |
| +// (wake). A replica without the lease's signal is left to the tick's |
| +// rep.Err check. The watch ends when the entry is forgotten (finishStop |
| +// closes ownerDone). The caller holds a.mu. |
| +func (a *Service) watchResidentLeaseLocked(e *actEntry) { |
| + sig, ok := e.rep.(residentOwnership) |
| + if !ok || e.ownerDone != nil { |
| + return |
| + } |
| + done := make(chan struct{}) |
| + e.ownerDone = done |
| + go a.watchResidentLease(e, sig, done) |
| +} |
| + |
| +// watchResidentLease is one resident's lease watch: the safe deadline is read |
| +// again whenever it was due to fall inside the drain budget (a renewal may |
| +// have moved it); once it does, a graceful stop begins (StopLeaseLost); at |
| +// loss the entry's generations are killed. |
| +func (a *Service) watchResidentLease(e *actEntry, sig residentOwnership, done <-chan struct{}) { |
| + draining := false |
| + for { |
| + until, err := sig.SafeUntil() |
| + if err != nil { |
| + a.residentLeaseLost(e, err) |
| + return |
| + } |
| + var t *time.Timer |
| + var due <-chan time.Time |
| + if !draining { |
| + left := time.Until(until) |
| + if left <= residentDrainBudget { |
| + draining = true |
| + a.residentLeaseShort(e, left) |
| + } else { |
| + t = time.NewTimer(left - residentDrainBudget) |
| + due = t.C |
| + } |
| + } |
| + select { |
| + case <-done: |
| + stopTimer(t) |
| + return |
| + case <-sig.Lost(): |
| + stopTimer(t) |
| + select { |
| + case <-done: |
| + return // forgotten as the loss latched: nothing left to kill |
| + default: |
| + } |
| + _, err := sig.SafeUntil() |
| + if err == nil { |
| + err = lease.ErrLost |
| + } |
| + a.residentLeaseLost(e, err) |
| + return |
| + case <-due: |
| + } |
| + } |
| +} |
| + |
| +// stopTimer stops t when there is one. |
| +func stopTimer(t *time.Timer) { |
| + if t != nil { |
| + t.Stop() |
| + } |
| +} |
| + |
| +// residentLeaseShort begins e's graceful stop when the lease's safe time |
| +// left (left) can no longer wait: renewals are not landing, and a drain |
| +// begun later would outlast the deadline. |
| +func (a *Service) residentLeaseShort(e *actEntry, left time.Duration) { |
| + a.mu.Lock() |
| + defer a.mu.Unlock() |
| + if a.entries[e.host] != e || e.state != actAwake { |
| + return |
| + } |
| + log.Printf("activator: %s: its lease is not renewing and is safe for %s more; stopping it while a drain still fits", e.host, left.Round(time.Millisecond)) |
| + a.beginStopLocked(e, StopLeaseLost) |
| +} |
| + |
| +// residentLeaseLost is the loss itself: e is stopped if it is still awake, |
| +// and every generation it has is killed and proven gone, off a.mu. |
| +func (a *Service) residentLeaseLost(e *actEntry, err error) { |
| + a.mu.Lock() |
| + gens := a.residentLeaseLostLocked(e, err) |
| + a.mu.Unlock() |
| + if gens != nil { |
| + a.killResidentGens(e.route, gens) |
| + } |
| +} |
| + |
| +// residentLeaseLostLocked begins e's stop for a lost lease (if it is still |
| +// awake), cancels its generation attempts, and returns every generation |
| +// number the entry has (the current one and each operation member's) for |
| +// killResidentGens; nil when e is no longer the host's entry. The caller |
| +// holds a.mu. |
| +func (a *Service) residentLeaseLostLocked(e *actEntry, err error) []uint64 { |
| + if a.entries[e.host] != e { |
| + return nil |
| + } |
| + log.Printf("activator: LEASE LOST for always-on %s (%v); killing it", e.host, err) |
| + if e.state == actAwake { |
| + a.beginStopLocked(e, StopLeaseLost) |
| + } |
| + gens := []uint64{} |
| + if e.gen.N != 0 { |
| + gens = append(gens, e.gen.N) |
| + } |
| + for n, m := range e.ops.members { |
| + if m.cancel != nil { |
| + m.cancel() |
| + } |
| + if n != 0 && n != e.gen.N { |
| + gens = append(gens, n) |
| + } |
| + } |
| + return gens |
| +} |
| + |
| +// killResidentGens kills each generation outright through the backend's |
| +// KillGen, which returns once that generation's cgroup is proven empty, all |
| +// at once. A failure is logged: the stop path's own proof (releasable) |
| +// keeps the lease and the entry until termination is proven. |
| +func (a *Service) killResidentGens(rt registry.Route, gens []uint64) { |
| + k, ok := a.backend.(genKiller) |
| + if !ok { |
| + log.Printf("activator: %s: this backend has no generation kill; its stop's own proof decides", rt.Host) |
| + return |
| + } |
| + var wg sync.WaitGroup |
| + for _, n := range gens { |
| + wg.Add(1) |
| + go func(n uint64) { |
| + defer wg.Done() |
| + ctx, cancel := context.WithTimeout(context.Background(), instancectl.DeadlineControl+roleEmptyBound) |
| + defer cancel() |
| + if err := k.KillGen(ctx, rt, n); err != nil { |
| + log.Printf("activator: %s: kill generation %d after its lease was lost: %v; its stop keeps the lease until it is proven", rt.Host, n, err) |
| + return |
| + } |
| + log.Printf("activator: %s: generation %d killed and proven gone after its lease was lost", rt.Host, n) |
| + }(n) |
| + } |
| + wg.Wait() |
| +} |
| + |
| // superviseRootfsLocked is the resident tick's supervision hook for an awake |
| // rootfs entry. A no-op in group A; W1 fills it with worker supervision. |
| func (a *Service) superviseRootfsLocked(e *actEntry) {} |
| @@ -661,6 +934,9 @@ func (a *Service) noteResidentWakeLocked(e *actEntry, err error) { |
| now := a.now() |
| if !residentFailure(err) { |
| st.retryAt = now |
| + if d := residentOwnerWait(err); d > 0 { |
| + st.waitUntil = now.Add(d) |
| + } |
| return |
| } |
| st.failures++ |
diff --git a/internal/activator/swap.go b/internal/activator/swap.go| index 50ec2f02d..7b7dc17b4 100644 |
| --- a/internal/activator/swap.go |
| +++ b/internal/activator/swap.go |
| @@ -249,6 +249,15 @@ func verdictOf(err error) gateVerdict { |
| errors.Is(err, errBuildStateUnwritten): |
| return gateNoOwnership |
| } |
| + // A lease another holder still has (errLeaseHeld) and config this box |
| + // cannot provide yet (errConfigRefused) are typed answers given before |
| + // anything of the build ran: refusals, never its failure (INV-4; Astra |
| + // rootfs Plan 3 Task 8 R1 5). |
| + var held *errLeaseHeld |
| + var refused *errConfigRefused |
| + if errors.As(err, &held) || errors.As(err, &refused) { |
| + return gateNoOwnership |
| + } |
| return gateProceed |
| } |