carlos / platform Public

edge tests: drive the watch and the silence window, not sleeps

From the Go audit (#1123), activator-edge finding 3. About 54 s of
fixed sleeping goes from internal/edge tests; the changed tests ran
85 s before and 23.5 s after (20 s of that is one test whose twenty
seconds belong to the activator's timers, left as is).

lbhealth_test.go:
- TestRegistryWatchDoesNotBeatOnFingerprintError and wedgedProbe (both
  TestEdgeBeat* tests) drive Watch through the existing Edge.watchTick
  seam (tickedWatch) instead of sleeping 5 s for its 2 s ticker. The
  tick channel is unbuffered, so the second send proves the first poll
  was wholly handled. wedgedProbe's setup beats are taken 5 s back
  (healthyStateAt), where the old 5 s sleep left them, so the same 57 s
  look-ahead separates a tick's beat from setup's. A mutation that beats
  on every tick fails both, as before.
- TestRegistryWatchBeats ticks the same way instead of polling for up
  to 5 s on the real ticker.
- TestHomeMapFeedsTheHealthState puts the home map on a test clock
  (homeMap.now) and advances it 1.2 s instead of sleeping; the check
  still fails if Refresh stamps at entry (mutation run).

forwardha.go: holderHeaderSuspectAfter becomes a var, value unchanged
(3 s), so a test can shorten it, as clientGoneGrace and
servingProbeTimeout are. ShortenHolderSilenceForTest sets it per test.
- TestSlowHolderResponseIsNotAborted waits for the silent note on a
  channel (fwAct.noteC) with a 100 ms window instead of sleeping 3.2 s,
  and for the final-headers note instead of a 1 s poll. Its 17 s "a
  twenty-second app" wait becomes six windows after the report, the
  same ratio to the window.
- TestCanceledHolderDoesNotConfirmNearThreshold uses a 500 ms window:
  cancel 200 ms before it ends, check 300 ms after, the old margins.
- TestSilentHolderObservationJoinsCallback: 100 ms window.
- forwardha_service_test.go: silenceSignal wraps the real activator and
  signals once a silent note is handled; the revalidate-once and
  slow-holder tests wait on it (100 ms window) instead of 3.2 s sleeps,
  TestSilentHolderNewOwnershipDuringTimer gets the 100 ms window, and
  TestSlowHolderTwentySecondHeadersKeepForwarding keeps the production
  window but waits on the signal instead of 3.3 s.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9e1390cd2389f57db27c42d28c3ce75dd499994f parent c4b44c3
4 files changed, +151 −47
  • internal/edge/forwardha.go +4 −1
  • internal/edge/forwardha_service_test.go +46 −6
  • internal/edge/forwardha_test.go +44 −10
  • internal/edge/lbhealth_test.go +57 −30
diff --git a/internal/edge/forwardha.go b/internal/edge/forwardha.go
index 1f382c68d..d6b991e62 100644
--- a/internal/edge/forwardha.go
+++ b/internal/edge/forwardha.go
@@ -506,7 +506,10 @@ func (e *Edge) handoverInRegion(v string, rt registry.Route) (handoverNext, bool
return handoverNext{ref: ref, dial: dial}, true
}
-const holderHeaderSuspectAfter = 3 * time.Second
+// holderHeaderSuspectAfter is how long a connected holder may send no final
+// headers before observeHolderHeaders reports silence. A var only so a test
+// can shorten it.
+var holderHeaderSuspectAfter = 3 * time.Second
// Observation never cancels the transport. Joining at final headers orders
// their confirmation after any suspicion already being reported. Joining on
diff --git a/internal/edge/forwardha_service_test.go b/internal/edge/forwardha_service_test.go
index 9bcb3464a..7c3ed59b9 100644
--- a/internal/edge/forwardha_service_test.go
+++ b/internal/edge/forwardha_service_test.go
@@ -31,8 +31,42 @@ func holderService(t *testing.T) (*activator.Service, registry.Route, *locktest.
return a, rt, fx
}
+// silenceSignal is the activator with a signal sent once it has handled a
+// silent-holder note, so a test waits for the report instead of sleeping
+// past the window.
+type silenceSignal struct {
+ *activator.Service
+ silent chan struct{}
+}
+
+func newSilenceSignal(a *activator.Service) *silenceSignal {
+ return &silenceSignal{Service: a, silent: make(chan struct{}, 8)}
+}
+
+func (f *silenceSignal) NoteForward(host string, res edge.ForwardResult) {
+ f.Service.NoteForward(host, res)
+ if res.Outcome == edge.ForwardSilent {
+ select {
+ case f.silent <- struct{}{}:
+ default:
+ }
+ }
+}
+
+// wait waits for the next silent-holder note to be handled.
+func (f *silenceSignal) wait(t *testing.T) {
+ t.Helper()
+ select {
+ case <-f.silent:
+ case <-time.After(10 * time.Second):
+ t.Fatal("the silent holder was never reported")
+ }
+}
+
func TestSilentHolderRevalidatesOnceThroughEdge(t *testing.T) {
+ edge.ShortenHolderSilenceForTest(t, 100*time.Millisecond)
a, rt, fx := holderService(t)
+ fw := newSilenceSignal(a)
d := a.ForwardTarget(t.Context(), rt, nil)
if d.Ref != "betty" {
t.Fatalf("discovery: %+v", d)
@@ -42,7 +76,7 @@ func TestSilentHolderRevalidatesOnceThroughEdge(t *testing.T) {
started := make(chan struct{})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
- forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forward := edge.ForwardHolderForTest(t, fw, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writes.Add(1)
close(started)
<-r.Context().Done()
@@ -56,7 +90,7 @@ func TestSilentHolderRevalidatesOnceThroughEdge(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("no request")
}
- time.Sleep(3200 * time.Millisecond)
+ fw.wait(t)
if got, hit := a.ForwardTargetFromMemory(rt, nil); !hit || got.Refuse || got.Ref != "betty" {
t.Fatalf("silence alone refused: %+v", got)
}
@@ -109,12 +143,14 @@ func TestSlowHolderResponseIsNotAbortedThroughEdge(t *testing.T) {
}
for _, newer := range []bool{false, true} {
t.Run(map[bool]string{false: "same holder", true: "new holder"}[newer], func(t *testing.T) {
+ edge.ShortenHolderSilenceForTest(t, 100*time.Millisecond)
a, rt, _ := holderService(t)
+ fw := newSilenceSignal(a)
d := a.ForwardTarget(t.Context(), rt, nil)
headers, body := make(chan struct{}), make(chan struct{})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
- forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forward := edge.ForwardHolderForTest(t, fw, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusEarlyHints)
select {
case <-headers:
@@ -132,7 +168,7 @@ func TestSlowHolderResponseIsNotAbortedThroughEdge(t *testing.T) {
}))
done := make(chan edge.ForwardResult, 1)
go func() { done <- forward(ctx, d) }()
- time.Sleep(3200 * time.Millisecond)
+ fw.wait(t)
if got, hit := a.ForwardTargetFromMemory(rt, nil); !hit || got.Refuse || got.Ref != "betty" {
cancel()
<-done
@@ -184,6 +220,7 @@ func (f *pausedSilentForwarder) NoteForward(host string, res edge.ForwardResult)
func TestSilentHolderNewOwnershipDuringTimer(t *testing.T) {
for _, owner := range []string{"carol", "annie"} {
t.Run(owner, func(t *testing.T) {
+ edge.ShortenHolderSilenceForTest(t, 100*time.Millisecond)
a, rt, _ := holderService(t)
d := a.ForwardTarget(t.Context(), rt, nil)
fw := &pausedSilentForwarder{Service: a, started: make(chan struct{}), release: make(chan struct{})}
@@ -217,15 +254,18 @@ func TestSilentHolderNewOwnershipDuringTimer(t *testing.T) {
}
}
+// The window stays at its production three seconds here: the twenty seconds
+// are the app's, measured against the activator's own timers.
func TestSlowHolderTwentySecondHeadersKeepForwarding(t *testing.T) {
a, rt, fx := holderService(t)
+ fw := newSilenceSignal(a)
d := a.ForwardTarget(t.Context(), rt, nil)
var writes atomic.Int32
headers := make(chan struct{})
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
arrived := make(chan time.Time, 1)
- forward := edge.ForwardHolderForTest(t, a, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ forward := edge.ForwardHolderForTest(t, fw, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if writes.Add(1) == 1 {
arrived <- time.Now()
}
@@ -243,7 +283,7 @@ func TestSlowHolderTwentySecondHeadersKeepForwarding(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("holder did not receive original POST")
}
- time.Sleep(3300 * time.Millisecond)
+ fw.wait(t)
for range 3 {
next := a.ForwardTarget(ctx, rt, nil)
if next.Refuse || next.Ref != "betty" {
diff --git a/internal/edge/forwardha_test.go b/internal/edge/forwardha_test.go
index 3f897db3d..3bfae5a34 100644
--- a/internal/edge/forwardha_test.go
+++ b/internal/edge/forwardha_test.go
@@ -74,6 +74,9 @@ type fwAct struct {
asked atomic.Int64
mu sync.Mutex
notes []fwNote
+ // noteC, when set, is sent every note once it is recorded, so a test
+ // can wait for one instead of sleeping. Give it room for every note.
+ noteC chan fwNote
}
type fwNote struct {
@@ -107,9 +110,25 @@ func (a *fwAct) ForwardTarget(_ context.Context, _ registry.Route, _ func() boxc
}
func (a *fwAct) NoteForward(host string, res ForwardResult) {
+ n := fwNote{host, res}
a.mu.Lock()
- defer a.mu.Unlock()
- a.notes = append(a.notes, fwNote{host, res})
+ a.notes = append(a.notes, n)
+ a.mu.Unlock()
+ if a.noteC != nil {
+ a.noteC <- n
+ }
+}
+
+// nextNote waits for the next note on noteC.
+func (a *fwAct) nextNote(t *testing.T) fwNote {
+ t.Helper()
+ select {
+ case n := <-a.noteC:
+ return n
+ case <-time.After(10 * time.Second):
+ t.Fatalf("no note within 10 s; noted %+v", a.noted())
+ return fwNote{}
+ }
}
func (a *fwAct) noted() []fwNote {
@@ -1438,6 +1457,17 @@ func (w fwFinalRecorder) WriteHeader(status int) {
w.ResponseRecorder.WriteHeader(status)
}
+// ShortenHolderSilenceForTest sets the time a connected holder may send no
+// final headers before it is reported silent (holderHeaderSuspectAfter,
+// 3 s in production) to d until the test ends. A test that needs the report
+// shortens the window and waits for the report, not three seconds.
+func ShortenHolderSilenceForTest(t *testing.T, d time.Duration) {
+ t.Helper()
+ old := holderHeaderSuspectAfter
+ holderHeaderSuspectAfter = d
+ t.Cleanup(func() { holderHeaderSuspectAfter = old })
+}
+
// ForwardHolderForTest keeps the real signed-hop proxy and callback path while
// redirecting its TLS transport to a loopback test server. The external-package
// witness uses this to connect the edge to the real activator without a cycle.
@@ -1514,7 +1544,8 @@ func TestCanceledHolderDoesNotConfirm(t *testing.T) {
func TestSlowHolderResponseIsNotAborted(t *testing.T) {
for _, informational := range []bool{false, true} {
t.Run(fmt.Sprint(informational), func(t *testing.T) {
- fw := &fwAct{}
+ ShortenHolderSilenceForTest(t, 100*time.Millisecond)
+ fw := &fwAct{noteC: make(chan fwNote, 8)}
started, headers, body := make(chan struct{}), make(chan struct{}), make(chan struct{})
var writes atomic.Int32
ctx, cancel := context.WithCancel(t.Context())
@@ -1552,7 +1583,7 @@ func TestSlowHolderResponseIsNotAborted(t *testing.T) {
case <-time.After(5 * time.Second):
t.Fatal("server never received request")
}
- time.Sleep(3200 * time.Millisecond)
+ fw.nextNote(t)
notes := fw.noted()
if len(notes) != 1 || notes[0].res.Outcome != ForwardSilent || notes[0].res.Gen != 7 || notes[0].res.Ref != "betty" || notes[0].host != fwHost {
cancel()
@@ -1565,14 +1596,13 @@ func TestSlowHolderResponseIsNotAborted(t *testing.T) {
default:
}
if !informational {
- // The three-second observation must still allow a twenty-second app.
- time.Sleep(17 * time.Second)
+ // The observation must still allow an app far slower than
+ // its window: six more windows after the report, as the
+ // three-second window allowed a twenty-second app.
+ time.Sleep(6 * holderHeaderSuspectAfter)
}
close(headers)
- deadline := time.Now().Add(time.Second)
- for len(fw.noted()) < 2 && time.Now().Before(deadline) {
- time.Sleep(time.Millisecond)
- }
+ fw.nextNote(t)
notes = fw.noted()
if len(notes) != 2 || notes[1].res.Status != http.StatusCreated || notes[1].res.Outcome != ForwardDone {
cancel()
@@ -1596,6 +1626,9 @@ func TestSlowHolderResponseIsNotAborted(t *testing.T) {
}
func TestCanceledHolderDoesNotConfirmNearThreshold(t *testing.T) {
+ // Cancelled 200 ms before the window ends and checked 300 ms after
+ // cancelling, the margins the three-second window had.
+ ShortenHolderSilenceForTest(t, 500*time.Millisecond)
fw := &fwAct{}
started := make(chan struct{})
ctx, cancel := context.WithCancel(t.Context())
@@ -1649,6 +1682,7 @@ func TestSlowHolderResponseIsNotAbortedAfterHeaderDisconnect(t *testing.T) {
}
func TestSilentHolderObservationJoinsCallback(t *testing.T) {
+ ShortenHolderSilenceForTest(t, 100*time.Millisecond)
started, release := make(chan struct{}), make(chan struct{})
var calls atomic.Int32
ctx, stop := observeHolderHeaders(t.Context(), func() {
diff --git a/internal/edge/lbhealth_test.go b/internal/edge/lbhealth_test.go
index 58355ab35..d85fad0fa 100644
--- a/internal/edge/lbhealth_test.go
+++ b/internal/edge/lbhealth_test.go
@@ -64,9 +64,11 @@ func fallbackGet(e *Edge, method, path, host string) *httptest.ResponseRecorder
}
// healthyState meets every condition now.
-func healthyState() *lbhealth.State {
+func healthyState() *lbhealth.State { return healthyStateAt(time.Now()) }
+
+// healthyStateAt is healthyState with every beat taken at now.
+func healthyStateAt(now time.Time) *lbhealth.State {
s := &lbhealth.State{}
- now := time.Now()
s.SetHosting(true)
s.MapLoaded()
s.KeyLoaded()
@@ -152,8 +154,12 @@ func TestHomeMapFeedsTheHealthState(t *testing.T) {
h := &lbhealth.State{}
m := newHomeMap(s, "annie")
m.health = h
+ // The map stamps its attempts on its own clock, so the test moves time
+ // on rather than sleeping.
+ clk := &testClock{t: time.Now()}
+ m.now = clk.now
refreshHomeMap(t, m)
- now := time.Now()
+ now := clk.now()
failing := strings.Join(h.Failing(now), ",")
if strings.Contains(failing, lbhealth.CondForwarding) || strings.Contains(failing, lbhealth.CondRefresh) {
t.Fatalf("after a good refresh: %s", failing)
@@ -161,7 +167,7 @@ func TestHomeMapFeedsTheHealthState(t *testing.T) {
// A bucket outage: the attempt fails but finishes, and the latches hold.
s.down = true
- before := time.Now()
+ before := clk.now()
if err := m.Refresh(context.Background()); err == nil {
t.Fatal("refresh against a down bucket succeeded")
}
@@ -175,15 +181,15 @@ func TestHomeMapFeedsTheHealthState(t *testing.T) {
// A stamp taken at entry would be fresh here.
s.down = false
s.block, s.entered = make(chan struct{}), make(chan struct{}, 1)
- time.Sleep(1200 * time.Millisecond)
- t0 := time.Now()
+ clk.advance(1200 * time.Millisecond)
+ t0 := clk.now()
done := make(chan struct{})
go func() { _ = m.Refresh(context.Background()); close(done) }()
<-s.entered
if got := strings.Join(h.Failing(t0.Add(lbhealth.RefreshWindow-time.Second)), ","); !strings.Contains(got, lbhealth.CondRefresh) {
t.Fatalf("a refresh stuck inside its attempt was stamped at entry: %s", got)
}
- stuckAt := time.Now()
+ stuckAt := clk.now()
if got := strings.Join(h.Failing(stuckAt.Add(lbhealth.RefreshWindow+time.Second)), ","); !strings.Contains(got, lbhealth.CondRefresh) {
t.Fatalf("a refresh stuck for longer than the window still counts: %s", got)
}
@@ -229,18 +235,34 @@ func TestRegistryWatchBeats(t *testing.T) {
t.Cleanup(e.probers.Stop)
h := &lbhealth.State{}
e.lbHealth = h
- stop := make(chan struct{})
- t.Cleanup(func() { close(stop) })
- go e.Watch(stop)
- deadline := time.Now().Add(5 * time.Second)
- for strings.Contains(strings.Join(h.Failing(time.Now()), ","), lbhealth.CondEdge) {
- if time.Now().After(deadline) {
- t.Fatal("the registry watch never beat")
- }
- time.Sleep(50 * time.Millisecond)
+ tick := tickedWatch(t, e)
+ // The tick channel is unbuffered: the second send returns only once the
+ // first poll is wholly handled.
+ sendTick(t, tick)
+ sendTick(t, tick)
+ if strings.Contains(strings.Join(h.Failing(time.Now()), ","), lbhealth.CondEdge) {
+ t.Fatal("the registry watch never beat")
}
}
+// tickedWatch runs e.Watch on a test tick channel in place of its 2 s
+// ticker and returns the channel. Cleanup stops Watch and waits for it.
+func tickedWatch(t *testing.T, e *Edge) chan<- time.Time {
+ t.Helper()
+ tick := make(chan time.Time)
+ e.watchTick = tick
+ stop, done := make(chan struct{}), make(chan struct{})
+ go func() {
+ e.Watch(stop)
+ close(done)
+ }()
+ t.Cleanup(func() {
+ close(stop)
+ <-done
+ })
+ return tick
+}
+
// A certificate mirror whose first list fails has loaded nothing: the
// certificate condition stays unlatched, and a later good refresh latches it.
func TestCertMirrorFailedRefreshLeavesCertsUnlatched(t *testing.T) {
@@ -295,18 +317,20 @@ func TestRegistryWatchDoesNotBeatOnFingerprintError(t *testing.T) {
e.reg = failingFingerprint(t)
h := &lbhealth.State{}
e.lbHealth = h
- stop := make(chan struct{})
- t.Cleanup(func() { close(stop) })
- go e.Watch(stop)
- time.Sleep(5 * time.Second)
+ tick := tickedWatch(t, e)
+ // Three sends: the first two polls are wholly handled, each one failed.
+ for range 3 {
+ sendTick(t, tick)
+ }
if !strings.Contains(strings.Join(h.Failing(time.Now()), ","), lbhealth.CondEdge) {
t.Fatal("a failing Fingerprint beat")
}
}
-// wedgedProbe runs an edge over a state that is healthy at setup (every beat
-// taken then), so only the edge's beat can still move, and reports what is
-// failing a little before the window ends.
+// wedgedProbe runs an edge over a state that was healthy five seconds ago
+// (every beat taken then), so only the edge's beat can still move, ticks the
+// registry watch twice by hand, and reports what is failing a little before
+// the window ends.
func wedgedProbe(t *testing.T, wedge bool) (failing string) {
t.Helper()
old := servingProbeTimeout
@@ -318,7 +342,9 @@ func wedgedProbe(t *testing.T, wedge bool) (failing string) {
}
t.Cleanup(e.probers.Stop)
e.EnableCache(NewCache(10, 1<<20))
- h := healthyState()
+ // Setup's beats are taken five seconds back, where waiting five seconds
+ // for the watch's own ticker used to leave them.
+ h := healthyStateAt(time.Now().Add(-5 * time.Second))
h.SetActivator(time.Now) // the activator is not what this test wedges
e.lbHealth = h
if wedge {
@@ -327,12 +353,13 @@ func wedgedProbe(t *testing.T, wedge bool) (failing string) {
e.cache.mu.Lock()
t.Cleanup(e.cache.mu.Unlock)
}
- stop := make(chan struct{})
- t.Cleanup(func() { close(stop) })
- go e.Watch(stop)
- time.Sleep(5 * time.Second)
- // Set the clock 57s ahead: a beat from the last tick or two is still
- // inside the 60s window, one from before the wedge (setup, 5s+ ago) is not.
+ tick := tickedWatch(t, e)
+ // The tick channel is unbuffered: the second send returns only once the
+ // first poll is wholly handled, and a wedged path still lets the poll run.
+ sendTick(t, tick)
+ sendTick(t, tick)
+ // Set the clock 57s ahead: a beat from the ticks is still inside the 60s
+ // window, one from before the wedge (setup, 5s back) is not.
now := time.Now().Add(lbhealth.HeartbeatWindow - 3*time.Second)
got := h.Failing(now)
w := httptest.NewRecorder()