carlos / platform Public

activator tests: join the goroutines tests start before restores

CI on 71470f23 raced: TestTakeBoundOnAFirstWake started its own waiter
goroutine, whose beginRequest read wakeWaitBound in awaitWake with no
happens-before edge to the setKnob restore. The stack join saw it gone
and syncWithServices only orders goroutines that end under a.mu or by
the background decrement.

goTracked (and afterTracked for timers) starts a test goroutine whose
last act leaves a set under knobRestores lock; joinGoroutines waits for
that set and the production stacks together, then restores.
TestKnobTestsStartNoUntrackedGoroutine scans the test files and fails
on a go statement, time.AfterFunc or Go method in code a
setting-changing test reaches, or in any test-type method. 116 starts
converted. Comments on runKnobRestores and syncWithServices now state
the actual ordering rule. Tests only; no production change.

Refs #1249
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 5b4c932a407c92993b43d1fa1090d1127bc926ca parent 7c936c4
50 files changed, +549 −202
  • AGENTS.md +5 −1
  • internal/activator/activator_test.go +2 −2
  • internal/activator/backend_exec_test.go +7 −7
  • internal/activator/backend_unit_test.go +1 −1
  • internal/activator/childwait_test.go +2 −2
  • internal/activator/cmd_test.go +2 −2
  • internal/activator/escrow_linux_test.go +2 −2
  • internal/activator/escrow_test.go +2 −2
  • internal/activator/hadrain_test.go +1 −1
  • internal/activator/hadrainmove_test.go +4 −4
  • internal/activator/haduties_test.go +3 −3
  • internal/activator/hafiles_test.go +4 −4
  • internal/activator/haforward_test.go +1 −1
  • internal/activator/haleaseloss_test.go +3 −3
  • internal/activator/handover_test.go +9 −9
  • internal/activator/haplacement_test.go +3 −3
  • internal/activator/harelease_shutdown_test.go +3 −3
  • internal/activator/harelease_test.go +2 −2
  • internal/activator/hasecrets_test.go +2 −2
  • internal/activator/hasuspect_test.go +2 −2
  • internal/activator/hatake_test.go +3 −3
  • internal/activator/heldstream_e2e_test.go +1 −1
  • internal/activator/holdran_event_test.go +1 −1
  • internal/activator/knobguard_test.go +228 −0
  • internal/activator/knobrestore_test.go +134 −19
  • internal/activator/movestreams_test.go +3 −3
  • internal/activator/opset_test.go +2 −2
  • internal/activator/outcome_fence_test.go +2 −2
  • internal/activator/pendingwake_linux_test.go +7 −7
  • internal/activator/rawsecret_test.go +2 −2
  • internal/activator/replicadeploy_test.go +2 −2
  • internal/activator/rootfs_cmd_test.go +2 −2
  • internal/activator/rootfs_ctl_harness_test.go +2 −2
  • internal/activator/rootfs_release_backend_test.go +2 −2
  • internal/activator/rootfs_resident_test.go +2 −2
  • internal/activator/rootfs_swap_release_test.go +3 −3
  • internal/activator/rootfs_wake_release_test.go +2 −2
  • internal/activator/rootfsrelease_test.go +8 −8
  • internal/activator/rootfsworkers_backend_test.go +2 −2
  • internal/activator/seed_rollback_stop_test.go +2 −2
  • internal/activator/settle_test.go +5 −5
  • internal/activator/statelessrelease_test.go +1 −1
  • internal/activator/swap_executed_test.go +2 −2
  • internal/activator/swap_hold_test.go +3 −3
  • internal/activator/swap_review_test.go +3 −3
  • internal/activator/swap_sim_test.go +13 −13
  • internal/activator/wakeplan_test.go +6 −6
  • internal/activator/wakeslots_test.go +2 −2
  • internal/activator/workerswap_test.go +33 −33
  • internal/activator/writefence_test.go +11 −11
