test: make six timing-dependent tests deterministic (#526)
Activator rootfs release and worker tests and the edge held-stream tests asserted real wall-clock bounds and failed on a loaded CI runner. They now run on virtual time (testing/synctest) or wait for the event they assert. The held-stream simulation keeps all 300 seeds, tightens its bound from 185 ms to 160 ms and falls from about 195 s to 1 s. The WebSocket test owns its backend listener. Test-only; Astra implemented, Opus reviewed (P1 fixed: the sim's task-end check is kept). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from ci-timing-flakes-526 into main.
5 files changed,
+165
−126
internal/activator/rootfs_wake_release_test.go+3 −3internal/activator/rootfsrelease_test.go+85 −67internal/activator/rootfsworkers_test.go+10 −3internal/edge/heldstream_sim_test.go+46 −50internal/edge/localhold_test.go+21 −3
CI passed — run details
diff --git a/internal/activator/rootfs_wake_release_test.go b/internal/activator/rootfs_wake_release_test.go| index f177ffac8..ef5968c3c 100644 |
| --- a/internal/activator/rootfs_wake_release_test.go |
| +++ b/internal/activator/rootfs_wake_release_test.go |
| @@ -1042,9 +1042,9 @@ func TestReleaseObligationRetriedUntilProven(t *testing.T) { |
| if p, l := r.index("release:proven:v2"), r.index("release-lease"); p < 0 || l < p { |
| t.Fatalf("order %v: the lease went back before the proof", r.b.events()) |
| } |
| - if pinnedSettled(t, r.a, host, "v2") { |
| - t.Fatal("the generations file still names v2 after the proof") |
| - } |
| + // The pin leaves the file after the record goes (releaseProven persists |
| + // the generations once the record is deleted), so wait for it. |
| + waitFor(t, "the pin to leave the generations file", func() bool { return !pinnedSettled(t, r.a, host, "v2") }) |
| ch := r.wake(r.a) |
| r.nextUnit(t).done("exited", "0", "success") |
| if err := waitErr(t, ch); err != nil { |
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go| index 0f2b75d69..2a39a13cb 100644 |
| --- a/internal/activator/rootfsrelease_test.go |
| +++ b/internal/activator/rootfsrelease_test.go |
| @@ -24,6 +24,7 @@ import ( |
| "sync" |
| "sync/atomic" |
| "testing" |
| + "testing/synctest" |
| "time" |
| "github.com/carlosframework/platform/internal/hostclaim" |
| @@ -702,8 +703,17 @@ func (r *releaseRig) noRecord(t *testing.T, when string) { |
| } |
| // pinned reports whether the generations file on disk names build v under |
| -// the host. |
| +// the host. Publication writes the sequence marker before the generations |
| +// file, so pinnedSettled retries reads made between those two writes. |
| func pinned(t *testing.T, a *Service, host, v string) bool { |
| + t.Helper() |
| + return pinnedSettled(t, a, host, v) |
| +} |
| + |
| +// pinnedNow is pinned without the retry: one read, and a half-written file |
| +// fails. For a check whose point is ordering (the file is complete before |
| +// something else happens), where waiting for the write would hide the bug. |
| +func pinnedNow(t *testing.T, a *Service, host, v string) bool { |
| t.Helper() |
| g, err := release.ReadGenerations(a.GenerationsFile) |
| if err != nil { |
| @@ -788,7 +798,9 @@ func TestReleaseBuildPublishedBeforeExec(t *testing.T) { |
| r := newReleaseRig(t) |
| sawPin, sawRecord := false, false |
| r.b.onStart = func() { |
| - sawPin = pinned(t, r.a, r.rt.Host, "v2") |
| + // Strict: the file must already be complete when the release |
| + // starts, so a write still in flight is a failure, not a wait. |
| + sawPin = pinnedNow(t, r.a, r.rt.Host, "v2") |
| sawRecord = r.record() != nil |
| } |
| r.b.unit.done("1", "0", "success") |
| @@ -1139,72 +1151,78 @@ func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) { |
| } |
| func TestReleaseLeaseLossUnprovenLeavesTheHold(t *testing.T) { |
| - shrinkRelease(t, 200*time.Millisecond, 10*time.Millisecond) |
| - r := newReleaseRig(t) |
| - until := time.Now().Add(800 * time.Millisecond) |
| - r.held = newOwnedLease(until, false) |
| - var stuck sync.Mutex |
| - isStuck := true |
| - r.b.unit.settle = func(int) error { |
| - stuck.Lock() |
| - defer stuck.Unlock() |
| - if isStuck { |
| - return errors.New("processes remained in the unit's cgroup") |
| + // The settle loop, the supervisor and the lease deadline all read the real |
| + // clock, so under load a settle could start after the deadline by sleep |
| + // overshoot alone. A synctest bubble gives them one fake clock: sleeps are |
| + // exact and the deadline comparison is deterministic. |
| + synctest.Test(t, func(t *testing.T) { |
| + shrinkRelease(t, 200*time.Millisecond, 10*time.Millisecond) |
| + r := newReleaseRig(t) |
| + until := time.Now().Add(800 * time.Millisecond) |
| + r.held = newOwnedLease(until, false) |
| + var stuck sync.Mutex |
| + isStuck := true |
| + r.b.unit.settle = func(int) error { |
| + stuck.Lock() |
| + defer stuck.Unlock() |
| + if isStuck { |
| + return errors.New("processes remained in the unit's cgroup") |
| + } |
| + return nil |
| } |
| - return nil |
| - } |
| - ch := r.run(context.Background()) |
| - r.waitStarted(t) |
| - r.held.lose(lease.ErrLost) |
| - res := wait(t, ch) |
| - if !errors.Is(res.err, errReleaseUnproven) || !errors.Is(res.err, errSwapLeaseLost) { |
| - t.Fatalf("runRelease = %v, want errReleaseUnproven and errSwapLeaseLost", res.err) |
| - } |
| - if o := classifyRelease(res.err, true); o != releaseUnproven { |
| - t.Errorf("classified %v, want unproven", o) |
| - } |
| - stops := r.b.unit.stopTimes() |
| - if len(stops) < 2 { |
| - t.Errorf("the settle was tried %d times after the trip, want it retried until the deadline", len(stops)) |
| - } |
| - if last := stops[len(stops)-1]; last.After(until) { |
| - t.Errorf("a settle began at %v, after the deadline %v", last, until) |
| - } |
| - op := r.record() |
| - if op == nil { |
| - t.Fatal("the record went with its unit unproven") |
| - } |
| - r.a.mu.Lock() |
| - state := op.state |
| - r.a.mu.Unlock() |
| - if state != releaseNotProven { |
| - t.Errorf("record state %d, want releaseNotProven (the reaper's)", state) |
| - } |
| - if evs := r.events(); slices.Contains(evs, fmt.Sprintf(rolloutwords.EventReleaseLeaseLost, "v2")) { |
| - t.Errorf("C29 with the unit unproven: %q", evs) |
| - } |
| - if !pinned(t, r.a, r.rt.Host, "v2") { |
| - t.Error("the generations file does not name v2 while its unit is unproven") |
| - } |
| - // The reaper owns it now: once the group empties, the sweep's pass |
| - // proves it. |
| - n := len(stops) |
| - r.a.mu.Lock() |
| - r.a.finishPendingStops() |
| - r.a.mu.Unlock() |
| - time.Sleep(50 * time.Millisecond) |
| - if got := len(r.b.unit.stopTimes()); got != n { |
| - t.Fatalf("the reaper retried %d times inside actStopTimeout", got-n) |
| - } |
| - stuck.Lock() |
| - isStuck = false |
| - stuck.Unlock() |
| - r.clk.advance(actStopTimeout) |
| - r.a.mu.Lock() |
| - r.a.finishPendingStops() |
| - r.a.mu.Unlock() |
| - waitFor(t, "the reaper's proof", func() bool { return r.record() == nil }) |
| - waitFor(t, "the pin to go", func() bool { return !pinned(t, r.a, r.rt.Host, "v2") }) |
| + ch := r.run(context.Background()) |
| + r.waitStarted(t) |
| + r.held.lose(lease.ErrLost) |
| + res := wait(t, ch) |
| + if !errors.Is(res.err, errReleaseUnproven) || !errors.Is(res.err, errSwapLeaseLost) { |
| + t.Fatalf("runRelease = %v, want errReleaseUnproven and errSwapLeaseLost", res.err) |
| + } |
| + if o := classifyRelease(res.err, true); o != releaseUnproven { |
| + t.Errorf("classified %v, want unproven", o) |
| + } |
| + stops := r.b.unit.stopTimes() |
| + if len(stops) < 2 { |
| + t.Errorf("the settle was tried %d times after the trip, want it retried until the deadline", len(stops)) |
| + } |
| + if last := stops[len(stops)-1]; last.After(until) { |
| + t.Errorf("a settle began at %v, after the deadline %v", last, until) |
| + } |
| + op := r.record() |
| + if op == nil { |
| + t.Fatal("the record went with its unit unproven") |
| + } |
| + r.a.mu.Lock() |
| + state := op.state |
| + r.a.mu.Unlock() |
| + if state != releaseNotProven { |
| + t.Errorf("record state %d, want releaseNotProven (the reaper's)", state) |
| + } |
| + if evs := r.events(); slices.Contains(evs, fmt.Sprintf(rolloutwords.EventReleaseLeaseLost, "v2")) { |
| + t.Errorf("C29 with the unit unproven: %q", evs) |
| + } |
| + if !pinned(t, r.a, r.rt.Host, "v2") { |
| + t.Error("the generations file does not name v2 while its unit is unproven") |
| + } |
| + // The reaper owns it now: once the group empties, the sweep's pass |
| + // proves it. |
| + n := len(stops) |
| + r.a.mu.Lock() |
| + r.a.finishPendingStops() |
| + r.a.mu.Unlock() |
| + time.Sleep(50 * time.Millisecond) |
| + if got := len(r.b.unit.stopTimes()); got != n { |
| + t.Fatalf("the reaper retried %d times inside actStopTimeout", got-n) |
| + } |
| + stuck.Lock() |
| + isStuck = false |
| + stuck.Unlock() |
| + r.clk.advance(actStopTimeout) |
| + r.a.mu.Lock() |
| + r.a.finishPendingStops() |
| + r.a.mu.Unlock() |
| + waitFor(t, "the reaper's proof", func() bool { return r.record() == nil }) |
| + waitFor(t, "the pin to go", func() bool { return !pinned(t, r.a, r.rt.Host, "v2") }) |
| + }) |
| } |
| func TestReleaseLeaseLossRacesExit(t *testing.T) { |
diff --git a/internal/activator/rootfsworkers_test.go b/internal/activator/rootfsworkers_test.go| index 30bd37871..b9c7ec61b 100644 |
| --- a/internal/activator/rootfsworkers_test.go |
| +++ b/internal/activator/rootfsworkers_test.go |
| @@ -918,9 +918,16 @@ func TestRootfsWorkerUnprovenKeepsItsFiles(t *testing.T) { |
| ctl.umu.Lock() |
| ctl.workerStopErr = nil |
| ctl.umu.Unlock() |
| - clk.advance(actStopTimeout) |
| - a.sweepOnce() |
| - waitFor(t, "the stop to finish", func() bool { return !a.hasEntry(rt.Host) }) |
| + // The pending state is visible while the stop's own proof attempt (the |
| + // reap goroutine) may still be in flight against the error just cleared. |
| + // A sweep that meets that attempt in flight skips the entry, and the |
| + // attempt may have read the old error, so one sweep is not enough: each |
| + // poll is a fresh sweep pass a stop-timeout later, until the proof holds. |
| + waitFor(t, "the stop to finish", func() bool { |
| + clk.advance(actStopTimeout) |
| + a.sweepOnce() |
| + return !a.hasEntry(rt.Host) |
| + }) |
| for _, f := range []string{launch, record} { |
| if _, err := os.Stat(f); !os.IsNotExist(err) { |
| t.Errorf("%s outlived the proof: %v", filepath.Base(f), err) |
diff --git a/internal/edge/heldstream_sim_test.go b/internal/edge/heldstream_sim_test.go| index a8530362c..ff5992b4d 100644 |
| --- a/internal/edge/heldstream_sim_test.go |
| +++ b/internal/edge/heldstream_sim_test.go |
| @@ -7,10 +7,12 @@ import ( |
| "math/rand" |
| "net/http" |
| "net/http/httptest" |
| + "runtime" |
| "strings" |
| "sync" |
| "sync/atomic" |
| "testing" |
| + "testing/synctest" |
| "time" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -33,11 +35,8 @@ import ( |
| // admissible, the stream has been running, and its last leg has been |
| // done for longer than Tick + ReopenSpacing + BackoffCap (spec G4: |
| // outside a bounded reopen delay, no silent stream past one tick). |
| -// An observation is conclusive only when the checker overslept by no |
| -// more than starveLimit anywhere in its window; others are skipped, |
| -// never excused by widening the bound. Each seed runs until it has at |
| -// least one conclusive H2 observation past the bound (up to maxRun) |
| -// and fails as inconclusive without one; |
| +// Virtual time advances only when all stream tasks are blocked. Each |
| +// seed must produce an H2 observation past the bound (up to maxRun); |
| // H3: a stream never has two legs open at once. |
| // At the end of each seed every admitted leg must have been Done. |
| @@ -246,24 +245,28 @@ func (w *simWriter) Write(b []byte) (int, error) { w.n.Add(int64(len(b))); retur |
| func (w *simWriter) Flush() {} |
| func TestHeldStreamLifecycleSim(t *testing.T) { |
| - if testing.Short() { |
| - t.Skip("simulation") |
| + // Go 1.26 shares a race context between bubble timers: concurrent timer |
| + // callbacks can crash TSan (golang/go#76691, fixed in Go 1.27). Keep all |
| + // seeds and assertions under -race; ordinary builds still run on every CPU. |
| + if raceEnabled && strings.HasPrefix(runtime.Version(), "go1.26.") { |
| + defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1)) |
| } |
| + synctest.Test(t, heldStreamLifecycleSim) |
| +} |
| + |
| +func heldStreamLifecycleSim(t *testing.T) { |
| const ( |
| - seeds = 300 |
| - runFor = 600 * time.Millisecond |
| - maxRun = 10 * time.Second |
| - slack = 25 * time.Millisecond // fixed scheduler jitter allowance |
| - checkEv = 5 * time.Millisecond |
| - starveLimit = 20 * time.Millisecond |
| + seeds = 300 |
| + runFor = 600 * time.Millisecond |
| + maxRun = 10 * time.Second |
| + checkEv = 5 * time.Millisecond |
| ) |
| cfg := heldTestConfig() |
| cfg.MaxHold = time.Minute |
| cfg.LegHeader = time.Second |
| cfg.Commit = 20 * time.Millisecond // the timing the simulation was calibrated with |
| - bound := cfg.Tick + cfg.ReopenSpacing + cfg.BackoffCap + slack |
| - var totalAdmitted, totalClosedShort, conclusiveTotal, skipped int |
| - var maxLag time.Duration |
| + bound := cfg.Tick + cfg.ReopenSpacing + cfg.BackoffCap |
| + var totalAdmitted, totalClosedShort, conclusiveTotal int |
| for seed := int64(1); seed <= seeds; seed++ { |
| m := newSimModel(seed) |
| rng := rand.New(rand.NewSource(seed * 7919)) |
| @@ -338,23 +341,33 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| } |
| }() |
| - // Check the invariants. The checker measures its own oversleep; an H2 |
| - // window it was starved in for more than starveLimit says nothing |
| - // about the stream task, so that observation is skipped. A fresh |
| - // window starts when the oversleep ends: the bound is never widened, |
| - // it is only measured over a window with no oversleep in it. |
| - var lastStarve time.Time |
| - starves := 0 |
| + var stopOnce sync.Once |
| + stop := func() { |
| + stopOnce.Do(func() { |
| + close(stopDrive) |
| + <-driveDone |
| + cancel() |
| + // Bounded, in virtual time: a stream task that ignores its |
| + // client going would otherwise run out MaxHold instantly |
| + // inside the bubble and pass. |
| + waited := make(chan struct{}) |
| + go func() { wg.Wait(); close(waited) }() |
| + select { |
| + case <-waited: |
| + case <-time.After(5 * time.Second): |
| + t.Errorf("seed %d: stream tasks did not end within 5s of cancel", seed) |
| + <-waited |
| + } |
| + }) |
| + } |
| + defer stop() |
| + |
| + // Let every task runnable at this virtual instant finish before checking. |
| conclusive := 0 |
| for time.Since(start) < runFor || (conclusive == 0 && time.Since(start) < maxRun) { |
| - before := time.Now() |
| time.Sleep(checkEv) |
| + synctest.Wait() |
| now := time.Now() |
| - if lag := now.Sub(before) - checkEv; lag > starveLimit { |
| - lastStarve = now |
| - starves++ |
| - maxLag = max(maxLag, lag) |
| - } |
| if m.served.Load() != 0 { |
| t.Fatalf("seed %d: H1: activator ServeHTTP called", seed) |
| } |
| @@ -373,10 +386,6 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| quiet = le |
| } |
| if q := now.Sub(quiet); q > bound { |
| - if now.Sub(lastStarve) <= bound { |
| - skipped++ // no unstarved window past the bound yet |
| - continue |
| - } |
| conclusive++ |
| if m.open[i] == 0 { |
| m.violate("H2: stream %d has no leg %v into an admissible window (bound %v)", i, q, bound) |
| @@ -392,29 +401,16 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| v := append([]string(nil), m.violations...) |
| m.mu.Unlock() |
| if len(v) > 0 { |
| - close(stopDrive) |
| - cancel() |
| t.Fatalf("seed %d (n=%d): %v\nhistory:\n%s", seed, n, v, strings.Join(m.history, "\n")) |
| } |
| } |
| if conclusive == 0 { |
| - close(stopDrive) |
| - cancel() |
| - t.Fatalf("seed %d: inconclusive: no H2 observation past the bound in an unstarved window within %v (%d checker oversleeps over %v)", seed, maxRun, starves, starveLimit) |
| + t.Fatalf("seed %d: no H2 observation past the bound within %v", seed, maxRun) |
| } |
| conclusiveTotal += conclusive |
| - close(stopDrive) |
| - <-driveDone |
| - cancel() |
| - waited := make(chan struct{}) |
| - go func() { wg.Wait(); close(waited) }() |
| - select { |
| - case <-waited: |
| - case <-time.After(5 * time.Second): |
| - t.Fatalf("seed %d: stream tasks did not end", seed) |
| - } |
| + stop() |
| m.mu.Lock() |
| if len(m.legs) != 0 { |
| t.Fatalf("seed %d: %d admitted legs never Done", seed, len(m.legs)) |
| @@ -426,8 +422,8 @@ func TestHeldStreamLifecycleSim(t *testing.T) { |
| } |
| totalClosedShort += int(closedShort.Load()) |
| } |
| - t.Logf("%d seeds: %d legs admitted, %d streams closed by short legs; H2 observations past the bound: %d conclusive, %d skipped as starved (worst checker oversleep over %v: %v)", |
| - seeds, totalAdmitted, totalClosedShort, conclusiveTotal, skipped, starveLimit, maxLag) |
| + t.Logf("%d seeds: %d legs admitted, %d streams closed by short legs; %d H2 observations past the bound", |
| + seeds, totalAdmitted, totalClosedShort, conclusiveTotal) |
| if totalAdmitted == 0 { |
| t.Fatal("no leg was ever admitted") |
| } |
diff --git a/internal/edge/localhold_test.go b/internal/edge/localhold_test.go| index 314a4b996..44705dc66 100644 |
| --- a/internal/edge/localhold_test.go |
| +++ b/internal/edge/localhold_test.go |
| @@ -316,9 +316,24 @@ func TestHeldDialPOSTBodyArrives(t *testing.T) { |
| } |
| func TestHeldDialWebSocketUpgrade(t *testing.T) { |
| - a := deadAddr(t) |
| - listenLater(t, a, 300*time.Millisecond, upgradeEchoHandler("ws")) |
| - _, srv := holdEdge(t, a, localHold{dial: 2 * time.Second, probe: probeTimeout}) |
| + // The backend is owned for the whole test and the first dials are refused |
| + // by an injected dialer, so the hold's retry path runs against this exact |
| + // server. A closed-then-rebound port (deadAddr + listenLater) can be taken |
| + // by another process in the gap, and the test would then upgrade against |
| + // a stranger. |
| + backend := httptest.NewServer(upgradeEchoHandler("ws")) |
| + t.Cleanup(backend.Close) |
| + backendAddr := backend.Listener.Addr().String() |
| + const refusals = 3 |
| + var attempts atomic.Int32 |
| + hold := localHold{dial: 2 * time.Second, probe: probeTimeout, |
| + dialer: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + if attempts.Add(1) <= refusals { |
| + return nil, refusedErr() |
| + } |
| + return (&net.Dialer{}).DialContext(ctx, network, backendAddr) |
| + }} |
| + _, srv := holdEdge(t, backendAddr, hold) |
| c, err := net.Dial("tcp", strings.TrimPrefix(srv.URL, "http://")) |
| if err != nil { |
| @@ -351,6 +366,9 @@ func TestHeldDialWebSocketUpgrade(t *testing.T) { |
| if rest != "ws:hello\n" { |
| t.Fatalf("echo = %q, want %q", rest, "ws:hello\n") |
| } |
| + if n := attempts.Load(); n != refusals+1 { |
| + t.Fatalf("dial attempts = %d, want %d (%d refused, then the backend)", n, refusals+1, refusals) |
| + } |
| } |
| func TestHeldDialsReleaseAfterHold(t *testing.T) { |