edge tests: drive the watch and silence window, not sleeps
From the Go audit (#1123), batch 2. About 54 s of fixed sleeping removed from internal/edge tests (the changed tests ran 85.0 s before, 23.5 s after): - lbhealth tests tick the existing Edge.watchTick seam and advance the home map's clock seam instead of sleeping. - holderHeaderSuspectAfter becomes a package var (3 s unchanged) so the forwardha tests shrink the silence window; fakes signal on a channel instead of waiting it out. - TestSlowHolderTwentySecondHeadersKeepForwarding keeps the production window and its 20 s absolute witness. Reviewed by Astra (round 1, READY AFTER FIXES; both P2s fixed in 3dead10c). Census envelope approved on #280. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from audit-edge-test-sleeps into main.
9 files changed,
+262
−49
docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md+11 −0docs/superpowers/reviews/FINDINGS-audit-edge-test-sleeps-R1.md+36 −0docs/superpowers/reviews/REVIEW-BRIEF-audit-edge-test-sleeps.md+42 −0internal/edge/forwardha.go+4 −1internal/edge/forwardha_service_test.go+46 −6internal/edge/forwardha_test.go+44 −10internal/edge/lbhealth_test.go+75 −32internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv+3 −0internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0
CI failed — run details
diff --git a/docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md b/docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md| new file mode 100644 |
| index 000000000..ca4e2139f |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: audit-edge-test-sleeps |
| + |
| +Ruling `census-ruling-audit-edge-test-sleeps`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `internal/edge`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f` → `4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/docs/superpowers/reviews/FINDINGS-audit-edge-test-sleeps-R1.md b/docs/superpowers/reviews/FINDINGS-audit-edge-test-sleeps-R1.md| new file mode 100644 |
| index 000000000..064093eb9 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/FINDINGS-audit-edge-test-sleeps-R1.md |
| @@ -0,0 +1,36 @@ |
| +Reviewed `origin/main...5dc4ad0249beff4d9a50fb947d0c875b3a47c0e4`, round 1. The difference from the brief’s named commit is the brief itself. |
| + |
| +No P1 findings. |
| + |
| +1. **P2 — The fake clock masks a missing failed-refresh heartbeat.** |
| + [internal/edge/lbhealth_test.go:170](/home/paulca/amadan.net/carlos/platform-audit-edge-test-sleeps/internal/edge/lbhealth_test.go:170) |
| + **Invariant:** every completed refresh stamps the heartbeat, including failed attempts. |
| + |
| + The clock has not advanced since the successful refresh. Consequently, `before` equals the existing heartbeat. At `before.Add(lbhealth.RefreshWindow)`, that old heartbeat remains valid because the boundary is inclusive. An implementation that stamps only successful refreshes now passes this assertion and the subsequent stuck-refresh assertions. |
| + |
| + **Fix:** advance the clock before capturing `before` and performing the failed refresh. Check at a time when the successful refresh’s stamp has expired but the failed attempt’s stamp remains valid. |
| + |
| +2. **P2 — The free-path witness now depends on one 100 ms probe succeeding.** |
| + [internal/edge/lbhealth_test.go:359](/home/paulca/amadan.net/carlos/platform-audit-edge-test-sleeps/internal/edge/lbhealth_test.go:359) |
| + **Invariant:** an available serving path must pass the health witness despite ordinary scheduler delays. |
| + |
| + Two unbuffered sends guarantee completion of only the first poll. If its probe goroutine is delayed beyond `servingProbeTimeout`, the first poll records no heartbeat. The assertion can then run before the second poll completes, reporting a wedged path even though the cache lock is free. The previous five-second wait allowed two completed probe opportunities. |
| + |
| + **Fix:** for the free-path case, drive further polls until a fresh heartbeat is observed, with a bounded overall deadline. Keep the wedged-path assertion separate so retries cannot conceal an incorrectly emitted heartbeat. |
| + |
| +No P3 findings. |
| + |
| +The remaining checks are satisfactory by inspection: |
| + |
| +- The production silence window remains three seconds. Its only assignments after initialization are in the test helper. Tests using that helper are sequential. The timer reads the variable synchronously during construction; its goroutine does not reread it. Successful forwarding tests await completion, and observation shutdown joins its callback. |
| +- The fake activator records notes before signaling. The service wrapper signals only after `Service.NoteForward` returns. These waits establish the ordering needed by the assertions. |
| +- The registry-watch sends correctly establish completion of preceding polls. Backdating the initial heartbeat preserves the distinction between a stale setup beat and a fresh watch beat. |
| +- The brief’s third check names the wrong test: the shortened six-window wait is in `TestSlowHolderResponseIsNotAborted`. `TestSlowHolderTwentySecondHeadersKeepForwarding` still retains the production window and waits twenty seconds ([forwardha_service_test.go:294](/home/paulca/amadan.net/carlos/platform-audit-edge-test-sleeps/internal/edge/forwardha_service_test.go:294)). The scaled wait is acceptable for the observation test, especially with that absolute-duration service witness retained. |
| + |
| +`git diff --check` passed. Targeted tests could not start: Go could not create its work directory in the read-only sandbox. No full suites ran. |
| + |
| +**Census verdict: approve the `internal/edge` envelope re-pin.** I read the declaration and observation lifecycle in [forwardha.go:509](/home/paulca/amadan.net/carlos/platform-audit-edge-test-sleeps/internal/edge/forwardha.go:509), lines 509–551, and its forwarding integration, lines 413–485. The sole production change converts the unchanged three-second constant into an unexported variable. It adds no root reads, paths, commands, or authority and weakens no production validation. The envelope-only overlay at [plan14-root-reads-audit-edge-test-sleeps.tsv:3](/home/paulca/amadan.net/carlos/platform-audit-edge-test-sleeps/internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv:3) is appropriate; no unit dispositions change. |
| + |
| +Apply the P2 fixes without reopening review, per the stopping rule. |
| + |
| +READY AFTER FIXES |
| \ No newline at end of file |
diff --git a/docs/superpowers/reviews/REVIEW-BRIEF-audit-edge-test-sleeps.md b/docs/superpowers/reviews/REVIEW-BRIEF-audit-edge-test-sleeps.md| new file mode 100644 |
| index 000000000..d576085a1 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/REVIEW-BRIEF-audit-edge-test-sleeps.md |
| @@ -0,0 +1,42 @@ |
| +# Review brief: branch audit-edge-test-sleeps, round 1 of 3 |
| + |
| +Repo carlos/platform, branch `audit-edge-test-sleeps`, commit e888da4a7334ec6bee198ad126ebcd4e019a66c2. |
| +Under review: the diff `origin/main...e888da4a7334ec6bee198ad126ebcd4e019a66c2` (base c4b44c34). |
| +Authorities: AGENTS.md on main ("The census", "Stopping rules"). |
| +Context: amadan #1123, batch 2. |
| + |
| +You are the independent reviewer and the census reviewer. Card: |
| +`docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md` |
| +(envelope re-pin only; no unit changed). Give a verdict for the envelope, |
| +citing the lines you read. |
| + |
| +## What to check |
| + |
| +1. `holderHeaderSuspectAfter` const to package var (internal/edge/forwardha.go): |
| + production value unchanged, nothing in production writes it, and no |
| + data race between a test setter and running timers (are tests that |
| + shrink it parallel? any goroutine reading it outliving the test?). |
| +2. Each rewritten test still tests what it did: the lbhealth watch tests |
| + (watchTick ticks, stamped-in-the-past beats instead of a 5 s sleep), |
| + the home map clock seam, the forwardha and forwardha_service tests |
| + (fake activator note channel, the wrapper signalling a handled silence |
| + report). Could any now pass against a broken implementation? |
| +3. `TestSlowHolderTwentySecondHeadersKeepForwarding`: its wait now scales |
| + with the window (about six windows) instead of a fixed 17 s. Is losing |
| + the absolute 20 s check acceptable given the test swaps its own |
| + transport? |
| +4. Flake risk: any 100 ms windows or channel waits that could misfire on |
| + a loaded CI runner? |
| + |
| +## Severity |
| + |
| +- **P1**: unsafe, would not compile, a test fails, or it would not work. |
| +- **P2**: wrong or missing. Fixed without reopening this review. |
| +- **P3**: clarity or polish. Follow-up list only. |
| + |
| +## Output |
| + |
| +Findings ranked P1, P2, P3 with file:line, failure scenario and fix. Then |
| +the census verdict. End with exactly one verdict: READY, READY AFTER |
| +FIXES, or NOT READY. Do not edit files, spawn reviewers or run full |
| +suites. |
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..c61eb8c75 100644 |
| --- a/internal/edge/lbhealth_test.go |
| +++ b/internal/edge/lbhealth_test.go |
| @@ -7,6 +7,7 @@ import ( |
| "net/http/httptest" |
| "os" |
| "path/filepath" |
| + "slices" |
| "strings" |
| "testing" |
| "time" |
| @@ -64,9 +65,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,16 +155,23 @@ 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) |
| } |
| - // A bucket outage: the attempt fails but finishes, and the latches hold. |
| + // A bucket outage a minute later: the attempt fails but finishes, and |
| + // the latches hold. A window after it, the good refresh's stamp has |
| + // aged out, so only the failed attempt's own stamp keeps it fresh. |
| + clk.advance(time.Minute) |
| 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 +185,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 +239,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 +321,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 +346,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,13 +357,26 @@ 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. |
| - now := time.Now().Add(lbhealth.HeartbeatWindow - 3*time.Second) |
| + 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. |
| + ahead := func() time.Time { return time.Now().Add(lbhealth.HeartbeatWindow - 3*time.Second) } |
| + if !wedge { |
| + // A free path's probe can still lose to servingProbeTimeout on a |
| + // loaded box, and that poll records no beat: keep polling until one |
| + // beats, within a bound. The wedged case takes no retries, so a |
| + // retry cannot hide a beat it should never emit. |
| + deadline := time.Now().Add(5 * time.Second) |
| + for slices.Contains(h.Failing(ahead()), lbhealth.CondEdge) && time.Now().Before(deadline) { |
| + sendTick(t, tick) |
| + sendTick(t, tick) |
| + } |
| + } |
| + now := ahead() |
| got := h.Failing(now) |
| w := httptest.NewRecorder() |
| lbhealth.Serve(w, httptest.NewRequest(http.MethodGet, lbhealth.Path, nil), h, now) |
diff --git a/internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv b/internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv| new file mode 100644 |
| index 000000000..b5281fcfa |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-audit-edge-test-sleeps.tsv |
| @@ -0,0 +1,3 @@ |
| +# Census overlay audit-edge-test-sleeps, written by census-propose (#369). census-ruling-audit-edge-test-sleeps, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-audit-edge-test-sleeps.md. |
| +# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage internal/edge 520e8933785b5a5c512d6c465ec7dd00f855c77301bfeec979876718bbbb58c4 |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 4d0d769ad..485438ebf 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -238,3 +238,4 @@ plan14-root-reads-audit-request-path.tsv 3f7dc37d114377b168c6bc1ae48e7bf815dbc1f |
| plan14-root-reads-audit-gate-vet-staticcheck.tsv d4d3f367ca135da40d2c392d22b51669281d2d8268c0a5aa22ebf738cbe65080 |
| plan14-root-reads-audit-aws-timeouts.tsv c3e74a3069651a7ae638b2ecba5e38c4dbaec2831865318a52f254b5a041160f |
| plan14-root-reads-config-receipts-1.tsv 4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f |
| +plan14-root-reads-audit-edge-test-sleeps.tsv 4abde13ec40d53a479684b7f1e2079fbedb6c40cb1a28819c97853cdab768b2f |