Repository navigation
Fix flaky goroutine-leak test in pkg/scheduler - #9217
cert-manager-prow[bot] merged 2 commits into
Conversation
Test_afterFunc/stop_works starts 10000 afterFunc goroutines, cancels them all, then sleeps a fixed 100ms before comparing runtime.NumGoroutine() against the baseline taken at the start. Those goroutines exit asynchronously, so on a loaded machine 100ms is not nearly long enough for 10000 of them to be scheduled and exit, and the test fails despite there being no leak. Reproducing it showed a second, independent problem. The assertion used assert.InDelta, which fails in both directions, but this is a leak check where only an increase matters. Tests sharing the binary run concurrently, so the baseline can include goroutines that have since exited, leaving fewer at the end than there were at the start. - Poll for the count to come back down, up to a 30s deadline, rather than sleeping a fixed amount. A real leak never recovers, so it still fails once the deadline passes. - Assert an upper bound with assert.LessOrEqual instead of a two-sided delta. Verified by pinning the prebuilt test binary to a single saturated core: 2 of 8 runs failed before the change, exercising both directions (once 1494 goroutines above the baseline, once 1494 below it), and 15 of 15 passed after. Also checked the test still catches a real leak rather than merely having been made unfailable, by temporarily replacing the "case <-cancelCh: return" in afterFunc with a block that never returns. It fails as intended, with "10000 is not less than or equal to 100". Signed-off-by: Richard Wall <[email protected]>
Review of the previous commit found two problems: - The comment justifying the one-sided assertion claimed that tests sharing the binary run concurrently, but no test in this package calls t.Parallel() and Test_afterFunc runs first, so nothing runs concurrently with it. The below-baseline counts come from `go test -count=N` reruns, where one run's baseline includes still-draining goroutines from the previous run. - The hand-rolled deadline/sleep loop re-implemented assert.Eventually, which is already imported here and is the established pattern for poll-until-deadline assertions elsewhere in this repository. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Richard Wall <[email protected]>
There was a problem hiding this comment.
The code change looks good to me. Things I checked rather than assumed:
assert.Eventuallydoes not add latency on the happy path here. testify v1.12.1, which is what this repo pins, evaluates the condition once immediately before entering the tick loop (// Check the condition once first on the initial call.followed bygo checkCond()inassert/assertions.go), so there is no 10ms floor when nothing has leaked.- No data race introduced by the new closure: it reads
runtime.NumGoroutine()locally rather than writing a shared variable, so nothing crosses the goroutine boundary. - At most one checker goroutine is in flight at a time, since testify leaves the tick channel nil until a result is consumed. That is +1 against a tolerance of 100, so the self-inflation is not a concern.
- The assertion is still failable: the condition is a one-sided upper bound that a genuine leak never satisfies, so it fails once the 30s deadline passes.
On the data race you mention at the end: it reproduces for me too. go test ./pkg/scheduler/ -race fails TestAdd with a WARNING: DATA RACE, timerQueueItem.Stop() mutating stopped unlocked against the read under m.lock in warp(). Agree it belongs in a separate PR, and it seems worth filing so it is not lost.
The one thing I would ask for before this merges is a refresh of the PR description. It still describes the revision before 252849c, and in one place it now states the opposite of the code:
- The motivation section says the test "may run concurrently with other tests in the same binary, so the baseline can include goroutines belonging to other tests that have since exited". The comment in this diff now correctly says nothing runs concurrently with it in this binary. See the inline note.
- Under "The change", "Assert an upper bound with
assert.LessOrEqual" no longer matches the code, which usesassert.Eventually. - The failure-injection output quoted under "How I tested it" is
Error: "10000" is not less than or equal to "100", which is theLessOrEqualmessage. WithEventuallythe failure readsCondition never satisfied. The-test.count=15table is from that earlier revision too.
None of that changes the diff, but the description is the part a reader reaches for when they hit this test again in a year, and right now it would teach them something untrue about how go test schedules subtests.
[written by Claude]
| // Only an increase is a failure. Nothing runs concurrently with this | ||
| // test in this binary, but under `go test -count=N` the baseline of a | ||
| // run can include still-draining goroutines from the previous run, | ||
| // which later exit, leaving fewer goroutines at the end than at the | ||
| // start. |
There was a problem hiding this comment.
This wording is correct, and the correction was worth making: pkg/scheduler has a single test file with no t.Parallel() and no TestMain, and Go only runs tests concurrently across packages, which are separate binaries, never within one.
Flagging it because the PR description still carries the old claim, that the test "may run concurrently with other tests in the same binary". So the body and the code now say opposite things, and the body is the version a reviewer reads first.
One narrowing you might consider, entirely optional: within a single run nothing can precede this subtest, since it is the first subtest of the first test in the only file, so the residue cannot come from a sibling. It comes from this subtest's own previous iteration under -count=N, because the wait returns as soon as the excess is inside tolerance and up to 100 goroutines may still be draining when the run ends. The committed wording is accurate as it stands, so this is only worth folding in if you are pushing again anyway.
[written by Claude]
| return runtime.NumGoroutine()-expected <= tolerance | ||
| }, 30*time.Second, 10*time.Millisecond, "afterFunc leaked goroutines: cancel() did not stop them all") | ||
|
|
||
| t.Logf("%d goroutines before, %d goroutines after", expected, runtime.NumGoroutine()) |
There was a problem hiding this comment.
Nit, non-blocking: this takes a fresh runtime.NumGoroutine() sample after the assertion has already returned, so the number logged is not necessarily the one that satisfied the condition. Diagnostics only, and on a failure the magnitude is what matters, so it is fine either way. Capturing the value inside the closure would make the log and the assertion agree, at the cost of a shared variable and the mutex that would then need.
[written by Claude]
|
Thanks @maelvls — description refreshed. All three stale points are fixed: the motivation now describes the On the data race, I dug further before filing and it is more interesting than my original footnote suggested. The reported race is actually on I have not pushed another commit: the comment-wording narrowing was optional and the committed wording is accurate, and I agree the with claude fable-5 |
|
All good! I've also done a human inspection, and since it's test code it's all good 👍 /lgtm |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: maelvls The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
|
/cherry-pick release-1.21 |
|
@wallrj: new pull request created: #9261 DetailsIn response to this:
Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository. |
Pull Request Motivation
Test_afterFunc/stop_worksinpkg/scheduleris flaky on a loaded machine, and fails in a way that looks alarming — it reports thousands of "leaked" goroutines when nothing has leaked.The test starts 10000
afterFuncgoroutines, cancels them all, then sleeps a fixed 100 ms before comparingruntime.NumGoroutine()against a baseline taken at the start:Those goroutines exit asynchronously.
cancel()returning does not mean the goroutine has been scheduled and run to completion, so on a busy machine 100 ms is nowhere near long enough for 10000 of them to drain. The comment even acknowledges we don't know when they will finish, and then sleeps a fixed amount anyway.Reproducing it turned up a second, independent problem.
assert.InDeltafails in both directions, but this is a leak check where only an increase matters. Nothing runs concurrently with this subtest in this binary —pkg/schedulerhas a single test file with not.Parallel(), and this is the first subtest of the first test — but under repeated in-process runs (-test.count=N, or a test runner's rerun-on-fail) the baseline of one run can include still-draining goroutines left over from the previous run. Those exit during the run, leaving fewer goroutines at the end than at the start, and failing the two-sided assertion. (An earlier revision of this description blamed concurrent tests in the same binary; @maelvls pointed out that was wrong — Go only runs tests concurrently across packages, which are separate binaries.)I hit both directions within a single
-test.count=8run, which is what convinced me the two-sidedness was worth fixing as well as the sleep.The change
assert.Eventually(30 s deadline, 10 ms tick) for the goroutine count to come back down, instead of sleeping a fixed amount. A genuine leak never recovers, so it still fails once the deadline passes — the test does not become unfailable. testify evaluates the condition once immediately before entering the tick loop, so there is no added latency on the happy path.actual - expected <= tolerance) rather than a two-sided delta, and the failure carries an explanatory message.The tolerance of 100 and the 10000 goroutines are unchanged, so what the test checks is the same; only how long it is willing to wait, and the direction it cares about, have changed.
How I tested it
To imitate a loaded CI machine I built the test binary first, then pinned it to a single saturated core:
-test.count=8assert.Eventually),-test.count=153 goroutines before, 13 goroutines afterthen13 goroutines before, 3 goroutines after— the residue mechanism described above, caught in the act.-count=5, no contentionok github.com/cert-manager/cert-manager/pkg/scheduler 23.428sThe "before" failures look like this, and are the reason the flake is easy to misread as a real leak:
I also checked the test can still catch a real leak, rather than merely having been made unfailable. Temporarily replacing the
case <-cancelCh:inafterFuncwith a case that never fires:That injection was reverted; the diff touches only
scheduler_test.go.Related
#4856 and #4843 covered the sibling subtest, "f is called after roughly 100 milliseconds", whose delta was widened for much the same reason. This PR is about the goroutine-leak subtest, which was left alone at the time.
While in here I noticed that
go test -race ./pkg/scheduler/failsTestAddon master today. Digging into it turned up more than a mock locking bug: the mock clock has not actually been injected since #4233 —Addcalls the package-levelafterFuncrather than thes.afterFuncfield the tests set — soTestAdd/TestForgetrun on the real clock and the mock'swarp()races the real-timer callbacks. Now filed with full analysis as #9248; deliberately left out of this PR to keep the change focused.Kind
/kind flake
Release Note
with claude fable-5