diff --git a/AGENTS.md b/AGENTS.md
index 59fe7e7b6..b26350261 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -307,7 +307,11 @@ anything.
`newTrackedService`, so the restore waits for the test's wakes. A
subtest may not change one while a Service it does not own runs (its
parent's, or one it built first): `setKnob` fails it, and the setting
- goes in the parent, before the parent builds anything.
+ goes in the parent, before the parent builds anything. Test code such
+ a test can reach starts goroutines with `goTracked` (timers with
+ `afterTracked`), never `go`, `time.AfterFunc` or a `Go` method, so the
+ restore waits for them too;
+ `TestKnobTestsStartNoUntrackedGoroutine` enforces it.
`internal/lease` is out for now (`.amadan/README.md` says why).
- `80-gitleaks` runs `make gitleaks` (v8.30.1, pinned) over the tracked
files through `scripts/gitleaks-gate`, which first proves that planted
diff --git a/internal/activator/activator_test.go b/internal/activator/activator_test.go
index 5bb78d173..73112bbe2 100644
--- a/internal/activator/activator_test.go
+++ b/internal/activator/activator_test.go
@@ -3698,7 +3698,7 @@ func TestWorkerTokenIsLiveDuringTheSettleWindow(t *testing.T) {
setKnob(t, &sidecarSettle, 5*time.Second)
done := make(chan error, 1)
- go func() { done <- a.WakeWorker(testWorkerRoute("bot.x.internal")) }()
+ goTracked(func() { done <- a.WakeWorker(testWorkerRoute("bot.x.internal")) })
waitFor(t, "the waking entry to appear", func() bool { return a.Owns("bot.x.internal") })
waitFor(t, "the child to be spawned", func() bool { return b.workerStarts() == 1 })
@@ -3768,7 +3768,7 @@ func TestWorkerReadyEndsSettleWindowEarly(t *testing.T) {
done := make(chan error, 1)
start := time.Now()
- go func() { done <- a.WakeWorker(testWorkerRoute("bot.x.internal")) }()
+ goTracked(func() { done <- a.WakeWorker(testWorkerRoute("bot.x.internal")) })
waitFor(t, "the waking entry to appear", func() bool { return a.Owns("bot.x.internal") })
// The entry appears before the wake has minted the token and spawned the
diff --git a/internal/activator/backend_exec_test.go b/internal/activator/backend_exec_test.go
index c6ceab78b..4d7a10f07 100644
--- a/internal/activator/backend_exec_test.go
+++ b/internal/activator/backend_exec_test.go
@@ -1207,11 +1207,11 @@ func TestAnOlderExitCannotRemoveANewOwnersGroup(t *testing.T) {
var settle func()
var cmd *exec.Cmd
b.strictHook = hookAt("exit-cleanup-checked", func() {
- go func() {
+ goTracked(func() {
var err error
cmd, settle, err = b.spawnInCgroup(registry.Route{Host: host}, func() *exec.Cmd { return exec.Command("/bin/true") })
spawned <- err
- }()
+ })
select {
case err := <-spawned:
t.Errorf("a strict spawn took the host while an exit held its gate: %v", err)
@@ -1281,7 +1281,7 @@ func TestAPendingTransitionRacesARefusal(t *testing.T) {
for i := 0; i < 8; i++ {
wg.Add(1)
looping.Add(1)
- go func() {
+ goTracked(func() {
defer wg.Done()
first := true
for {
@@ -1300,7 +1300,7 @@ func TestAPendingTransitionRacesARefusal(t *testing.T) {
default:
}
}
- }()
+ })
}
looping.Wait()
b.settleStrict(host2, o2) // turns pending while the refusals run
@@ -1388,7 +1388,7 @@ func TestSwitchedOffSpawnsTakeNoNewLock(t *testing.T) {
b.strictMu.Lock()
defer b.strictMu.Unlock()
done := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(done)
rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(t.TempDir(), "i.sock")}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
@@ -1397,7 +1397,7 @@ func TestSwitchedOffSpawnsTakeNoNewLock(t *testing.T) {
if proc != nil {
_ = proc.Stop(context.Background())
}
- }()
+ })
select {
case <-done:
case <-time.After(5 * time.Second):
@@ -1406,7 +1406,7 @@ func TestSwitchedOffSpawnsTakeNoNewLock(t *testing.T) {
waitForFile(t, argvPath, time.Second)
// The exit path's call, again, with the lock held.
cleaned := make(chan struct{})
- go func() { b.cleanupHost(host); close(cleaned) }()
+ goTracked(func() { b.cleanupHost(host); close(cleaned) })
select {
case <-cleaned:
case <-time.After(2 * time.Second):
diff --git a/internal/activator/backend_unit_test.go b/internal/activator/backend_unit_test.go
index b2176dfe9..391a86b64 100644
--- a/internal/activator/backend_unit_test.go
+++ b/internal/activator/backend_unit_test.go
@@ -379,7 +379,7 @@ func TestUnitTenantWakeServesHeldRequest(t *testing.T) {
srvMu.Lock()
srv = s
srvMu.Unlock()
- go s.Serve(l)
+ goTracked(func() { s.Serve(l) })
}
sc.onStop = func() {
srvMu.Lock()
diff --git a/internal/activator/childwait_test.go b/internal/activator/childwait_test.go
index cc7240d06..ff323b6b8 100644
--- a/internal/activator/childwait_test.go
+++ b/internal/activator/childwait_test.go
@@ -107,7 +107,7 @@ func recordedCtx(within time.Duration, paths ...string) (context.Context, contex
// for when it sat out the timeout.
func ctxUntil(within time.Duration, done func() bool) (context.Context, context.CancelFunc) {
ctx, cancel := context.WithTimeout(context.Background(), within)
- go func() {
+ goTracked(func() {
t := time.NewTicker(5 * time.Millisecond)
defer t.Stop()
for {
@@ -121,7 +121,7 @@ func ctxUntil(within time.Duration, done func() bool) (context.Context, context.
return
}
}
- }()
+ })
return ctx, cancel
}
diff --git a/internal/activator/cmd_test.go b/internal/activator/cmd_test.go
index afcae2e66..3fe6acceb 100644
--- a/internal/activator/cmd_test.go
+++ b/internal/activator/cmd_test.go
@@ -621,10 +621,10 @@ func TestALostCmdResponseStopsTheCmdRoleBeforeReplicationCloses(t *testing.T) {
}
ctl.stopHook = func(_ string, role instancectl.Role) {
if role == instancectl.RoleCmd {
- go func() {
+ goTracked(func() {
time.Sleep(50 * time.Millisecond)
unit.set("inactive", "inv1", false, false)
- }()
+ })
}
}
cb.startCmd = b.StartCmd
diff --git a/internal/activator/escrow_linux_test.go b/internal/activator/escrow_linux_test.go
index 2f98dbd76..8d70ac955 100644
--- a/internal/activator/escrow_linux_test.go
+++ b/internal/activator/escrow_linux_test.go
@@ -70,7 +70,7 @@ func TestEscrowReadRefusesLinkFIFOAndOversize(t *testing.T) {
tc.plant(t, path)
done := make(chan EscrowSweepReport, 1)
- go func() { done <- b.EscrowSweep(context.Background(), []registry.Route{rt}) }()
+ goTracked(func() { done <- b.EscrowSweep(context.Background(), []registry.Route{rt}) })
var rep EscrowSweepReport
select {
case rep = <-done:
@@ -121,7 +121,7 @@ func TestFallbackIgnoresARefusedTrioPath(t *testing.T) {
t.Fatal(err)
}
done := make(chan error, 1)
- go func() { _, err := s.wakeForTest(context.Background()); done <- err }()
+ goTracked(func() { _, err := s.wakeForTest(context.Background()); done <- err })
select {
case err := <-done:
if err != nil {
diff --git a/internal/activator/escrow_test.go b/internal/activator/escrow_test.go
index 7f7c3c3e2..cab40d350 100644
--- a/internal/activator/escrow_test.go
+++ b/internal/activator/escrow_test.go
@@ -1252,14 +1252,14 @@ func TestSweepRacesNoLaunchOrWorker(t *testing.T) {
}
rows = append(rows, rt)
done := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(done)
for i := 0; i < 20; i++ {
if _, err := b.publishEscrow(ctx, rt, []byte(fmt.Sprintf("%sN=%d\n", envA, i))); err != nil {
t.Errorf("publish %d: %v", i, err)
}
}
- }()
+ })
for i := 0; i < 20; i++ {
rep := b.EscrowSweep(ctx, rows)
if len(rep.Failing) != 0 {
diff --git a/internal/activator/hadrain_test.go b/internal/activator/hadrain_test.go
index 6bb59dbbf..5ffb1b3ab 100644
--- a/internal/activator/hadrain_test.go
+++ b/internal/activator/hadrain_test.go
@@ -168,7 +168,7 @@ func TestDrainedDropOutlivesAPausedRead(t *testing.T) {
return holderRead{Ref: "b", View: &hafresh.View{}}
}
got := make(chan holderResolution, 1)
- go func() { got <- c.resolve(context.Background(), host, read) }()
+ goTracked(func() { got <- c.resolve(context.Background(), host, read) })
<-paused
s.a.DropHoldersNaming("a") // the fold's drained effect, before its ack
close(resume)
diff --git a/internal/activator/hadrainmove_test.go b/internal/activator/hadrainmove_test.go
index 3fea75532..1397b4cff 100644
--- a/internal/activator/hadrainmove_test.go
+++ b/internal/activator/hadrainmove_test.go
@@ -119,10 +119,10 @@ func TestDrainQuietWaitsForAnAcquireBeforeItsPUT(t *testing.T) {
}
})
woke := make(chan error, 1)
- go func() {
+ goTracked(func() {
_, err := s.wakeForTest(context.Background())
woke <- err
- }()
+ })
<-paused
if q := s.a.DrainQuietNow(); q.Waking != 1 || q.Zero() {
t.Fatalf("quiet with an acquire on its PUT: %+v", q)
@@ -183,10 +183,10 @@ func TestDrainHoldStats(t *testing.T) {
if r := s.a.MoveState(s.rt, edge.MoveAsk{Hop: true}); r.Phase != edge.MoveRefused {
t.Fatalf("a non-replayable hop: %+v", r)
}
- go func() {
+ goTracked(func() {
time.Sleep(50 * time.Millisecond)
s.a.SetMoveLeft(s.rt.Host, "test")
- }()
+ })
if got := d.Wait(context.Background()); got.Phase != edge.MoveRefused {
t.Fatalf("held: %+v", got)
}
diff --git a/internal/activator/haduties_test.go b/internal/activator/haduties_test.go
index 1079023fa..98d42481a 100644
--- a/internal/activator/haduties_test.go
+++ b/internal/activator/haduties_test.go
@@ -226,13 +226,13 @@ func TestHADutyVisitorCoalescing(t *testing.T) {
return boxchoice.WakeSnapshot{}
})
bg := make(chan error, 1)
- go func() {
+ goTracked(func() {
bg <- s.a.WithDuty(context.Background(), s.rt, func(context.Context) error { t.Error("losing background callback ran"); return nil })
- }()
+ })
<-entered
visitor := make(chan error, 1)
vc := &dutyWaitContext{Context: context.Background(), waiting: make(chan struct{})}
- go func() { _, err := s.wakeForTest(vc); visitor <- err }()
+ goTracked(func() { _, err := s.wakeForTest(vc); visitor <- err })
<-vc.waiting // the visitor is waiting on the background entry's ready channel
close(unblock)
if err := <-bg; !errors.Is(err, ErrDutyDeferred) {
diff --git a/internal/activator/hafiles_test.go b/internal/activator/hafiles_test.go
index 8345fb25f..5bb255890 100644
--- a/internal/activator/hafiles_test.go
+++ b/internal/activator/hafiles_test.go
@@ -112,7 +112,7 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) {
f.snapshotEvery = time.Hour
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- go f.Run(ctx)
+ goTracked(func() { f.Run(ctx) })
p := b.pathsFor(rt)
const env = "CARLOS_ADMIN_TOKEN=tok-5f2e9c\nCARLOS_INSTANCE_KEY=k1\n"
writeFiles(t, b, rt, map[string]string{"a.txt": "app", "instance.key": "key-8b41d7"})
@@ -161,7 +161,7 @@ func TestTrioPublishedWithinOneSecond(t *testing.T) {
f2.platformEvery, f2.snapshotEvery = time.Hour, 200*time.Millisecond
ctx2, cancel2 := context.WithCancel(context.Background())
defer cancel2()
- go f2.Run(ctx2)
+ goTracked(func() { f2.Run(ctx2) })
waitFor(t, "the snapshot of a.txt", func() bool { return loadManifest(t, b, rt).Entries["a.txt"].Object != "" })
}
@@ -244,7 +244,7 @@ func TestIncompleteSnapshotRunsAgainOverAnUnchangedTree(t *testing.T) {
})
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- go f.Run(ctx)
+ goTracked(func() { f.Run(ctx) })
waitFor(t, "a.txt published by a later snapshot", func() bool {
m, _, err := hostfiles.Load(context.Background(), b.FilesStore, b.filesPrefix(rt.Host))
return err == nil && m.Entries["a.txt"].Object != ""
@@ -277,7 +277,7 @@ func TestPlatformPublishesDuringASnapshot(t *testing.T) {
})
ctx, cancel := context.WithCancel(context.Background())
ran := make(chan struct{})
- go func() { defer close(ran); f.Run(ctx) }()
+ goTracked(func() { defer close(ran); f.Run(ctx) })
select {
case <-blocked:
case <-time.After(2 * time.Second):
diff --git a/internal/activator/haforward_test.go b/internal/activator/haforward_test.go
index 74fbfe1f5..ad49f7fa7 100644
--- a/internal/activator/haforward_test.go
+++ b/internal/activator/haforward_test.go
@@ -476,7 +476,7 @@ func TestForwardTargetStalledReadIsBounded(t *testing.T) {
start := time.Now()
got := make(chan string, 10)
for range cap(got) {
- go func() { got <- s.a.ForwardTarget(context.Background(), s.rt, nil).Ref }()
+ goTracked(func() { got <- s.a.ForwardTarget(context.Background(), s.rt, nil).Ref })
}
bound := time.After(holderReadTimeout + 2*time.Second)
for range cap(got) {
diff --git a/internal/activator/haleaseloss_test.go b/internal/activator/haleaseloss_test.go
index 2c8e6d50f..4c8e96107 100644
--- a/internal/activator/haleaseloss_test.go
+++ b/internal/activator/haleaseloss_test.go
@@ -511,7 +511,7 @@ func TestHALostRecoveryShutdownDoesNotWaitForWake(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond)
defer cancel()
done := make(chan struct{})
- go func() { s.a.Shutdown(ctx); close(done) }()
+ goTracked(func() { s.a.Shutdown(ctx); close(done) })
select {
case <-done:
case <-time.After(time.Second):
@@ -604,10 +604,10 @@ func TestHALostQueuedStopWaiterRefusesOnLoss(t *testing.T) {
defer cancel()
w := httptest.NewRecorder()
done := make(chan struct{})
- go func() {
+ goTracked(func() {
s.a.ServeHTTP(w, httptest.NewRequest("GET", "http://shop.example.com/", nil).WithContext(ctx), s.rt, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("proxied") }))
close(done)
- }()
+ })
select {
case <-done:
t.Fatal("ordinary stop did not wait")
diff --git a/internal/activator/handover_test.go b/internal/activator/handover_test.go
index 7aed4374e..037509531 100644
--- a/internal/activator/handover_test.go
+++ b/internal/activator/handover_test.go
@@ -37,7 +37,7 @@ func shortMoveBounds(t *testing.T, client, hop time.Duration) {
// waitAsync runs d.Wait in the background.
func waitAsync(ctx context.Context, d edge.MoveDecision) <-chan edge.MoveDecision {
ch := make(chan edge.MoveDecision, 1)
- go func() { ch <- d.Wait(ctx) }()
+ goTracked(func() { ch <- d.Wait(ctx) })
return ch
}
@@ -345,7 +345,7 @@ func TestMoveTicketsPausePoints(t *testing.T) {
t.Fatalf("the move did not wait for the ticket: %v", err)
}
done := make(chan error, 1)
- go func() { done <- s.a.WaitMoveTickets(t.Context(), s.rt.Host) }()
+ goTracked(func() { done <- s.a.WaitMoveTickets(t.Context(), s.rt.Host) })
time.Sleep(20 * time.Millisecond)
d.Done()
d.Done() // twice is once
@@ -368,7 +368,7 @@ func TestMoveTicketsPausePoints(t *testing.T) {
waited := make(chan error, 1)
wctx, wcancel := context.WithTimeout(t.Context(), 5*time.Second)
defer wcancel()
- go func() { waited <- s.a.WaitMoveTickets(wctx, s.rt.Host) }()
+ goTracked(func() { waited <- s.a.WaitMoveTickets(wctx, s.rt.Host) })
select {
case err := <-waited:
t.Fatalf("the move went on past a request ForwardTarget sent here: %v", err)
@@ -385,7 +385,7 @@ func TestMoveTicketsPausePoints(t *testing.T) {
})
r := edge.WithMoveTicket(httptest.NewRequest(http.MethodGet, "https://shop.example.com/", nil), d.Done)
served := make(chan bool, 1)
- go func() { served <- s.a.ServeHTTP(httptest.NewRecorder(), r, s.rt, proxy) }()
+ goTracked(func() { served <- s.a.ServeHTTP(httptest.NewRecorder(), r, s.rt, proxy) })
<-inProxy
if err := <-waited; err != nil {
t.Fatal(err)
@@ -409,19 +409,19 @@ func TestMoveTicketsPausePoints(t *testing.T) {
}
d := s.a.MoveState(s.rt, askClient)
stopDone := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(stopDone)
s.stopForTest(e)
- }()
+ })
<-stopping
ctx, cancel := context.WithCancel(t.Context())
r := edge.WithMoveTicket(httptest.NewRequestWithContext(ctx, http.MethodGet, "https://shop.example.com/", nil), d.Done)
served := make(chan struct{})
- go func() {
+ goTracked(func() {
s.a.ServeHTTP(httptest.NewRecorder(), r, s.rt, http.NotFoundHandler())
d.Done() // the edge's own end of the request
close(served)
- }()
+ })
waitUntil(t, "the request waiting in begin on the stop", func() bool {
s.a.mu.Lock()
defer s.a.mu.Unlock()
@@ -489,7 +489,7 @@ func TestConfirmMoveHolderCoalesced(t *testing.T) {
results := make(chan edge.MoveDecision, 20)
for range 20 {
wg.Add(1)
- go func() { defer wg.Done(); results <- s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()) }()
+ goTracked(func() { defer wg.Done(); results <- s.a.ConfirmMoveHolder(t.Context(), s.rt, snap()) })
}
wg.Wait()
close(results)
diff --git a/internal/activator/haplacement_test.go b/internal/activator/haplacement_test.go
index 9b2d9bb36..cdc0b7c7d 100644
--- a/internal/activator/haplacement_test.go
+++ b/internal/activator/haplacement_test.go
@@ -240,13 +240,13 @@ func TestPlacementSingleFlight(t *testing.T) {
})
ctx, cancel := context.WithCancel(context.Background())
first := make(chan edge.ForwardDecision, 1)
- go func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) }()
+ goTracked(func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) })
waitFor(t, "read", func() bool { return reads.Load() == 1 })
got := make(chan edge.ForwardDecision, 20)
for range 20 {
- go func() {
+ goTracked(func() {
got <- s.a.ForwardTarget(context.Background(), s.rt, func() boxchoice.WakeSnapshot { return placementSnapshot(time.Now()) })
- }()
+ })
}
cancel()
select {
diff --git a/internal/activator/harelease_shutdown_test.go b/internal/activator/harelease_shutdown_test.go
index 34b61d07f..7bcfc9347 100644
--- a/internal/activator/harelease_shutdown_test.go
+++ b/internal/activator/harelease_shutdown_test.go
@@ -92,7 +92,7 @@ func TestHAShutdownFinalDeadlineReservesMarker(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
deadline, _ := ctx.Deadline()
done := make(chan struct{})
- go func() { s.a.Shutdown(ctx); close(done) }()
+ goTracked(func() { s.a.Shutdown(ctx); close(done) })
t.Cleanup(func() { close(abort); cancel(); <-done; <-e.stopped })
f := awaitShutdownCall(t, final)
if remaining := f.deadline.Sub(f.at); remaining < 500*time.Millisecond || remaining > time.Second {
@@ -119,7 +119,7 @@ func TestHAShutdownStuckFinishWritesNoMarker(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second)
deadline, _ := ctx.Deadline()
done := make(chan struct{})
- go func() { s.a.Shutdown(ctx); close(done) }()
+ goTracked(func() { s.a.Shutdown(ctx); close(done) })
t.Cleanup(func() { close(unblock); cancel(); <-done; <-e.stopped })
select {
case <-entered:
@@ -204,7 +204,7 @@ func TestHAShutdownJoinsMarker(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
done := make(chan struct{})
- go func() { s.a.Shutdown(ctx); close(done) }()
+ goTracked(func() { s.a.Shutdown(ctx); close(done) })
t.Cleanup(func() {
select {
case <-unblock:
diff --git a/internal/activator/harelease_test.go b/internal/activator/harelease_test.go
index a48a4055d..8771f361d 100644
--- a/internal/activator/harelease_test.go
+++ b/internal/activator/harelease_test.go
@@ -472,7 +472,7 @@ func TestNoWriteAfterMarker(t *testing.T) {
stop := make(chan struct{})
var writer sync.WaitGroup
writer.Add(1)
- go func() { // keepWriting: the trio, an app file and the database
+ goTracked(func() { // keepWriting: the trio, an app file and the database
defer writer.Done()
db, _ := sql.Open("sqlite", s.b.pathsFor(s.rt).dbPath)
defer db.Close()
@@ -486,7 +486,7 @@ func TestNoWriteAfterMarker(t *testing.T) {
_ = os.WriteFile(filepath.Join(dir, "a.txt"), []byte(time.Now().String()), 0o600)
_, _ = db.Exec("insert into t values (?)", i)
}
- }()
+ })
time.Sleep(1500 * time.Millisecond) // the publisher's platform pass has run
s.unit.set(func(u *haUnit) { u.active, u.unitPop, u.slicePop = "inactive", false, false })
if err := s.a.releaseHAClean(context.Background(), e); err != nil {
diff --git a/internal/activator/hasecrets_test.go b/internal/activator/hasecrets_test.go
index 135519f0d..f2de8d61a 100644
--- a/internal/activator/hasecrets_test.go
+++ b/internal/activator/hasecrets_test.go
@@ -366,10 +366,10 @@ func TestFirstWakeCrashBeforePublishRemints(t *testing.T) {
}
})
dead := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(dead)
_, _ = s.wakeForTest(context.Background())
- }()
+ })
t.Cleanup(func() {
close(release)
select {
diff --git a/internal/activator/hasuspect_test.go b/internal/activator/hasuspect_test.go
index 1ac413a94..897ae95f4 100644
--- a/internal/activator/hasuspect_test.go
+++ b/internal/activator/hasuspect_test.go
@@ -60,7 +60,7 @@ func (s *haSvc) note(d edge.ForwardDecision, res edge.ForwardResult) {
func (s *haSvc) concurrently(n int) <-chan edge.ForwardDecision {
out := make(chan edge.ForwardDecision, n)
for range n {
- go func() { out <- s.decide() }()
+ goTracked(func() { out <- s.decide() })
}
return out
}
@@ -613,7 +613,7 @@ func TestSuspectWindowRevalidationTimeout(t *testing.T) {
defer cancel()
first := make(chan edge.ForwardDecision, 1)
start := time.Now()
- go func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) }()
+ goTracked(func() { first <- s.a.ForwardTarget(ctx, s.rt, nil) })
waitFor(t, "suspect read", func() bool { return reads.Load() == 1 })
cancel()
recv(t, first)
diff --git a/internal/activator/hatake_test.go b/internal/activator/hatake_test.go
index 181e0df30..dd58953ac 100644
--- a/internal/activator/hatake_test.go
+++ b/internal/activator/hatake_test.go
@@ -501,17 +501,17 @@ func TestTakeBoundOnAFirstWake(t *testing.T) {
})
// An ordinary waiter: extended past the bound.
ordinary := make(chan error, 1)
- go func() {
+ goTracked(func() {
if worker {
ordinary <- s.a.WakeWorker(s.rt)
} else {
_, err := s.a.beginRequest(context.Background(), s.rt)
ordinary <- err
}
- }()
+ })
took := make(chan edge.TakeAnswer, 1)
began := time.Now()
- go func() { took <- s.a.TakeHost(context.Background(), s.rt, lifetime, 6) }()
+ goTracked(func() { took <- s.a.TakeHost(context.Background(), s.rt, lifetime, 6) })
select {
case ans := <-took:
if d := time.Since(began); d > 2*time.Second {
diff --git a/internal/activator/heldstream_e2e_test.go b/internal/activator/heldstream_e2e_test.go
index ab19c6af5..23d5e5506 100644
--- a/internal/activator/heldstream_e2e_test.go
+++ b/internal/activator/heldstream_e2e_test.go
@@ -396,7 +396,7 @@ func (b *sseBrowser) connect() *sseConn {
close(conn.done)
return conn
}
- go b.read(conn)
+ goTracked(func() { b.read(conn) })
return conn
}
diff --git a/internal/activator/holdran_event_test.go b/internal/activator/holdran_event_test.go
index 3cc5bf872..90edb1708 100644
--- a/internal/activator/holdran_event_test.go
+++ b/internal/activator/holdran_event_test.go
@@ -50,7 +50,7 @@ func TestAFirstWakeEndedAfterItsExecReportsThatItRan(t *testing.T) {
<-ctx.Done()
return ctx.Err()
}
- go a.beginRequest(context.Background(), testRoute(host)) //nolint:errcheck
+ goTracked(func() { _, _ = a.beginRequest(context.Background(), testRoute(host)) })
if !refuse {
<-entered
} else {
diff --git a/internal/activator/knobguard_test.go b/internal/activator/knobguard_test.go
new file mode 100644
index 000000000..473b79b69
--- /dev/null
+++ b/internal/activator/knobguard_test.go
@@ -0,0 +1,228 @@
+package activator
+
+import (
+ "fmt"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+)
+
+// untrackedStarterExemptions are the functions whose goroutine starts the
+// guard accepts, with the reason. Each runs no code of this package on the
+// goroutine it starts, or is the join's own machinery.
+var untrackedStarterExemptions = map[string]string{
+ "goTracked": "the helper itself",
+ "afterTracked": "the helper itself",
+ "trySetKnob": "runs setKnob, no production code, and waits for the goroutine before it returns",
+ "endLeaseWatches": "the join's own wait on Service.leaseWork; reads no setting",
+ "newOwnedRep": "its timer only marks a fake lease lost; the watch that reacts is production's, which endLeaseWatches ends",
+ "newOwnedLease": "its timer only marks a fake lease lost; the watch that reacts is production's, which endLeaseWatches ends",
+ "admitHeld": "its bound timer only cancels a context, and is stopped once the admission returns",
+ "serveAfter": "serves a fixed status on a socket; runs no code of this package",
+ "serveOn": "serves a fixed body on a socket; runs no code of this package",
+ "serveOK": "serves a fixed status on a socket; runs no code of this package",
+}
+
+// TestKnobTestsStartNoUntrackedGoroutine keeps setKnob's join complete. A
+// goroutine a test starts can read a setting in production code it calls,
+// and only goTracked orders its reads before the restore (#1249). So test
+// code a test that changes a setting can reach starts goroutines with
+// goTracked, and timers with afterTracked: no go statement, time.AfterFunc
+// or Go method (sync.WaitGroup, errgroup). Methods of test types are checked too, whoever reaches them:
+// production calls them, from any test.
+func TestKnobTestsStartNoUntrackedGoroutine(t *testing.T) {
+ paths, err := filepath.Glob("*_test.go")
+ if err != nil || len(paths) == 0 {
+ t.Fatalf("no test files: %v", err)
+ }
+ fset := token.NewFileSet()
+ var files []*ast.File
+ for _, p := range paths {
+ f, err := parser.ParseFile(fset, p, nil, parser.SkipObjectResolution)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if f.Name.Name == "activator" {
+ files = append(files, f)
+ }
+ }
+ var bad []string
+ used := map[string]bool{}
+ for _, s := range untrackedStarters(fset, files) {
+ if _, ok := untrackedStarterExemptions[s.fn]; ok {
+ used[s.fn] = true
+ continue
+ }
+ bad = append(bad, s.String())
+ }
+ if len(bad) > 0 {
+ t.Errorf("test code a test that changes a setting can reach starts a goroutine without goTracked, "+
+ "so the test's restore is not ordered after its reads (#1249). Use goTracked(func() { ... }):\n%s",
+ strings.Join(bad, "\n"))
+ }
+ for fn := range untrackedStarterExemptions {
+ if !used[fn] {
+ t.Errorf("untrackedStarterExemptions names %s, which starts no untracked goroutine: remove it", fn)
+ }
+ }
+}
+
+// The guard finds a goroutine started directly by a test that changes a
+// setting, one started by a helper it calls, one a test reaches through a
+// rig that changes the setting, and one in a test type's method. It passes
+// goTracked and a test that changes no setting.
+func TestKnobGoroutineGuardFindsUntrackedStarts(t *testing.T) {
+ const src = `package activator
+
+func rig(t *testing.T) { setKnob(t, &wakeWaitBound, 1) }
+func helper() { go work() }
+func TestDirect(t *testing.T) { setKnob(t, &wakeWaitBound, 1); go func() {}() }
+func TestViaRig(t *testing.T) { rig(t); helper() }
+func TestTracked(t *testing.T) { rig(t); goTracked(func() {}) }
+func TestTimer(t *testing.T) { rig(t); time.AfterFunc(d, func() {}) }
+func TestGroup(t *testing.T) { rig(t); var wg sync.WaitGroup; wg.Go(func() {}) }
+func TestNoSetting(t *testing.T) { go func() {}() }
+func (f *fake) Start() { go f.run() }
+`
+ fset := token.NewFileSet()
+ f, err := parser.ParseFile(fset, "guard_test.go", src, parser.SkipObjectResolution)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var got []string
+ for _, s := range untrackedStarters(fset, []*ast.File{f}) {
+ got = append(got, s.fn)
+ }
+ slices.Sort(got)
+ want := []string{"Start", "TestDirect", "TestGroup", "TestTimer", "helper"}
+ if !slices.Equal(got, want) {
+ t.Fatalf("the guard found starts in %v, want %v", got, want)
+ }
+}
+
+// goroutineStart is a goroutine start the guard found.
+type goroutineStart struct {
+ fn, kind string
+ pos token.Position
+}
+
+func (s goroutineStart) String() string {
+ return fmt.Sprintf("%s:%d: %s in %s", s.pos.Filename, s.pos.Line, s.kind, s.fn)
+}
+
+// guardFunc is a function or method of the test files, or a package-level
+// variable's initialiser, as the guard sees it.
+type guardFunc struct {
+ name string
+ method bool
+ // refs are the names it mentions: calls, function values, selectors.
+ refs map[string]bool
+ starts []goroutineStart
+}
+
+// untrackedStarters returns the goroutine starts in the test code that a
+// test that changes a setting can reach, and in every method. Reach is by
+// name: a function reaches every function or method named by an identifier
+// in its body, so a function value, an interface call or a shared method
+// name counts. That over-counts, which only makes the guard stricter.
+func untrackedStarters(fset *token.FileSet, files []*ast.File) []goroutineStart {
+ byName := map[string][]*guardFunc{}
+ var all []*guardFunc
+ add := func(name string, method bool, body ast.Node) {
+ g := &guardFunc{name: name, method: method, refs: map[string]bool{}}
+ ast.Inspect(body, func(n ast.Node) bool {
+ switch n := n.(type) {
+ case *ast.Ident:
+ g.refs[n.Name] = true
+ case *ast.GoStmt:
+ g.starts = append(g.starts, goroutineStart{fn: name, kind: "go statement", pos: fset.Position(n.Pos())})
+ case *ast.CallExpr:
+ if sel, ok := n.Fun.(*ast.SelectorExpr); ok {
+ if x, ok := sel.X.(*ast.Ident); ok && x.Name == "time" && sel.Sel.Name == "AfterFunc" {
+ g.starts = append(g.starts, goroutineStart{fn: name, kind: "time.AfterFunc", pos: fset.Position(n.Pos())})
+ } else if sel.Sel.Name == "Go" {
+ g.starts = append(g.starts, goroutineStart{fn: name, kind: "Go method", pos: fset.Position(n.Pos())})
+ }
+ }
+ }
+ return true
+ })
+ byName[name] = append(byName[name], g)
+ all = append(all, g)
+ }
+ for _, f := range files {
+ for _, d := range f.Decls {
+ switch d := d.(type) {
+ case *ast.FuncDecl:
+ if d.Body != nil {
+ add(d.Name.Name, d.Recv != nil, d.Body)
+ }
+ case *ast.GenDecl:
+ for _, spec := range d.Specs {
+ if vs, ok := spec.(*ast.ValueSpec); ok {
+ for _, v := range vs.Values {
+ for _, n := range vs.Names {
+ add(n.Name, false, v)
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ // changes holds the functions that change a setting: they mention
+ // setKnob, or a function that does.
+ changes := map[*guardFunc]bool{}
+ for grew := true; grew; {
+ grew = false
+ for _, g := range all {
+ if changes[g] {
+ continue
+ }
+ for ref := range g.refs {
+ if ref == "setKnob" || slices.ContainsFunc(byName[ref], func(h *guardFunc) bool { return changes[h] }) {
+ changes[g], grew = true, true
+ break
+ }
+ }
+ }
+ }
+ // reached holds what those functions reach, and every method.
+ reached := map[*guardFunc]bool{}
+ var queue []*guardFunc
+ for _, g := range all {
+ if changes[g] || g.method {
+ reached[g] = true
+ queue = append(queue, g)
+ }
+ }
+ for len(queue) > 0 {
+ g := queue[0]
+ queue = queue[1:]
+ for ref := range g.refs {
+ for _, h := range byName[ref] {
+ if !reached[h] {
+ reached[h] = true
+ queue = append(queue, h)
+ }
+ }
+ }
+ }
+ var starts []goroutineStart
+ for _, g := range all {
+ if reached[g] {
+ starts = append(starts, g.starts...)
+ }
+ }
+ slices.SortFunc(starts, func(a, b goroutineStart) int {
+ if c := strings.Compare(a.pos.Filename, b.pos.Filename); c != 0 {
+ return c
+ }
+ return a.pos.Line - b.pos.Line
+ })
+ return starts
+}
diff --git a/internal/activator/knobrestore_test.go b/internal/activator/knobrestore_test.go
index 9eacfff81..2dc269118 100644
--- a/internal/activator/knobrestore_test.go
+++ b/internal/activator/knobrestore_test.go
@@ -2,6 +2,7 @@ package activator
import (
"fmt"
+ "path/filepath"
"runtime"
"slices"
"strings"
@@ -26,7 +27,86 @@ var knobRestores = struct {
abandoned map[string]bool
// services are the Services built since a test last restored a setting.
services []*trackedService
-}{byTest: map[string][]func(){}, abandoned: map[string]bool{}}
+ // goroutines are the goroutines goTracked started that have not
+ // finished. Each removes itself, under this lock, as its last act.
+ goroutines map[*testGoroutine]bool
+}{byTest: map[string][]func(){}, abandoned: map[string]bool{}, goroutines: map[*testGoroutine]bool{}}
+
+// testGoroutine is a goroutine a test started with goTracked.
+type testGoroutine struct {
+ // site is the file and line of the goTracked call.
+ site string
+ // abandoned is set once a test's end reported it as never finishing.
+ // Under knobRestores.
+ abandoned bool
+}
+
+// goTracked runs f on a goroutine of its own, which every test's settings
+// restore waits for. A test that starts a goroutine uses it instead of a go
+// statement (TestKnobTestsStartNoUntrackedGoroutine enforces this).
+//
+// A goroutine a test starts can run production code that reads a setting,
+// as TestTakeBoundOnAFirstWake's waiters run beginRequest and its wait
+// bound. Seeing it gone from the stacks shows that it ended, not that its
+// reads came before the restore: only a synchronisation shows that to the
+// race detector. The goroutine's last act is to leave knobRestores.goroutines
+// under knobRestores' lock, and the join reads that set under the same lock,
+// so everything the goroutine did happens before the restores that follow.
+//
+// The join runs where setKnob's restores run, after the cleanups registered
+// after the test's first setKnob. A goroutine that only ends when a cleanup
+// releases it needs that cleanup registered after the first setKnob.
+func goTracked(f func()) {
+ g := trackGoroutine()
+ go func() {
+ defer g.finish()
+ f()
+ }()
+}
+
+// afterTracked runs f after d on a goroutine of its own, as time.AfterFunc
+// does, and the join waits for it as for goTracked: from the call, so a
+// timer still pending at the test's end is waited for too.
+func afterTracked(d time.Duration, f func()) {
+ g := trackGoroutine()
+ time.AfterFunc(d, func() {
+ defer g.finish()
+ f()
+ })
+}
+
+// trackGoroutine records a goroutine its caller's caller is starting.
+func trackGoroutine() *testGoroutine {
+ _, file, line, _ := runtime.Caller(2)
+ g := &testGoroutine{site: fmt.Sprintf("%s:%d", filepath.Base(file), line)}
+ knobRestores.Lock()
+ knobRestores.goroutines[g] = true
+ knobRestores.Unlock()
+ return g
+}
+
+// finish is a tracked goroutine's last act: it leaves the set under
+// knobRestores' lock.
+func (g *testGoroutine) finish() {
+ knobRestores.Lock()
+ delete(knobRestores.goroutines, g)
+ knobRestores.Unlock()
+}
+
+// runningTestGoroutines returns the goTracked goroutines still running,
+// apart from abandoned ones. Taking knobRestores' lock orders everything
+// each goroutine that has left the set did before the caller's next step.
+func runningTestGoroutines() []*testGoroutine {
+ knobRestores.Lock()
+ defer knobRestores.Unlock()
+ var running []*testGoroutine
+ for g := range knobRestores.goroutines {
+ if !g.abandoned {
+ running = append(running, g)
+ }
+ }
+ return running
+}
// trackedService is a Service built by newTrackedService.
type trackedService struct {
@@ -61,8 +141,8 @@ func newTrackedService(t testing.TB, cfg Config, backend Backend, due DueStore)
}
// setKnob sets the package-level setting *p to v for the rest of t, and puts
-// it back when t ends, once the production goroutines t started have
-// finished. A wake outlives the request that began it, so restoring a timing
+// it back when t ends, once the goroutines t started, its own (goTracked)
+// and production's, have finished. A wake outlives the request that began it, so restoring a timing
// setting in a plain t.Cleanup writes it while that wake may still read it: a
// data race under -race, though production never changes these settings
// (#1249).
@@ -113,12 +193,31 @@ func unownedServiceLocked(t testing.TB) *trackedService {
return nil
}
+// runKnobRestores runs t's restores once nothing can still read a setting.
+// The rule it keeps: every goroutine that may read a setting has finished,
+// and something orders its reads before the restore, a synchronisation the
+// race detector sees and not just its absence from the stacks. Each kind of
+// goroutine has its own ordering:
+//
+// - a goroutine a test started: goTracked's exit under knobRestores' lock,
+// which joinGoroutines reads under the same lock;
+// - a lease watch, and the kills a loss starts: Service.leaseWork, which
+// endLeaseWatches waits on;
+// - a wake: its Service.background decrement, its last act;
+// - any other goroutine production starts: a last critical section under
+// its Service's a.mu after its last read of a setting.
+//
+// syncWithServices loads the counter and takes a.mu. The last two hold only
+// for goroutines production starts. A test's goroutine that calls into
+// production, as beginRequest, has no such last act: its last read of a
+// setting can follow its last a.mu section (awaitWake's wait bound does), so
+// it must be started with goTracked.
func runKnobRestores(t testing.TB) {
t.Helper()
- joinProductionGoroutines(t)
+ joinGoroutines(t)
endLeaseWatches(t)
// A watch that was handling a loss may have begun a stop.
- joinProductionGoroutines(t)
+ joinGoroutines(t)
syncWithServices(t)
knobRestores.Lock()
restores := knobRestores.byTest[t.Name()]
@@ -130,32 +229,45 @@ func runKnobRestores(t testing.TB) {
}
}
-// joinProductionGoroutines waits until no goroutine is running this package's
-// production code, apart from the idle ones idleGoroutineRoots names. It polls
+// joinGoroutines waits until every goroutine a test started with goTracked
+// has finished, and no goroutine is running this package's production code,
+// apart from the idle ones idleGoroutineRoots names. It waits for both
+// together, since either may be waiting for the other. It polls the stacks
// because production has no signal for "every goroutine has ended", and the
// goroutines that matter are not all counted in Service.background: the
// first-wake watch (watchFirstWake) is one that is not.
-func joinProductionGoroutines(t testing.TB) {
+func joinGoroutines(t testing.TB) {
t.Helper()
- live := productionGoroutines()
- if len(live) == 0 {
+ live, tracked := productionGoroutines(), runningTestGoroutines()
+ if len(live) == 0 && len(tracked) == 0 {
return
}
deadline := time.After(knobJoinBound)
tick := time.NewTicker(time.Millisecond)
defer tick.Stop()
- for len(live) > 0 {
+ for len(live) > 0 || len(tracked) > 0 {
select {
case <-tick.C:
- live = productionGoroutines()
+ live, tracked = productionGoroutines(), runningTestGoroutines()
case <-deadline:
+ var sites []string
knobRestores.Lock()
for _, g := range live {
knobRestores.abandoned[goroutineHeader(g)] = true
}
+ for _, g := range tracked {
+ g.abandoned = true
+ sites = append(sites, g.site)
+ }
knobRestores.Unlock()
- t.Errorf("%d production goroutines still running %s after the test ended:\n%s",
- len(live), knobJoinBound, strings.Join(live, "\n\n"))
+ if len(tracked) > 0 {
+ t.Errorf("%d goroutines a test started (goTracked) still running %s after the test ended, started at: %s",
+ len(tracked), knobJoinBound, strings.Join(sites, ", "))
+ }
+ if len(live) > 0 {
+ t.Errorf("%d production goroutines still running %s after the test ended:\n%s",
+ len(live), knobJoinBound, strings.Join(live, "\n\n"))
+ }
return
}
}
@@ -210,13 +322,16 @@ func endLeaseWatches(t testing.TB) {
}
}
-// 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
+// syncWithServices orders what the finished production 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
// it still reports the goroutine's last read against the restore. A wake's
// last act is its Service.background decrement, and the other goroutines
-// finish their knob reads before a last critical section under a.mu, so
-// loading the one and taking the other is that synchronisation.
+// production starts finish their reads of settings before a last critical
+// section under a.mu, so loading the one and taking the other is that
+// synchronisation for them. It is not one for a goroutine a test started:
+// production code run on it need not end under a.mu, and goTracked orders
+// those instead (see runKnobRestores).
func syncWithServices(t testing.TB) {
t.Helper()
deadline := time.After(knobJoinBound)
diff --git a/internal/activator/movestreams_test.go b/internal/activator/movestreams_test.go
index 2d52fcf96..49df07115 100644
--- a/internal/activator/movestreams_test.go
+++ b/internal/activator/movestreams_test.go
@@ -196,7 +196,7 @@ func TestMoveEndsAStreamThatOpensAfterItsStart(t *testing.T) {
func wantStreamEnded(t *testing.T, r io.Reader) {
t.Helper()
done := make(chan struct{})
- go func() { io.Copy(io.Discard, r); close(done) }()
+ goTracked(func() { io.Copy(io.Discard, r); close(done) })
select {
case <-done:
case <-time.After(2 * time.Second):
@@ -281,7 +281,7 @@ func TestMoveKeepsTheBoundForAnOrdinaryRequest(t *testing.T) {
release := make(chan struct{})
front := moveStreamFront(t, s, moveStreamUpstream(t, release))
got := make(chan string, 1)
- go func() {
+ goTracked(func() {
resp, err := http.Get(front + "/slow")
if err != nil {
got <- err.Error()
@@ -290,7 +290,7 @@ func TestMoveKeepsTheBoundForAnOrdinaryRequest(t *testing.T) {
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
got <- string(b)
- }()
+ })
waitUntil(t, "the request in flight", func() bool { return s.inflight() == 1 })
took, err := moveAndWait(t, s, 300*time.Millisecond)
if !errors.Is(err, context.DeadlineExceeded) || took < 300*time.Millisecond {
diff --git a/internal/activator/opset_test.go b/internal/activator/opset_test.go
index 0c50add19..ff5451d14 100644
--- a/internal/activator/opset_test.go
+++ b/internal/activator/opset_test.go
@@ -39,12 +39,12 @@ func plantMember(t *testing.T, a *Service, host string, role genRole, p *fakePro
}
a.addMemberLocked(e, m)
a.mu.Unlock()
- go func() {
+ goTracked(func() {
if role != roleRetiring {
<-ctx.Done()
}
a.dropMember(e, m)
- }()
+ })
return m
}
diff --git a/internal/activator/outcome_fence_test.go b/internal/activator/outcome_fence_test.go
index 1c4a57441..f21efb65f 100644
--- a/internal/activator/outcome_fence_test.go
+++ b/internal/activator/outcome_fence_test.go
@@ -220,10 +220,10 @@ func TestAFirstWakeObserverDeliversItsOutcomeBeforeAdmissionReopens(t *testing.T
t.Fatal("Current showed the first wake while its failure was still being delivered: firstWatch was cleared first")
}
second := make(chan error, 1)
- go func() {
+ goTracked(func() {
_, err := a.beginRequest(context.Background(), testRoute(host))
second <- err
- }()
+ })
select {
case rec := <-saw:
close(o.release)
diff --git a/internal/activator/pendingwake_linux_test.go b/internal/activator/pendingwake_linux_test.go
index 1335f2922..1296234f9 100644
--- a/internal/activator/pendingwake_linux_test.go
+++ b/internal/activator/pendingwake_linux_test.go
@@ -272,13 +272,13 @@ func TestPendingWakeDoesNotBootAStaleCopy(t *testing.T) {
// A's wake reads its route and waits for the lease.
woke := make(chan error, 1)
- go func() {
+ goTracked(func() {
release, err := aSvc.beginRequest(context.Background(), rtA)
if err == nil {
release()
}
woke <- err
- }()
+ })
select {
case <-boxA.entered:
case <-time.After(10 * time.Second):
@@ -378,13 +378,13 @@ func TestRetirementFencesAPendingWake(t *testing.T) {
a, box, _ := fleetBox(t, "pi-1", lock, bucket, eb, rt)
box.gate, box.entered = make(chan struct{}), make(chan struct{})
woke := make(chan error, 1)
- go func() {
+ goTracked(func() {
release, err := a.beginRequest(context.Background(), rt)
if err == nil {
release()
}
woke <- err
- }()
+ })
<-box.entered
a.RetireExcept(map[string]bool{})
close(box.gate)
@@ -935,7 +935,7 @@ func TestUnlabelledWakeFencedWhenLabelledWhileWaitingForTheLease(t *testing.T) {
asFleetBox(r.a, "pi-1", store)
r.box.gate, r.box.entered = make(chan struct{}), make(chan struct{})
woke := make(chan error, 1)
- go func() { woke <- r.wake(r.a) }()
+ goTracked(func() { woke <- r.wake(r.a) })
select {
case <-r.box.entered:
case <-time.After(10 * time.Second):
@@ -1741,10 +1741,10 @@ func (r *checkpointRig) shutdownSpent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
done := make(chan struct{})
- go func() {
+ goTracked(func() {
r.a.Shutdown(ctx)
close(done)
- }()
+ })
select {
case <-done:
case <-time.After(30 * time.Second):
diff --git a/internal/activator/rawsecret_test.go b/internal/activator/rawsecret_test.go
index d6cda704e..1c47b8674 100644
--- a/internal/activator/rawsecret_test.go
+++ b/internal/activator/rawsecret_test.go
@@ -227,10 +227,10 @@ func TestEachRawRevisionIsReportedOnce(t *testing.T) {
for range 16 {
p := openAt()
wg.Add(1)
- go func() {
+ goTracked(func() {
defer wg.Done()
b.noteRawBaseline(rt.Host, p)
- }()
+ })
}
wg.Wait()
n := 0
diff --git a/internal/activator/replicadeploy_test.go b/internal/activator/replicadeploy_test.go
index a56fed35e..bc7379766 100644
--- a/internal/activator/replicadeploy_test.go
+++ b/internal/activator/replicadeploy_test.go
@@ -631,9 +631,9 @@ func TestReplicaSwapRetiresAfterRoutedRequests(t *testing.T) {
}
})
out := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
out <- r.a.ReplicaSwap(context.Background(), r.attempt(CauseRelease, ModeOverlap), *r.store.snapshot(), "b", newestOne)
- }()
+ })
waitFor(t, "the old generation's drain", func() bool {
p.mu.Lock()
defer p.mu.Unlock()
diff --git a/internal/activator/rootfs_cmd_test.go b/internal/activator/rootfs_cmd_test.go
index 027467d08..e7a11a10e 100644
--- a/internal/activator/rootfs_cmd_test.go
+++ b/internal/activator/rootfs_cmd_test.go
@@ -426,10 +426,10 @@ func TestRootfsRunPollsAndStopsTheRootfsUnit(t *testing.T) {
err error
}
pollDone := make(chan polled, 1)
- go func() {
+ goTracked(func() {
st, err := run.Poll(context.Background())
pollDone <- polled{st, err}
- }()
+ })
select {
case p := <-pollDone:
t.Fatalf("Poll answered %+v (%v) while the rootfs cmd unit runs; the binary unit would read as gone", p.st, p.err)
diff --git a/internal/activator/rootfs_ctl_harness_test.go b/internal/activator/rootfs_ctl_harness_test.go
index 64e3c5600..7e7ff17f2 100644
--- a/internal/activator/rootfs_ctl_harness_test.go
+++ b/internal/activator/rootfs_ctl_harness_test.go
@@ -163,7 +163,7 @@ func newRootfsCtlHarness(t *testing.T) *rootfsCtlHarness {
}
ctx, cancel := context.WithCancel(context.Background())
served := make(chan struct{})
- go func() { defer close(served); _ = h.srv.Serve(ctx, ln) }()
+ goTracked(func() { defer close(served); _ = h.srv.Serve(ctx, ln) })
front := filepath.Join(root, "front.sock")
fln, err := net.Listen("unix", front)
if err != nil {
@@ -196,7 +196,7 @@ func newRootfsCtlHarness(t *testing.T) *rootfsCtlHarness {
}
proxy.ServeHTTP(w, r)
})}
- go func() { _ = fs.Serve(fln) }()
+ goTracked(func() { _ = fs.Serve(fln) })
t.Cleanup(func() {
fs.Close()
cancel()
diff --git a/internal/activator/rootfs_release_backend_test.go b/internal/activator/rootfs_release_backend_test.go
index 77562ef22..2c27adddd 100644
--- a/internal/activator/rootfs_release_backend_test.go
+++ b/internal/activator/rootfs_release_backend_test.go
@@ -180,10 +180,10 @@ func TestReleasePollsTheRootfsCmdUnit(t *testing.T) {
err error
}
done := make(chan answer, 1)
- go func() {
+ goTracked(func() {
st, err := u.Poll(context.Background())
done <- answer{st, err}
- }()
+ })
// A poll of the binary unit would answer CmdGone at once: the running
// rootfs unit keeps root's long poll open.
select {
diff --git a/internal/activator/rootfs_resident_test.go b/internal/activator/rootfs_resident_test.go
index 2913067ac..e85df63e8 100644
--- a/internal/activator/rootfs_resident_test.go
+++ b/internal/activator/rootfs_resident_test.go
@@ -719,12 +719,12 @@ func TestResidentRequestAndTickRaceOneWake(t *testing.T) {
codes := make(chan int, 50)
for i := 0; i < 50; i++ {
wg.Add(1)
- go func() {
+ goTracked(func() {
defer wg.Done()
rec := httptest.NewRecorder()
a.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "http://shop.example.com/", nil), rt, okHandler())
codes <- rec.Code
- }()
+ })
}
wg.Wait()
close(codes)
diff --git a/internal/activator/rootfs_swap_release_test.go b/internal/activator/rootfs_swap_release_test.go
index 6f5238cfe..0bdb6ff7a 100644
--- a/internal/activator/rootfs_swap_release_test.go
+++ b/internal/activator/rootfs_swap_release_test.go
@@ -217,7 +217,7 @@ func (f *relSwapFixture) attemptV3(mode SwapMode) Attempt {
// swapAsync runs Swap in the background.
func (f *relSwapFixture) swapAsync(at Attempt) <-chan SwapResult {
ch := make(chan SwapResult, 1)
- go func() { ch <- f.a.Swap(context.Background(), at, f.newest) }()
+ goTracked(func() { ch <- f.a.Swap(context.Background(), at, f.newest) })
return ch
}
@@ -757,8 +757,8 @@ func TestSwapReleaseLeaseLossRacesTheSweep(t *testing.T) {
start := make(chan struct{})
var wg sync.WaitGroup
wg.Add(2)
- go func() { defer wg.Done(); <-start; f.rep.lose(lease.ErrLost) }()
- go func() { defer wg.Done(); <-start; f.a.sweepOnce() }()
+ goTracked(func() { defer wg.Done(); <-start; f.rep.lose(lease.ErrLost) })
+ goTracked(func() { defer wg.Done(); <-start; f.a.sweepOnce() })
close(start)
wg.Wait()
res := waitSwap(t, ch)
diff --git a/internal/activator/rootfs_wake_release_test.go b/internal/activator/rootfs_wake_release_test.go
index 33daa13af..f75b65bca 100644
--- a/internal/activator/rootfs_wake_release_test.go
+++ b/internal/activator/rootfs_wake_release_test.go
@@ -312,13 +312,13 @@ func (r *wakeRelRig) setPlan(p WakePlan) {
func (r *wakeRelRig) wake(a *Service) <-chan error {
r.requests.Add(1)
ch := make(chan error, 1)
- go func() {
+ goTracked(func() {
done, err := a.beginRequest(context.Background(), r.rt)
if err == nil {
done()
}
ch <- err
- }()
+ })
return ch
}
diff --git a/internal/activator/rootfsrelease_test.go b/internal/activator/rootfsrelease_test.go
index 85d7f2176..9b05e5f04 100644
--- a/internal/activator/rootfsrelease_test.go
+++ b/internal/activator/rootfsrelease_test.go
@@ -648,10 +648,10 @@ type releaseResult struct {
// channel.
func (r *releaseRig) run(ctx context.Context) <-chan releaseResult {
ch := make(chan releaseResult, 1)
- go func() {
+ goTracked(func() {
ex, err := r.a.runRelease(ctx, r.e, r.rt, r.id, r.held, r.gate)
ch <- releaseResult{ex, err}
- }()
+ })
return ch
}
@@ -1120,7 +1120,7 @@ func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) {
r := newReleaseRig(t)
r.held = newOwnedLease(time.Now().Add(time.Second), false)
renew := make(chan struct{})
- go func() {
+ goTracked(func() {
tk := time.NewTicker(20 * time.Millisecond)
defer tk.Stop()
for {
@@ -1131,7 +1131,7 @@ func TestReleaseKeepsRunningWhileTheLeaseRenews(t *testing.T) {
r.held.setUntil(time.Now().Add(time.Second))
}
}
- }()
+ })
defer close(renew)
ch := r.run(context.Background())
r.waitStarted(t)
@@ -1236,8 +1236,8 @@ func TestReleaseLeaseLossRacesExit(t *testing.T) {
r.waitStarted(t)
var wg sync.WaitGroup
wg.Add(2)
- go func() { defer wg.Done(); r.held.lose(lease.ErrLost) }()
- go func() { defer wg.Done(); r.b.unit.done("1", "0", "success") }()
+ goTracked(func() { defer wg.Done(); r.held.lose(lease.ErrLost) })
+ goTracked(func() { defer wg.Done(); r.b.unit.done("1", "0", "success") })
wg.Wait()
res := wait(t, ch)
if res.err == nil || !errors.Is(res.err, errSwapLeaseLost) || !errors.Is(res.err, errReleaseLeaseLost) {
@@ -1605,10 +1605,10 @@ func (r *consumerRig) gate() error {
func (r *consumerRig) start(t *testing.T, ctx context.Context) <-chan releaseResult {
t.Helper()
ch := make(chan releaseResult, 1)
- go func() {
+ goTracked(func() {
ex, err := r.a.runRelease(ctx, r.e, r.rrt, r.id, r.held, r.gate)
ch <- releaseResult{ex, err}
- }()
+ })
select {
case <-r.rel.started:
case res := <-ch:
diff --git a/internal/activator/rootfsworkers_backend_test.go b/internal/activator/rootfsworkers_backend_test.go
index 67deada4c..d73c2c72b 100644
--- a/internal/activator/rootfsworkers_backend_test.go
+++ b/internal/activator/rootfsworkers_backend_test.go
@@ -501,10 +501,10 @@ func TestRootfsWorkerStopAnswers(t *testing.T) {
n := asks()
ctx, cancel := context.WithCancel(context.Background())
cancel()
- go func() {
+ goTracked(func() {
time.Sleep(3 * b.ObservePoll)
units.set(unit, "inactive", "inv1", false)
- }()
+ })
if err := b.RootfsWorkerGone(ctx, rt, "jobs"); err != nil {
t.Errorf("RootfsWorkerGone on a cancelled context = %v, want the stop and the proof to run anyway", err)
}
diff --git a/internal/activator/seed_rollback_stop_test.go b/internal/activator/seed_rollback_stop_test.go
index 590ebb6ff..a1ff2940c 100644
--- a/internal/activator/seed_rollback_stop_test.go
+++ b/internal/activator/seed_rollback_stop_test.go
@@ -172,13 +172,13 @@ func (x *importRollback) wake(t *testing.T) <-chan error {
t.Helper()
rt := *x.row(t)
done := make(chan error, 1)
- go func() {
+ goTracked(func() {
release, err := x.a.beginRequest(context.Background(), rt)
if err == nil {
release()
}
done <- err
- }()
+ })
return done
}
diff --git a/internal/activator/settle_test.go b/internal/activator/settle_test.go
index 0cdddb804..b4daaf098 100644
--- a/internal/activator/settle_test.go
+++ b/internal/activator/settle_test.go
@@ -92,7 +92,7 @@ func TestSwapCanarySettle(t *testing.T) {
setKnob(t, &swapSettle, time.Hour)
f := newSwapFixture(t)
done := make(chan SwapResult, 1)
- go func() { done <- f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) }()
+ goTracked(func() { done <- f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest) })
select {
case res := <-done:
if res.Outcome != SwapDone {
@@ -117,14 +117,14 @@ func TestSwapIntentionalStopDuringSettleIsNotAFailure(t *testing.T) {
{"hibernate", func(f *swapFixture) { f.clk.advance(2 * time.Hour); f.a.sweepOnce() }},
{"lease lost", func(f *swapFixture) { f.b.lastRep().setErr(errors.New("renewal failed")); f.a.sweepOnce() }},
{"maintenance fence", func(f *swapFixture) {
- go func() {
+ goTracked(func() {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
f.a.FenceAndStop(ctx, f.host, 1) //nolint:errcheck
- }()
+ })
}},
{"move or park retire", func(f *swapFixture) { f.a.RetireExcept(map[string]bool{}) }},
- {"shutdown", func(f *swapFixture) { go f.a.Shutdown(context.Background()) }},
+ {"shutdown", func(f *swapFixture) { goTracked(func() { f.a.Shutdown(context.Background()) }) }},
} {
t.Run(tc.name, func(t *testing.T) {
f := newSwapFixture(t)
@@ -134,7 +134,7 @@ func TestSwapIntentionalStopDuringSettleIsNotAFailure(t *testing.T) {
at := f.attempt(ModeOverlap)
at.Canary = true
results := make(chan SwapResult, 1)
- go func() { results <- f.a.Swap(context.Background(), at, f.newest) }()
+ goTracked(func() { results <- f.a.Swap(context.Background(), at, f.newest) })
<-healthy
// The settle has begun once it has polled the successor (nothing
// else asks it between the health check and the settle).
diff --git a/internal/activator/statelessrelease_test.go b/internal/activator/statelessrelease_test.go
index 6e4a74cf3..d7ba4e9f8 100644
--- a/internal/activator/statelessrelease_test.go
+++ b/internal/activator/statelessrelease_test.go
@@ -106,7 +106,7 @@ func replicaReleaseRig(t *testing.T) (*releaseRig, *replicaReleaseStore) {
}
func prepareReplica(r *releaseRig, id string) <-chan error {
ch := make(chan error, 1)
- go func() { ch <- r.a.PrepareStatelessRelease(context.Background(), r.rt, r.id, id) }()
+ goTracked(func() { ch <- r.a.PrepareStatelessRelease(context.Background(), r.rt, r.id, id) })
return ch
}
func replicaResult(t *testing.T, ch <-chan error) error {
diff --git a/internal/activator/swap_executed_test.go b/internal/activator/swap_executed_test.go
index 375e410e0..1a68dd451 100644
--- a/internal/activator/swap_executed_test.go
+++ b/internal/activator/swap_executed_test.go
@@ -311,10 +311,10 @@ func TestReplaceWorkerLearnsItsRespawnsExecutionWhenItsCallerLeaves(t *testing.T
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
out := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
out <- a.ReplaceWorker(ctx, workerAttempt(CauseRelease, ModeHold, fakeIdentity("v2")), nil,
func(string) uint64 { return rev.Load() })
- }()
+ })
select {
case <-entered:
case <-time.After(5 * time.Second):
diff --git a/internal/activator/swap_hold_test.go b/internal/activator/swap_hold_test.go
index 8606003ed..856d858da 100644
--- a/internal/activator/swap_hold_test.go
+++ b/internal/activator/swap_hold_test.go
@@ -107,7 +107,7 @@ func TestSwapHoldCanarySettles(t *testing.T) {
at := f.attempt(ModeHold)
at.Canary = true
results := make(chan SwapResult, 1)
- go func() { results <- f.a.Swap(context.Background(), at, f.newest) }()
+ goTracked(func() { results <- f.a.Swap(context.Background(), at, f.newest) })
var g Gen
var p *fakeProc
waitFor(t, "the pinned generation awake", func() bool {
@@ -565,7 +565,7 @@ func TestSwapHoldReleasesItsCallerWhileTheStopIsPending(t *testing.T) {
{"the caller's context ends", func(f *swapFixture) SwapResult {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
- go func() {
+ goTracked(func() {
// Cancel once the hold's stop has begun (bounded: the test's
// own assertion reports a hold that never got there).
for deadline := time.Now().Add(5 * time.Second); time.Now().Before(deadline); time.Sleep(time.Millisecond) {
@@ -578,7 +578,7 @@ func TestSwapHoldReleasesItsCallerWhileTheStopIsPending(t *testing.T) {
}
}
cancel()
- }()
+ })
return f.a.Swap(ctx, f.attempt(ModeHold), f.newest)
}, errSwapStopped},
} {
diff --git a/internal/activator/swap_review_test.go b/internal/activator/swap_review_test.go
index c61fa7ed1..b809ac905 100644
--- a/internal/activator/swap_review_test.go
+++ b/internal/activator/swap_review_test.go
@@ -191,7 +191,7 @@ func TestSwapNeverHealthyAppKeepsTheIncumbentServing(t *testing.T) {
t.Skipf("cannot bind a unix socket here (%v); run with TMPDIR=/tmp/k", err)
}
srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(code) })}
- go srv.Serve(ln) //nolint:errcheck
+ goTracked(func() { _ = srv.Serve(ln) })
return func() { srv.Close() }
}
setKnob(t, &spawnHealthTimeout, 600*time.Millisecond)
@@ -210,7 +210,7 @@ func TestSwapNeverHealthyAppKeepsTheIncumbentServing(t *testing.T) {
stop := make(chan struct{})
var wg sync.WaitGroup
wg.Add(1)
- go func() {
+ goTracked(func() {
defer wg.Done()
for {
select {
@@ -234,7 +234,7 @@ func TestSwapNeverHealthyAppKeepsTheIncumbentServing(t *testing.T) {
}
resp.Body.Close()
}
- }()
+ })
res := f.a.Swap(context.Background(), f.attempt(ModeOverlap), f.newest)
close(stop)
wg.Wait()
diff --git a/internal/activator/swap_sim_test.go b/internal/activator/swap_sim_test.go
index 3879b63fb..c9ee757e9 100644
--- a/internal/activator/swap_sim_test.go
+++ b/internal/activator/swap_sim_test.go
@@ -618,7 +618,7 @@ func (p *simProc) exitLater() {
return
}
d := time.Duration(1+p.w.intn(15)) * time.Millisecond
- time.AfterFunc(d, func() { p.die("late exit") })
+ afterTracked(d, func() { p.die("late exit") })
}
func (p *simProc) Exited() bool {
@@ -1006,7 +1006,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
newest := func(h string) uint64 { return revs[h].Load() }
stopCheck, checked := make(chan struct{}), make(chan struct{})
- go func() { defer close(checked); w.checkGenerations(a, hosts, stopCheck) }()
+ goTracked(func() { defer close(checked); w.checkGenerations(a, hosts, stopCheck) })
var reqs, swaps sync.WaitGroup
var fenceGen atomic.Uint64
@@ -1023,7 +1023,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
sweepMu.Unlock()
}
stopSweeper, sweeperDone := make(chan struct{}), make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(sweeperDone)
tick := time.NewTicker(5 * time.Millisecond)
defer tick.Stop()
@@ -1035,7 +1035,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
sweep()
}
}
- }()
+ })
for i := 0; i < 25; i++ {
host := hosts[w.intn(len(hosts))]
rt := registry.Route{Host: host, Kind: "instance", Socket: filepath.Join(sockDir, host+".sock"),
@@ -1043,7 +1043,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
switch w.intn(15) {
case 0, 1:
reqs.Add(1)
- go func() {
+ goTracked(func() {
defer reqs.Done()
// An ordinary request: shared with other requests, never
// with a held admission on the host (I5).
@@ -1055,7 +1055,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
w.jitter()
release()
}
- }()
+ })
case 2, 3, 4:
mode := ModeOverlap
if w.intn(3) == 0 {
@@ -1069,7 +1069,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
// pinned wake; the rest meet whatever state the host is in.
wakeFirst := w.intn(4) != 0
swaps.Add(1)
- go func() {
+ goTracked(func() {
defer swaps.Done()
if wakeFirst {
w.heldHost[host].RLock()
@@ -1081,7 +1081,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
w.heldHost[host].RUnlock()
}
w.checkSwap(at, a.Swap(context.Background(), at, newest))
- }()
+ })
case 5:
clk.advance(2 * time.Hour)
sweep()
@@ -1092,7 +1092,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
a.Bounce(host)
case 8:
reqs.Add(1)
- go func() {
+ goTracked(func() {
defer reqs.Done()
g := fenceGen.Add(1)
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
@@ -1100,7 +1100,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
_, _ = a.FenceAndStop(ctx, host, g)
w.jitter()
a.LiftFence(host, g)
- }()
+ })
case 9:
w.setLive(host, []string{"v1", "v2"}[w.intn(2)])
revs[host].Add(1) // the scheduler's newer desired build supersedes in-flight attempts
@@ -1116,10 +1116,10 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
case 12, 13:
// Edge-held streams: admit a held leg (I4, I5).
reqs.Add(1)
- go func() {
+ goTracked(func() {
defer reqs.Done()
w.admitHeld(a, sb, rt)
- }()
+ })
case 14:
w.finishHeld()
}
@@ -1145,7 +1145,7 @@ func simulateSwapOnce(t testing.TB, seed int, staged map[string]simArtifact, soc
w.violatef("I2: %d generation process(es) still run after Shutdown returned", n)
}
done := make(chan struct{})
- go func() { swaps.Wait(); close(done) }()
+ goTracked(func() { swaps.Wait(); close(done) })
select {
case <-done:
case <-time.After(10 * time.Second):
diff --git a/internal/activator/wakeplan_test.go b/internal/activator/wakeplan_test.go
index 914e97bae..a9dcfc509 100644
--- a/internal/activator/wakeplan_test.go
+++ b/internal/activator/wakeplan_test.go
@@ -485,7 +485,7 @@ func TestFirstWakeWaitersGetTheLongerBudget(t *testing.T) {
first, b, _ := planActivator(t, WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good})
b.gate = make(chan struct{})
- time.AfterFunc(250*time.Millisecond, func() { close(b.gate) })
+ afterTracked(250*time.Millisecond, func() { close(b.gate) })
done, err := first.beginRequest(context.Background(), testRoute("one.example.com"))
if err != nil {
t.Fatalf("a first wake's waiter gave up at the ordinary bound: %v", err)
@@ -494,7 +494,7 @@ func TestFirstWakeWaitersGetTheLongerBudget(t *testing.T) {
plain, b2, _ := planActivator(t, WakePlan{Boot: good, Mode: ModeOverlap})
b2.gate = make(chan struct{})
- time.AfterFunc(250*time.Millisecond, func() { close(b2.gate) })
+ afterTracked(250*time.Millisecond, func() { close(b2.gate) })
if _, err := plain.beginRequest(context.Background(), testRoute("two.example.com")); !errors.Is(err, errWakeTimeout) {
t.Fatalf("an ordinary wake's waiter = %v, want errWakeTimeout at wakeWaitBound", err)
}
@@ -862,11 +862,11 @@ func TestAFailedWorkerFirstWakeFallsBackOnlyOnceItsCgroupIsEmpty(t *testing.T) {
a.Planner = func(context.Context, registry.Route) WakePlan {
return WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}
}
- go func() {
+ goTracked(func() {
waitFor(t, "the v2 child", func() bool { return len(b.calls()) == 1 })
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
_ = a.WakeWorker(alwaysOnWorkerRoute("bot.x.internal"))
if calls := b.calls(); len(calls) != 1 {
t.Fatalf("spawns %v: the good build started beside the failed worker's unproven host cgroup", calls)
@@ -889,11 +889,11 @@ func TestAFailedWorkerFirstWakeFallsBackToTheGoodBuild(t *testing.T) {
a.Planner = func(context.Context, registry.Route) WakePlan {
return WakePlan{Boot: next, Mode: ModeOverlap, FirstWake: true, Fallback: &good}
}
- go func() {
+ goTracked(func() {
waitFor(t, "the v2 child", func() bool { return len(b.calls()) == 1 })
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
if err := a.WakeWorker(alwaysOnWorkerRoute("bot.x.internal")); err != nil {
t.Fatalf("WakeWorker: %v, want the good build serving", err)
}
diff --git a/internal/activator/wakeslots_test.go b/internal/activator/wakeslots_test.go
index b3f56c9ed..e1c0fa3b6 100644
--- a/internal/activator/wakeslots_test.go
+++ b/internal/activator/wakeslots_test.go
@@ -212,13 +212,13 @@ func TestWakeSlotQueuedFirstWakeStillExecsTheCandidate(t *testing.T) {
a.wakeSlots = make(chan struct{}, 1)
hold := a.acquireWakeSlot(context.Background(), "other.example.com")
out := make(chan error, 1)
- go func() {
+ goTracked(func() {
done, err := a.beginRequest(context.Background(), testRoute("one.example.com"))
if err == nil {
done()
}
out <- err
- }()
+ })
time.Sleep(2500 * time.Millisecond)
if gens := b.started(); len(gens) != 0 {
t.Fatalf("spawned %+v while every slot was held", gens)
diff --git a/internal/activator/workerswap_test.go b/internal/activator/workerswap_test.go
index b1e1c6cd2..2ae610d54 100644
--- a/internal/activator/workerswap_test.go
+++ b/internal/activator/workerswap_test.go
@@ -69,11 +69,11 @@ func TestReplaceWorkerFallsBackToTheGoodBuild(t *testing.T) {
t.Fatal(err)
}
good := fakeIdentity("v1")
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), &good, one)
if res.Outcome != SwapFailed || res.Gen.Build != "v1" {
t.Fatalf("ReplaceWorker = %+v, want failed with the good v1 serving", res)
@@ -112,12 +112,12 @@ func TestACrashInsideAReplaceWorkerObservationIsCoalesced(t *testing.T) {
t.Fatal(err)
}
good := fakeIdentity("v1")
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
time.Sleep(100 * time.Millisecond)
b.lastWorker().crash()
a.sweepOnce() // the crash restart's arm, inside the observation
- }()
+ })
running.Store(true)
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), &good, one)
running.Store(false)
@@ -146,11 +146,11 @@ func TestReplaceWorkerInHoldModeStaysDown(t *testing.T) {
t.Fatal(err)
}
good := fakeIdentity("v1")
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeHold, fakeIdentity("v2")), &good, one)
if res.Outcome != SwapDown {
t.Fatalf("ReplaceWorker = %+v, want down", res)
@@ -171,11 +171,11 @@ func TestReplaceWorkerRestartFailureRespawnsTheServingBuild(t *testing.T) {
t.Fatal(err)
}
serving := a.entryServing(host)
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRestart, ModeOverlap, serving), nil, one)
if res.Outcome != SwapFailed {
t.Fatalf("ReplaceWorker = %+v", res)
@@ -193,10 +193,10 @@ func TestReplaceWorkerOneShotCleanExitIsReady(t *testing.T) {
if err := a.WakeWorker(alwaysOnWorkerRoute("bot.x.internal")); err != nil {
t.Fatal(err)
}
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
b.lastWorker().exit()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
if res.Outcome != SwapDone {
t.Fatalf("ReplaceWorker = %+v, want done", res)
@@ -259,7 +259,7 @@ func TestWakeWorkerWaitsOutAFirstWakeFallback(t *testing.T) {
switch {
case tc.firstWake && n == 1:
// The failing build dies inside its settle window.
- time.AfterFunc(20*time.Millisecond, func() { b.lastWorker().crash() })
+ afterTracked(20*time.Millisecond, func() { b.lastWorker().crash() })
case tc.firstWake && n == 2, !tc.firstWake && n == 1:
time.Sleep(250 * time.Millisecond) // the good build boots slowly
}
@@ -299,10 +299,10 @@ func TestReplaceWorkerReChecksAtTheSpawnAndBeforeTheResult(t *testing.T) {
var rev atomic.Uint64
rev.Store(1)
results := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
results <- a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil,
func(string) uint64 { return rev.Load() })
- }()
+ })
waitFor(t, "the retire to begin", func() bool { return a.entryRespawning(host) })
rev.Store(2) // a newer release lands while the old child drains
close(gate)
@@ -329,10 +329,10 @@ func TestReplaceWorkerReChecksAtTheSpawnAndBeforeTheResult(t *testing.T) {
}
var rev atomic.Uint64
rev.Store(1)
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
rev.Store(2)
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil,
func(string) uint64 { return rev.Load() })
if res.Outcome != SwapAbandoned || !strings.Contains(res.Reason, errSwapSuperseded.Error()) {
@@ -445,9 +445,9 @@ func TestReplaceWorkerWithoutOwnershipSpawnsNothing(t *testing.T) {
gate := make(chan struct{})
b.lastWorker().setStopGate(gate)
results := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
results <- a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
- }()
+ })
waitFor(t, "the retire to begin", func() bool { return a.entryRespawning(host) })
b.lastRep().setErr(errors.New("lease renewal failed")) // ownership lost mid-retire
close(gate)
@@ -514,7 +514,7 @@ func TestReplaceWorkerAnIntentionalStopDuringTheObservationIsNoVerdict(t *testin
a.mu.Lock()
a.entries[host].unexpectedExit = true // left by an earlier crash restart
a.mu.Unlock()
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
waitFor(t, "the observation", func() bool {
a.mu.Lock()
@@ -525,7 +525,7 @@ func TestReplaceWorkerAnIntentionalStopDuringTheObservationIsNoVerdict(t *testin
a.mu.Lock()
a.beginStopLocked(a.entries[host], StopIdle) // an operator's stop
a.mu.Unlock()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
if res.Outcome != SwapAbandoned {
t.Fatalf("ReplaceWorker = %+v, want abandoned: an intentional stop records nothing", res)
@@ -629,9 +629,9 @@ func TestALateWakePublicationNeverOverwritesItsReplacement(t *testing.T) {
e, inc0 := a.entries[host], a.entries[host].workerInc
a.mu.Unlock()
results := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
results <- a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
- }()
+ })
waitFor(t, "B's install", func() bool { a.mu.Lock(); defer a.mu.Unlock(); return e.workerInc > inc0 })
a.servingMu.Unlock()
locked = false
@@ -690,12 +690,12 @@ func TestAWorkerFallbackWithoutOwnershipSpawnsNothing(t *testing.T) {
t.Fatal(err)
}
good := fakeIdentity("v1")
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
b.lastRep().setErr(errors.New("lease renewal failed")) // ownership lost after B's exec
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), &good, one)
if res.Outcome != SwapFailed || res.Gen.Build != "" {
t.Fatalf("ReplaceWorker = %+v, want failed with nothing serving", res)
@@ -766,15 +766,15 @@ func TestAWorkerFallbackPublishesOnlyWhenReleased(t *testing.T) {
t.Fatal("the wake never published its identity")
}
good := fakeIdentity("v1")
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 2)
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
+ })
results := make(chan SwapResult, 1)
- go func() {
+ goTracked(func() {
results <- a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), &good, one)
- }()
+ })
select {
case res := <-results:
if res.Outcome != SwapFailed || res.Gen.Build != "v1" {
@@ -823,13 +823,13 @@ func TestAFallbackWakeRecordsTheFailureBeforeItPublishes(t *testing.T) {
called.Store(true)
<-block
}
- go func() {
+ goTracked(func() {
waitForWorkerStarts(t, b, 1)
time.Sleep(50 * time.Millisecond)
b.lastWorker().crash()
- }()
- go a.WakeWorker(alwaysOnWorkerRoute("bot.x.internal")) //nolint:errcheck
- evs.wait(t, GenFellBack) // arrives while the publication is still blocked
+ })
+ goTracked(func() { _ = a.WakeWorker(alwaysOnWorkerRoute("bot.x.internal")) })
+ evs.wait(t, GenFellBack) // arrives while the publication is still blocked
waitFor(t, "the publication", func() bool { return called.Load() })
close(block)
if !sawFailure.Load() {
@@ -957,7 +957,7 @@ func TestAnExitedOneShotIsGoodOnlyAfterACleanPark(t *testing.T) {
t.Fatal(err)
}
done := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(done)
waitForWorkerStarts(t, b, 2)
waitFor(t, "the observation", func() bool {
@@ -968,7 +968,7 @@ func TestAnExitedOneShotIsGoodOnlyAfterACleanPark(t *testing.T) {
})
b.lastWorker().exit() // status 0: the one-shot finished
tc.stop(t, a, b, host)
- }()
+ })
res := a.ReplaceWorker(context.Background(), workerAttempt(CauseRelease, ModeOverlap, fakeIdentity("v2")), nil, one)
<-done
if tc.clean {
diff --git a/internal/activator/writefence_test.go b/internal/activator/writefence_test.go
index faf2bbbc6..a20f6de8b 100644
--- a/internal/activator/writefence_test.go
+++ b/internal/activator/writefence_test.go
@@ -300,10 +300,10 @@ func TestWriteFenceRequestAndWatcherStopOnce(t *testing.T) {
case "together":
r.setErr(lease.ErrReplicaStale)
answered := make(chan struct{})
- go func() {
+ goTracked(func() {
defer close(answered)
assertLostResponse(t, s)
- }()
+ })
r.trip()
<-answered
waitFenced(t, s, e)
@@ -484,10 +484,10 @@ func TestWriteFenceDuringABlockedPublisherOpen(t *testing.T) {
woke := make(chan result, 1)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
- go func() {
+ goTracked(func() {
e, err := s.wakeForTest(ctx)
woke <- result{e, err}
- }()
+ })
var r *fenceTestRep
select {
case r = <-reps:
@@ -530,10 +530,10 @@ func TestWriteFenceDuringABlockedPublisherOpen(t *testing.T) {
t.Errorf("want an unclean marker, the lock is %+v", v)
}
ended := make(chan struct{})
- go func() {
+ goTracked(func() {
s.a.fenceWatchers.Wait()
close(ended)
- }()
+ })
waitClosed(t, "the watcher to end", ended, 5*time.Second)
}
@@ -686,10 +686,10 @@ func TestWriteFenceWakingAnswersAtOnce(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
r, store, entry := fencedPublisherWake(t, s, func() {
- go func() {
+ goTracked(func() {
_, err := s.wakeForTest(ctx)
woke <- err
- }()
+ })
})
r.trip()
store.armed.Store(false)
@@ -732,7 +732,7 @@ func TestWriteFenceWaitingCallerGetsTheLossAnswer(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
r, store, _ := fencedPublisherWake(t, s, func() {
- go func() { answered <- serveRequest(s, ctx) }()
+ goTracked(func() { answered <- serveRequest(s, ctx) })
})
r.trip()
store.armed.Store(false)
@@ -749,10 +749,10 @@ func TestWriteFenceWatcherEndsOnCleanHibernation(t *testing.T) {
s, e, r := fencedEntry(t)
s.stopForTest(e)
ended := make(chan struct{})
- go func() {
+ goTracked(func() {
s.a.fenceWatchers.Wait()
close(ended)
- }()
+ })
waitClosed(t, "the watchers to end", ended, 5*time.Second)
assertOneRelease(t, s, r)
}