Skip to content

Fix flaky goroutine-leak test in pkg/scheduler - #9217

Merged
cert-manager-prow[bot] merged 2 commits into
cert-manager:masterfrom
wallrj-cyberark:scheduler-goroutine-flake
Sep 1, 2026
Merged

cert-manager-prow[bot] merged 2 commits into
cert-manager:masterfrom
wallrj-cyberark:scheduler-goroutine-flake

Conversation

@wallrj-cyberark

@wallrj-cyberark wallrj-cyberark commented Aug 30, 2026 •

Copy link
Copy Markdown
Member

Pull Request Motivation

Test_afterFunc/stop_works in pkg/scheduler is 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 afterFunc goroutines, cancels them all, then sleeps a fixed 100 ms before comparing runtime.NumGoroutine() against a baseline taken at the start:

for _, cancel := range cancels {
	cancel()
}

// We don't know when the goroutines will actually finish.
time.Sleep(100 * time.Millisecond)

assert.InDelta(t, expected, runtime.NumGoroutine(), 100)

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.InDelta fails in both directions, but this is a leak check where only an increase matters. Nothing runs concurrently with this subtest in this binary — pkg/scheduler has a single test file with no t.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=8 run, which is what convinced me the two-sidedness was worth fixing as well as the sleep.

The change

  • Poll with 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.
  • The polled condition is a one-sided upper bound (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:

go test -c -o sched.test ./pkg/scheduler/
for i in $(seq 8); do taskset -c 0 bash -c 'while :; do :; done' & done
taskset -c 0 ./sched.test -test.run 'Test_afterFunc/stop_works' -test.count=N -test.v
Result
Before, -test.count=8 2 failed. One run 1494 goroutines above the baseline, the next 1494 below it — both failure modes.
After (assert.Eventually), -test.count=15 15 passed. One adjacent pair of runs logged 3 goroutines before, 13 goroutines after then 13 goroutines before, 3 goroutines after — the residue mechanism described above, caught in the act.
After, whole package -count=5, no contention ok github.com/cert-manager/cert-manager/pkg/scheduler 23.428s

The "before" failures look like this, and are the reason the flake is easy to misread as a real leak:

scheduler_test.go:56: 3 goroutines before, 1497 goroutines after
    Error: Max difference between 3 and 1497 allowed is 100, but difference was -1494
scheduler_test.go:56: 1497 goroutines before, 3 goroutines after
    Error: Max difference between 1497 and 3 allowed is 100, but difference was 1494

I also checked the test can still catch a real leak, rather than merely having been made unfailable. Temporarily replacing the case <-cancelCh: in afterFunc with a case that never fires:

scheduler_test.go:64:
    Error:      	Condition never satisfied
    Test:       	Test_afterFunc/stop_works
    Messages:   	afterFunc leaked goroutines: cancel() did not stop them all
scheduler_test.go:68: 3 goroutines before, 10003 goroutines after
--- FAIL: Test_afterFunc/stop_works (30.07s)

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/ fails TestAdd on master today. Digging into it turned up more than a mock locking bug: the mock clock has not actually been injected since #4233 — Add calls the package-level afterFunc rather than the s.afterFunc field the tests set — so TestAdd/TestForget run on the real clock and the mock's warp() 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

NONE

with claude fable-5

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]>
@cert-manager-prow cert-manager-prow Bot added release-note-none Denotes a PR that doesn't merit a release note. kind/flake Categorizes issue or PR as related to a flaky test. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. size/S Denotes a PR that changes 10-29 lines, ignoring generated files. labels Aug 30, 2026
@wallrj
wallrj requested a lite review from Copilot August 31, 2026 08:26

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

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]>

@maelvls maelvls left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code change looks good to me. Things I checked rather than assumed:

  • assert.Eventually does 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 by go checkCond() in assert/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:

  1. 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.
  2. Under "The change", "Assert an upper bound with assert.LessOrEqual" no longer matches the code, which uses assert.Eventually.
  3. The failure-injection output quoted under "How I tested it" is Error: "10000" is not less than or equal to "100", which is the LessOrEqual message. With Eventually the failure reads Condition never satisfied. The -test.count=15 table 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]

Comment on lines +58 to +62
// 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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]

@wallrj

wallrj commented Sep 1, 2026

Copy link
Copy Markdown
Member

Thanks @maelvls — description refreshed. All three stale points are fixed: the motivation now describes the -count=N residue mechanism instead of the concurrent-tests claim (with a note crediting the correction), "The change" says assert.Eventually, and the test evidence is regenerated against the current revision — the failure injection now shows the Condition never satisfied output, and a fresh 15-run pinned-core rerun happened to catch the residue mechanism in the act (3 before, 13 after followed by 13 before, 3 after in adjacent runs), which also confirms your narrowing: the residue is this subtest's own previous iteration.

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 mockAfter.currentTime (unlocked read in the callback vs the locked write in warp()), not timerQueueItem.stopped — that one is real too, but latent, because the mock is never actually exercised: Add calls the package-level afterFunc rather than the s.afterFunc field the tests set, and has done since #4233 converted the swappable package var into a field. So TestAdd/TestForget have been running on the real clock all along, and warp() schedules nothing. Filed with the full analysis and permalinks as #9248.

I have not pushed another commit: the comment-wording narrowing was optional and the committed wording is accurate, and I agree the t.Logf re-sample is fine as diagnostics.

with claude fable-5

@maelvls

maelvls commented Sep 1, 2026

Copy link
Copy Markdown
Member

All good! I've also done a human inspection, and since it's test code it's all good 👍

/lgtm
/approve

@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Sep 1, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

[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

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@cert-manager-prow cert-manager-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Sep 1, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 39cf357 into cert-manager:master Sep 1, 2026
6 checks passed
@wallrj-cyberark
wallrj-cyberark deleted the scheduler-goroutine-flake branch September 1, 2026 15:27
@wallrj

wallrj commented Sep 3, 2026

Copy link
Copy Markdown
Member

/cherry-pick release-1.21

@cert-manager-bot

Copy link
Copy Markdown
Contributor

@wallrj: new pull request created: #9261

Details

In response to this:

/cherry-pick release-1.21

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. kind/flake Categorizes issue or PR as related to a flaky test. lgtm Indicates that a PR is ready to be merged. release-note-none Denotes a PR that doesn't merit a release note. size/S Denotes a PR that changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants