Skip to content

fix(scheduler): drop the mock clock and drive tests with synctest (#9248) - #9267

Merged
cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
shashankvarma499:scheduler-use-injected-afterfunc
Sep 3, 2026
Merged

cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
shashankvarma499:scheduler-use-injected-afterfunc

Conversation

@shashankvarma499

@shashankvarma499 shashankvarma499 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

What

Deletes the dead afterFunc test hook and rewrites the scheduler tests with testing/synctest.

The afterFunc field on scheduledWorkQueue has been dead since it was added for testing in #4233: Add never routed through it, so the tests silently ran against real timers, and TestAdd raced on the mock clock state under -race.

Rather than wiring the hook up, this removes it. With Go 1.26 the tests drive the real afterFunc through clock.RealClock (a thin wrapper over time.NewTimer) inside a synctest bubble, so time is deterministic and race-free.

Why synctest instead of wiring the mock

  • The mock (mockAfter / timerQueueItem) carried its own unsynchronised bookkeeping that pkg/scheduler: TestAdd fails under -race; the test clock injection has been dead since #4233 #9248 flagged (Stop writes without a lock, currentTime read unlocked).
  • The old TestAdd "too early" check could never fire (it compared against how far warp advanced, always -1ms). The synctest version asserts the exact fire time and fails on a duration/2 mutation with "fired early".
  • Goroutine leaks are caught by synctest itself (a goroutine parked on its timer fails the test), so the runtime.NumGoroutine counting goes away.

Changes

  • pkg/scheduler/scheduler.go: remove the dead afterFunc field.
  • pkg/scheduler/scheduler_test.go: port TestAdd, TestForget, TestConcurrentAdd to synctest; replace the goroutine-counting Test_afterFunc/stop_works with TestAfterFuncStop; delete mockAfter/timerQueueItem.

Verification

go test -race ./pkg/scheduler/ -count=10 passes. Mutation checks: scheduling duration/2 fails with "fired early"; a cancel() that does not close cancelCh fails with a synctest deadlock.

Fixes #9248

NONE

@cert-manager-prow cert-manager-prow Bot added dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Sep 3, 2026
@cert-manager-prow

Copy link
Copy Markdown
Contributor

Hi @shashankvarma499. Thanks for your PR.

I'm waiting for a cert-manager member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

Regular contributors should join the org to skip this step.

Once the patch is verified, the new status will be reflected by the ok-to-test label.

I understand the commands that are listed here.

Details

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.

@cert-manager-prow cert-manager-prow Bot added the size/S Denotes a PR that changes 10-29 lines, ignoring generated files. label Sep 3, 2026
@wallrj
wallrj requested a balanced review from Copilot September 3, 2026 14:23

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.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Pull request overview

Fixes scheduler timer injection so tests use the fake clock reliably and adds stronger assertions to prevent regressions.

Changes:

  • Schedule work via the queue’s injected afterFunc instead of the package-level function.
  • Strengthen TestForget to assert scheduling uses the injected timer and that Forget stops it.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
pkg/scheduler/scheduler.go Routes scheduling through s.afterFunc so injected timers/mocks are honored.
pkg/scheduler/scheduler_test.go Adds assertions to ensure injected scheduling is used and timers are stopped by Forget.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread pkg/scheduler/scheduler_test.go Outdated
Comment on lines +167 to +175
item := after.queue[len(after.queue)-1]
after.lock.Unlock()

queue.Forget(test.obj)
after.warp(test.duration * 2)

after.lock.Lock()
assert.False(t, item.run)
assert.True(t, item.stopped)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good catch — addressed in the latest push: the item is now re-read under the lock at assertion time.

Comment thread pkg/scheduler/scheduler_test.go Outdated
Comment on lines +166 to +176
assert.Len(t, after.queue, before+1)
item := after.queue[len(after.queue)-1]
after.lock.Unlock()

queue.Forget(test.obj)
after.warp(test.duration * 2)

after.lock.Lock()
assert.False(t, item.run)
assert.True(t, item.stopped)
after.lock.Unlock()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed — values are now read into locals under the lock, and every assert runs outside it.

@cert-manager-prow cert-manager-prow Bot added release-note-none Denotes a PR that doesn't merit a release note. and removed do-not-merge/release-note-label-needed Indicates that a PR should not merge because it's missing one of the release note labels. labels Sep 3, 2026
@shashankvarma499

Copy link
Copy Markdown
Contributor Author

/kind bug

@cert-manager-prow cert-manager-prow Bot added kind/bug Categorizes issue or PR as related to a bug. and removed needs-kind Indicates a PR lacks a `kind/foo` label and requires one. labels Sep 3, 2026
@shashankvarma499
shashankvarma499 force-pushed the scheduler-use-injected-afterfunc branch 2 times, most recently from 2c8f974 to 0985642 Compare September 3, 2026 15:32
@cert-manager-prow cert-manager-prow Bot added dco-signoff: no Indicates that at least one commit in this pull request is missing the DCO sign-off message. and removed dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. labels Sep 3, 2026
@shashankvarma499
shashankvarma499 marked this pull request as draft September 3, 2026 15:32
@cert-manager-prow cert-manager-prow Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Sep 3, 2026
@shashankvarma499
shashankvarma499 marked this pull request as ready for review September 3, 2026 15:33
@cert-manager-prow cert-manager-prow Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Sep 3, 2026
Comment thread pkg/scheduler/scheduler.go Outdated
}

