carlos / platform Public

activator tests: end lease watches before restoring settings

A lease watch handling a loss launches kills that read restored settings,
so the join now waits for one that is working and ends the parked ones.
Service.leaseWork is the signal: production never waits on it.

The sweep burst test's wall-clock bound no longer applies under -race.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7a8b820fad21bf54d91bd0c2ce46adab7959e990 parent ccb3bff
6 files changed, +178 −14
  • internal/activator/activator.go +4 −0
  • internal/activator/escrow_test.go +1 −1
  • internal/activator/knobrestore_test.go +152 −12
  • internal/activator/race_off_test.go +7 −0
  • internal/activator/race_on_test.go +7 −0
  • internal/activator/rootfs_service.go +7 −1
diff --git a/internal/activator/activator.go b/internal/activator/activator.go
index 1aab0b8a5..24f5c507d 100644
--- a/internal/activator/activator.go
+++ b/internal/activator/activator.go
@@ -1688,6 +1688,10 @@ type Service struct {
// wakes' reapers (reapUnprovenWake). Nothing in the agent waits on it;
// tests do, before their files go (#897).
background atomic.Int64
+ // leaseWork counts each lease watch and the one-shot stops a short lease
+ // starts from it. Production never waits on it: it is how a test knows that
+ // work has ended before it restores a timing setting the work reads.
+ leaseWork sync.WaitGroup
// schedMu guards schedFences, each host's schedule write fence
// (schedfence.go). It is never held with a.mu or a fence's own lock.
diff --git a/internal/activator/escrow_test.go b/internal/activator/escrow_test.go
index 41caecc41..4faddb85b 100644
--- a/internal/activator/escrow_test.go
+++ b/internal/activator/escrow_test.go
@@ -1034,7 +1034,7 @@ func TestSweepBurstOf252MeetsTheDeadline(t *testing.T) {
if rep.Published != 252 || rep.Deferred != 0 || len(rep.Failing) != 0 {
t.Fatalf("sweep: %+v", rep)
}
- if elapsed >= EscrowEvery {
+ if !raceBuild && elapsed >= EscrowEvery {
t.Fatalf("252 publishes took %v of store time, past the %v sweep period", elapsed, EscrowEvery)
}
if p := ls.peak.Load(); p > escrowSweepWorkers || p < 2 {
diff --git a/internal/activator/knobrestore_test.go b/internal/activator/knobrestore_test.go
index 832031e97..18d408d21 100644
--- a/internal/activator/knobrestore_test.go
+++ b/internal/activator/knobrestore_test.go
@@ -7,6 +7,8 @@ import (
"sync"
"testing"
"time"
+
+ "github.com/carlosframework/platform/internal/lease"
)
// knobJoinBound is how long a test's end waits for the production goroutines
@@ -22,7 +24,10 @@ var knobRestores = struct {
abandoned map[string]bool
// services are the Services built since the last top-level test ended.
services []*Service
-}{byTest: map[*testing.T][]func(){}, abandoned: map[string]bool{}}
+ // firstOwned is, for a subtest, where in services its own Services begin.
+ // Those before it are its parent's, still in use.
+ firstOwned map[*testing.T]int
+}{byTest: map[*testing.T][]func(){}, abandoned: map[string]bool{}, firstOwned: map[*testing.T]int{}}
// newTrackedService is New for tests: the join at a test's end synchronises
// with every Service built this way (syncWithServices).
@@ -49,6 +54,9 @@ func restoreKnob(t *testing.T, restore func()) {
knobRestores.Lock()
defer knobRestores.Unlock()
if _, ok := knobRestores.byTest[t]; !ok {
+ if strings.Contains(t.Name(), "/") {
+ knobRestores.firstOwned[t] = len(knobRestores.services)
+ }
t.Cleanup(func() { runKnobRestores(t) })
}
knobRestores.byTest[t] = append(knobRestores.byTest[t], restore)
@@ -57,10 +65,14 @@ func restoreKnob(t *testing.T, restore func()) {
func runKnobRestores(t *testing.T) {
t.Helper()
joinProductionGoroutines(t)
+ endLeaseWatches(t)
+ // A watch that was handling a loss may have begun a stop.
+ joinProductionGoroutines(t)
syncWithServices(t)
knobRestores.Lock()
restores := knobRestores.byTest[t]
delete(knobRestores.byTest, t)
+ delete(knobRestores.firstOwned, t)
knobRestores.Unlock()
for i := len(restores) - 1; i >= 0; i-- {
restores[i]()
@@ -98,6 +110,61 @@ func joinProductionGoroutines(t *testing.T) {
}
}
+// ownedServices returns the Services t may end: every one for a top-level
+// test, and for a subtest those built since its first restoreKnob.
+func ownedServices(t *testing.T) []*Service {
+ knobRestores.Lock()
+ defer knobRestores.Unlock()
+ return slices.Clone(knobRestores.services[knobRestores.firstOwned[t]:])
+}
+
+// lockService takes a.mu, giving up when deadline fires.
+func lockService(a *Service, deadline <-chan time.Time) bool {
+ tick := time.NewTicker(time.Millisecond)
+ defer tick.Stop()
+ for !a.mu.TryLock() {
+ select {
+ case <-tick.C:
+ case <-deadline:
+ return false
+ }
+ }
+ return true
+}
+
+// endLeaseWatches ends the lease watches of t's Services and waits for them.
+// A parked watch reads no setting, but a lease that runs out later would wake
+// it, and the loss it then handles does. Waiting on Service.leaseWork also
+// orders the reads of the kills a loss started before the restores.
+func endLeaseWatches(t *testing.T) {
+ t.Helper()
+ deadline := time.After(knobJoinBound)
+ for _, a := range ownedServices(t) {
+ if !lockService(a, deadline) {
+ t.Errorf("a Service's lock was still held %s after the test ended", knobJoinBound)
+ return
+ }
+ for _, e := range a.entries {
+ if e.ownerDone != nil {
+ close(e.ownerDone)
+ e.ownerDone = nil
+ }
+ }
+ a.mu.Unlock()
+ ended := make(chan struct{})
+ go func() {
+ a.leaseWork.Wait()
+ close(ended)
+ }()
+ select {
+ case <-ended:
+ case <-deadline:
+ t.Errorf("a Service's lease watch was still running %s after the test ended", knobJoinBound)
+ return
+ }
+ }
+}
+
// syncWithServices orders everything the finished goroutines did before the
// restores that follow. Seeing a goroutine gone from the stacks shows that it
// ended, but the race detector only believes a synchronisation: without one
@@ -114,17 +181,11 @@ func syncWithServices(t *testing.T) {
}
knobRestores.Unlock()
deadline := time.After(knobJoinBound)
- tick := time.NewTicker(time.Millisecond)
- defer tick.Stop()
for _, a := range services {
a.background.Load()
- for !a.mu.TryLock() {
- select {
- case <-tick.C:
- case <-deadline:
- t.Errorf("a Service's lock was still held %s after the test ended", knobJoinBound)
- return
- }
+ if !lockService(a, deadline) {
+ t.Errorf("a Service's lock was still held %s after the test ended", knobJoinBound)
+ return
}
a.mu.Unlock()
}
@@ -139,7 +200,6 @@ var idleGoroutineRoots = []string{
"activator.(*ExecBackend).observe(",
"activator.(*ExecBackend).retryStrictCleanup(",
"activator.(*unitProc).Stop.func1(",
- "activator.(*Service).watchResidentLease(",
"activator.(*Service).superviseRelease(",
}
@@ -199,7 +259,15 @@ func runsProductionCode(g string) bool {
return false
}
-// isIdleGoroutine reports whether g's outermost function is an idle root.
+// parkedLeaseWatch reports whether g, a lease watch, is waiting for its lease.
+// One handling a short or lost lease is working, and is waited for.
+func parkedLeaseWatch(g string) bool {
+ return strings.Contains(g, " [select") &&
+ !strings.Contains(g, "residentLeaseLost(") && !strings.Contains(g, "residentLeaseShort(")
+}
+
+// isIdleGoroutine reports whether g's outermost function is an idle root, or
+// g is a parked lease watch, which endLeaseWatches ends.
func isIdleGoroutine(g string) bool {
root := ""
for _, line := range stackFrames(g) {
@@ -207,6 +275,9 @@ func isIdleGoroutine(g string) bool {
root = line
}
}
+ if strings.Contains(root, "activator.(*Service).watchResidentLease(") {
+ return parkedLeaseWatch(g)
+ }
for _, idle := range idleGoroutineRoots {
if strings.Contains(root, idle) {
return true
@@ -214,3 +285,72 @@ func isIdleGoroutine(g string) bool {
}
return false
}
+
+// leaseWatchIsLive reports whether the join is waiting for a lease watch.
+func leaseWatchIsLive() bool {
+ for _, g := range productionGoroutines() {
+ if strings.Contains(g, "activator.(*Service).watchResidentLease(") {
+ return true
+ }
+ }
+ return false
+}
+
+// A lease watch handling a loss launches kills that read restored settings,
+// so the join waits for it. Once parked again it is only ended, not awaited.
+func TestKnobJoinWaitsForALeaseWatchHandlingALoss(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()
+ waitFor(t, "the watch to park", func() bool { return !leaseWatchIsLive() })
+
+ killing, release := make(chan struct{}), make(chan struct{})
+ var once, killedOnce sync.Once
+ finish := func() { once.Do(func() { close(release) }) }
+ t.Cleanup(finish)
+ kb.kmu.Lock()
+ kb.onKill = func(uint64) { // the loss and the stop's proof both kill
+ killedOnce.Do(func() { close(killing) })
+ <-release
+ proc.exit()
+ }
+ kb.kmu.Unlock()
+ rep.lose(lease.ErrLost)
+ select {
+ case <-killing:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the lost lease never reached its kill")
+ }
+ if !leaseWatchIsLive() {
+ t.Fatal("the join would not wait for a lease watch handling a loss")
+ }
+ finish()
+ waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(host) })
+}
+
+// endLeaseWatches ends a parked watch, so that a lease running out after the
+// test cannot wake it while settings are being restored.
+func TestEndLeaseWatchesEndsAParkedWatch(t *testing.T) {
+ host := "shop.example.com"
+ a, kb, _, _ := residentKillService(t, residentRoute(host))
+ kb.mu.Lock()
+ kb.repWrap = func(r *fakeRep) Rep { return newOwnedRep(r, time.Now().Add(time.Hour)) }
+ kb.mu.Unlock()
+ startResident(t, a, host)
+ waitFor(t, "the watch to park", func() bool { return !leaseWatchIsLive() })
+ kb.lastProc().exit()
+
+ endLeaseWatches(t)
+ if t.Failed() {
+ t.Fatal("the lease watch did not end")
+ }
+ stacks := make([]byte, 1<<20)
+ if s := string(stacks[:runtime.Stack(stacks, true)]); strings.Contains(s, "activator.(*Service).watchResidentLease(") {
+ t.Fatalf("a lease watch is still running:\n%s", s)
+ }
+}
diff --git a/internal/activator/race_off_test.go b/internal/activator/race_off_test.go
new file mode 100644
index 000000000..adc67c137
--- /dev/null
+++ b/internal/activator/race_off_test.go
@@ -0,0 +1,7 @@
+//go:build !race
+
+package activator
+
+// raceBuild reports whether the race detector is compiled in. It makes code
+// many times slower, so a bound on elapsed time proves nothing under it.
+const raceBuild = false
diff --git a/internal/activator/race_on_test.go b/internal/activator/race_on_test.go
new file mode 100644
index 000000000..d20c2fdb1
--- /dev/null
+++ b/internal/activator/race_on_test.go
@@ -0,0 +1,7 @@
+//go:build race
+
+package activator
+
+// raceBuild reports whether the race detector is compiled in. It makes code
+// many times slower, so a bound on elapsed time proves nothing under it.
+const raceBuild = true
diff --git a/internal/activator/rootfs_service.go b/internal/activator/rootfs_service.go
index 6c0f655cc..3a104c93e 100644
--- a/internal/activator/rootfs_service.go
+++ b/internal/activator/rootfs_service.go
@@ -909,6 +909,7 @@ func (a *Service) watchResidentLeaseLocked(e *actEntry) {
}
done := make(chan struct{})
e.ownerDone = done
+ a.leaseWork.Add(1)
go a.watchResidentLease(e, sig, done)
}
@@ -921,6 +922,7 @@ func (a *Service) watchResidentLeaseLocked(e *actEntry) {
// generations are killed at once (residentLeaseLost), and the stop path's
// proof still decides when the lease goes.
func (a *Service) watchResidentLease(e *actEntry, sig residentOwnership, done <-chan struct{}) {
+ defer a.leaseWork.Done()
draining := false
for {
until, err := sig.SafeUntil()
@@ -991,7 +993,11 @@ func (a *Service) residentLeaseShort(e *actEntry, left time.Duration) {
}
a.mu.Unlock()
for _, f := range oneShots {
- go f()
+ a.leaseWork.Add(1)
+ go func() {
+ defer a.leaseWork.Done()
+ f()
+ }()
}
}