Repository navigation
fix(scheduler): drop the mock clock and drive tests with synctest (#9248) - #9267
Conversation
|
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 Regular contributors should join the org to skip this step. Once the patch is verified, the new status will be reflected by the I understand the commands that are listed here. DetailsInstructions 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. |
There was a problem hiding this comment.
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
afterFuncinstead of the package-level function. - Strengthen
TestForgetto assert scheduling uses the injected timer and thatForgetstops 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.
| 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) |
There was a problem hiding this comment.
Good catch — addressed in the latest push: the item is now re-read under the lock at assertion time.
| 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() |
There was a problem hiding this comment.
Fixed — values are now read into locals under the lock, and every assert runs outside it.
|
/kind bug |
2c8f974 to
0985642
Compare
| } | ||
|
|
||
| s.work[obj] = afterFunc(s.clock, duration, func() { | ||
| s.work[obj] = s.afterFunc(s.clock, duration, func() { |
There was a problem hiding this comment.
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()writesstoppedwithout holding the mock's lock.- The test reads
currentTimewithout 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.modis on Go 1.26. This repo already usestesting/synctestinpkg/server/tls/dynamic_source_test.go.RealClock.NewTimeris a thin wrapper overtime.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
afterFuncwithclock.RealClock{}and no mock at all. - A goroutine left waiting on a timer makes
synctest.Testfail by itself. That replaces the goroutine-countingTest_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]
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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:197readiness_controller.go:372acmeorders/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]
There was a problem hiding this comment.
Agreed, that window is real. Happy to pick up the follow-up issue once you file it.
There was a problem hiding this comment.
Filed as #9269. Thank you for offering to pick it up.
[Claude Fable 5.1]
| after.lock.Lock() | ||
| queueLen := len(after.queue) | ||
| after.lock.Unlock() | ||
| assert.Equal(t, before+1, queueLen) |
There was a problem hiding this comment.
Please make this check fatal. If Add ever bypasses the injected afterFunc again, this test panics instead of failing cleanly.
| 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]
There was a problem hiding this comment.
Gone with the mock. The synctest rewrite removes this assertion entirely.
| // 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 |
There was a problem hiding this comment.
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 writesstoppedunder the queue'sworkLockonly.warpat line 255 also readsstoppedunderafter.lock.- The race detector stays quiet only because
warpchecksitem.runfirst and the subtests run one at a time. Swap the order of that condition, or addt.Parallel()to the subtests, and the detector reports it. Stop()is never called withm.lockheld, so taking it there is safe.
#9248 asked for the mock to be synchronised together with the wiring.
[Claude Fable 5.1]
There was a problem hiding this comment.
Same here, resolved by the synctest rewrite. The mock and its one-sided locking are deleted.
|
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.
What I checked
[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]>
0985642 to
a21ed0b
Compare
|
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. |
|
/ok-to-test |
wallrj
left a comment
There was a problem hiding this comment.
/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]
|
[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 DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
|
/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 [Claude Fable 5.1] |
|
@wallrj: new pull request created: #9311 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. |
What
Deletes the dead
afterFunctest hook and rewrites the scheduler tests withtesting/synctest.The
afterFuncfield onscheduledWorkQueuehas been dead since it was added for testing in #4233:Addnever routed through it, so the tests silently ran against real timers, andTestAddraced 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
afterFuncthroughclock.RealClock(a thin wrapper overtime.NewTimer) inside a synctest bubble, so time is deterministic and race-free.Why synctest instead of wiring 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 (Stopwrites without a lock,currentTimeread unlocked).TestAdd"too early" check could never fire (it compared against how farwarpadvanced, always -1ms). The synctest version asserts the exact fire time and fails on aduration/2mutation with "fired early".runtime.NumGoroutinecounting goes away.Changes
pkg/scheduler/scheduler.go: remove the deadafterFuncfield.pkg/scheduler/scheduler_test.go: portTestAdd,TestForget,TestConcurrentAddto synctest; replace the goroutine-countingTest_afterFunc/stop_workswithTestAfterFuncStop; deletemockAfter/timerQueueItem.Verification
go test -race ./pkg/scheduler/ -count=10passes. Mutation checks: schedulingduration/2fails with "fired early"; acancel()that does not closecancelChfails with a synctest deadlock.Fixes #9248