s.work[obj] = afterFunc(s.clock, duration, func() {
s.work[obj] = s.afterFunc(s.clock, duration, func() {

@wallrj wallrj Sep 3, 2026 •

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.

Consider replacing the mock timer with testing/synctest. You could then delete the afterFunc field, mockAfter, timerQueueItem and the goroutine-counting test. The resulting tests also catch bugs that the current ones miss.

Your change is correct. go test -race -count=30 ./pkg/scheduler/ passes at 2c8f974. But the afterFunc field exists only so that tests can inject mockAfter. The mock still has the locking problems that #9248 described:

  • Stop() writes stopped without holding the mock's lock.
  • The test reads currentTime without the lock at lines 111 and 114.

The race detector stays quiet only by luck. warp checks item.run first, and the subtests run one at a time.

Why synctest works here

  • go.mod is on Go 1.26. This repo already uses testing/synctest in pkg/server/tls/dynamic_source_test.go.
  • RealClock.NewTimer is a thin wrapper over time.NewTimer (k8s.io/utils clock.go#L105-L109). Timers created inside a synctest bubble use the bubble's fake clock.
  • So the tests can drive the real afterFunc with clock.RealClock{} and no mock at all.
  • A goroutine left waiting on a timer makes synctest.Test fail by itself. That replaces the goroutine-counting Test_afterFunc/stop_works.

The prototype is stronger than the current tests

I prototyped it below. It passes go test -race -count=20. I then broke the production code in two ways to see what each test suite catches:

Mutation Current tests Prototype
cancel() does not close cancelCh not checked fails: deadlock: main bubble goroutine has exited but blocked goroutines remain
Add schedules after duration/2 TestAdd passes fails: fired early

The second row is the important one. See the summary comment for why the current TestAdd cannot catch it.

Prototype
func TestAdd(t *testing.T) {
	for _, d := range []time.Duration{500 * time.Millisecond, time.Second, 3 * time.Second} {
		t.Run(d.String(), func(t *testing.T) {
			synctest.Test(t, func(t *testing.T) {
				start := time.Now()
				var mu sync.Mutex
				var firedAt time.Time
				queue := NewScheduledWorkQueue(clock.RealClock{}, func(obj string) {
					mu.Lock()
					defer mu.Unlock()
					firedAt = time.Now()
				})
				queue.Add("obj", d)

				time.Sleep(d - time.Nanosecond)
				synctest.Wait()
				mu.Lock()
				assert.True(t, firedAt.IsZero(), "fired early")
				mu.Unlock()

				time.Sleep(time.Nanosecond)
				synctest.Wait()
				mu.Lock()
				assert.Equal(t, start.Add(d), firedAt)
				mu.Unlock()
			})
		})
	}
}

func TestForget(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		queue := NewScheduledWorkQueue(clock.RealClock{}, func(string) {
			t.Error("scheduled function should never be called")
		})
		queue.Add("obj", time.Second)
		queue.Forget("obj")
		time.Sleep(time.Hour)
		synctest.Wait()
		// synctest.Test also fails if the afterFunc goroutine is still parked when this returns.
	})
}

func TestAfterFuncStop(t *testing.T) {
	synctest.Test(t, func(t *testing.T) {
		for range 10000 {
			cancel := afterFunc(clock.RealClock{}, time.Hour, func() { t.Error("should never be called") })
			cancel()
		}
	})
}

TestConcurrentAdd ports the same way. Wrap the body in synctest.Test and replace after.warp(5s) with time.Sleep(5s); synctest.Wait().

[Claude Fable 5.1]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks, that is the right depth. Adopted the synctest approach: deleted the afterFunc field, mockAfter and timerQueueItem, and ported the tests to your prototype. go test -race ./pkg/scheduler/ -count=10 passes, and the duration/2 mutation now fails with "fired early".


s.work[obj] = afterFunc(s.clock, duration, func() {
s.work[obj] = s.afterFunc(s.clock, duration, func() {
defer s.Forget(obj)

@wallrj wallrj Sep 3, 2026 •

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 is a pre-existing bug, not one this PR introduces. The deferred Forget(obj) can cancel a newer timer for the same key and silently lose a reschedule. I suggest we track it in a separate issue rather than fix it here.

How it happens

Nothing holds workLock between processFunc returning and the deferred Forget running. If another goroutine calls Add(obj, d2) in that window, line 106 stores the new cancel function in s.work[obj]. The deferred Forget then cancels and deletes that new timer. The old cancel() is a no-op because its timer has already fired.

Who is affected

All three callers reschedule from inside reconcile, with processFunc = queue.Add:

  • trigger_controller.go:197
  • readiness_controller.go:372
  • acmeorders/sync.go:234

The worst case is an Order polled on the 5s RequeuePeriod. If it loses a reschedule, nothing retries it until the 10h informer resync.

Suggested fix

Have the callback delete the map entry only if it still holds its own cancel function. Compare a per-timer token under workLock instead of calling the unconditional Forget.

The window is tiny. The worker has to dequeue the key and finish a whole reconcile before this goroutine reaches its defer. I have not reproduced it, only read the code.

[Claude Fable 5.1]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, that window is real. Happy to pick up the follow-up issue once you file it.

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.

Filed as #9269. Thank you for offering to pick it up.

[Claude Fable 5.1]

Comment thread pkg/scheduler/scheduler_test.go Outdated
after.lock.Lock()
queueLen := len(after.queue)
after.lock.Unlock()
assert.Equal(t, before+1, queueLen)

@wallrj wallrj Sep 3, 2026 •

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.

Please make this check fatal. If Add ever bypasses the injected afterFunc again, this test panics instead of failing cleanly.

Suggested change
assert.Equal(t, before+1, queueLen)
if !assert.Equal(t, before+1, queueLen, "Add did not schedule through the injected afterFunc") {
return
}
Why

assert.Equal does not stop the test. On that regression the queue is empty, so the next line indexes after.queue[-1]. I reproduced it by reverting line 106 to afterFunc(:

--- FAIL: TestForget (0.00s)
        scheduler_test.go:168: Error: Not equal: ...
panic: runtime error: index out of range [-1] [recovered, repanicked]

[Claude Fable 5.1]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Gone with the mock. The synctest rewrite removes this assertion entirely.

Comment thread pkg/scheduler/scheduler_test.go Outdated
// so assertion helpers never run while the mock's lock is held.
after.lock.Lock()
item := after.queue[len(after.queue)-1]
run, stopped := item.run, item.stopped

@wallrj wallrj Sep 3, 2026 •

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 reads item.stopped under after.lock, but the writer never takes that lock. Please take m.lock inside Stop(), or drop the mock for synctest as suggested in the other comment.

Evidence
  • timerQueueItem.Stop() at line 219 writes stopped under the queue's workLock only.
  • warp at line 255 also reads stopped under after.lock.
  • The race detector stays quiet only because warp checks item.run first and the subtests run one at a time. Swap the order of that condition, or add t.Parallel() to the subtests, and the detector reports it.
  • Stop() is never called with m.lock held, so taking it there is safe.

#9248 asked for the mock to be synchronised together with the wiring.

[Claude Fable 5.1]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same here, resolved by the synctest rewrite. The mock and its one-sided locking are deleted.

@wallrj

wallrj commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

The fix is correct and both Copilot comments are addressed. Two of the existing tests are weaker than they look. Those lines are outside the diff, so I am noting them here rather than inline.

TestAdd's "too early" check cannot fail (scheduler_test.go:114-118). durationEarly compares against how far warp advanced, not against when the item was scheduled. So it is always -1ms. If you change Add to schedule after duration/2, TestAdd still passes. #9248 said this check could never fire while the mock was bypassed. Wiring the mock up does not change that. You could assert the queued item's t against currentTime + duration. Or synctest gives you this for free. See the inline comment on scheduler.go:106.

TestConcurrentAdd calls t.Fatalf from the callback (scheduler_test.go:195). Now that the mock is really injected, a regression runs that callback on the goroutine started by warp. FailNow must run on the test goroutine. t.Errorf is enough here.

What I checked
  • go test -race -count=30 ./pkg/scheduler/ passes at 2c8f974.
  • queue is []*timerQueueItem, and the asserts run outside the lock, so both Copilot comments are resolved.
  • Minor and pre-existing: the WaitGroup in TestForget does nothing. defer wg.Done() runs at the top of each sequential subtest, and wg.Wait() runs after every t.Run has returned.

[Claude Fable 5.1]

…rt-manager#9248)

The scheduledWorkQueue.afterFunc field was added for testing purposes in
cert-manager#4233, but Add never used it, so tests ran against real timers and
TestAdd raced on the mock clock state under -race.

Rather than wiring the dead hook up, delete it: with Go 1.26 the tests
can use testing/synctest, which drives the real afterFunc through
k8s.io/utils clock.RealClock deterministically. This removes the
unsynchronised mockAfter bookkeeping that cert-manager#9248 flagged, makes the
"fired early" check actually fail when Add mis-schedules, and catches
goroutine leaks without runtime.NumGoroutine counting.

Fixes cert-manager#9248

Signed-off-by: Shashank Varma <[email protected]>
@shashankvarma499
shashankvarma499 force-pushed the scheduler-use-injected-afterfunc branch from 0985642 to a21ed0b Compare September 3, 2026 15:39
@cert-manager-prow cert-manager-prow Bot removed the dco-signoff: no Indicates that at least one commit in this pull request is missing the DCO sign-off message. label Sep 3, 2026
@cert-manager-prow cert-manager-prow Bot added dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. and removed size/S Denotes a PR that changes 10-29 lines, ignoring generated files. labels Sep 3, 2026
@shashankvarma499 shashankvarma499 changed the title fix(scheduler): use the injected afterFunc to schedule work fix(scheduler): drop the mock clock and drive tests with synctest (#9248) Sep 3, 2026
@shashankvarma499

Copy link
Copy Markdown
Contributor Author

Both points addressed in the synctest rewrite: the too-early check now asserts the exact fire time against the fake clock (and catches the duration/2 mutation), TestConcurrentAdd uses t.Errorf, and the no-op WaitGroup is gone. Thanks for the thorough review.

@wallrj

wallrj commented Sep 3, 2026

Copy link
Copy Markdown
Member

/ok-to-test

@cert-manager-prow cert-manager-prow Bot added ok-to-test and removed needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Sep 3, 2026

@wallrj wallrj 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.

/lgtm
/approve

Thank you. This is a clear improvement. It removes a test-only hook from production code, and the new tests catch mutations that the old ones did not.

I verified a21ed0b locally. The scheduler tests pass with the race detector, run twenty times. Scheduling at half the duration fails with "fired early", and a cancel that does not close its channel fails with a synctest deadlock.

The Forget race is tracked in #9269.

[Claude Fable 5.1]

@cert-manager-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: wallrj

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 lgtm Indicates that a PR is ready to be merged. approved Indicates a PR has been approved by an approver from all required OWNERS files. labels Sep 3, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit 1e7c04e into cert-manager:master Sep 3, 2026
6 checks passed
@wallrj

wallrj commented Sep 8, 2026

Copy link
Copy Markdown
Member

/cherry-pick release-1.21

Backporting this test-only change for v1.21.2 (tracker: #9237) because #9270 depends on it. The fix in #9270 comes with a regression test written against the synctest helpers this PR introduced, and that test does not compile on release-1.21 without them. Picking both keeps the backport identical to master rather than rewriting the test against the old mock clock.

[Claude Fable 5.1]

@cert-manager-bot

Copy link
Copy Markdown
Contributor

@wallrj: new pull request created: #9311

Details

In response to this:

/cherry-pick release-1.21

Backporting this test-only change for v1.21.2 (tracker: #9237) because #9270 depends on it. The fix in #9270 comes with a regression test written against the synctest helpers this PR introduced, and that test does not compile on release-1.21 without them. Picking both keeps the backport identical to master rather than rewriting the test against the old mock clock.

[Claude Fable 5.1]

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.

@wallrj wallrj mentioned this pull request Sep 8, 2026
39 of 41 tasks
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/bug Categorizes issue or PR as related to a bug. lgtm Indicates that a PR is ready to be merged. ok-to-test release-note-none Denotes a PR that doesn't merit a release note. size/L Denotes a PR that changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

pkg/scheduler: TestAdd fails under -race; the test clock injection has been dead since #4233

4 participants