Repository navigation
fix(scheduler): keep a newer timer for the same key from being cancelled (#9269) - #9270
Conversation
|
/kind bug |
|
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. |
| work map[T]func() | ||
| work map[T]workEntry | ||
| workLock sync.Mutex | ||
| nextToken uint64 |
There was a problem hiding this comment.
This branch needs a rebase. #9267 merged earlier today and GitHub now reports this PR as conflicting. #9267 deleted the afterFunc field and the mockAfter harness, so the two lines below nextToken no longer exist on master, and the test file has been rewritten around synctest.
I rebased locally to check that the fix itself survives. The only conflict is this struct (keep nextToken, drop the afterFunc field). After that, go test -race -count=5 ./pkg/scheduler/ passes, and reverting forgetIfOwned to Forget still makes TestAddDuringCallbackKeepsNewerTimer fail. The note in the description about TestAdd failing under -race is now stale too.
Evidence
$ gh pr view 9270 --json mergeable,mergeStateStatus
{"mergeStateStatus":"DIRTY","mergeable":"CONFLICTING"}
$ git rebase upstream/master
CONFLICT (content): Merge conflict in pkg/scheduler/scheduler.go
The struct on master after #9267:
cert-manager/pkg/scheduler/scheduler.go
Lines 72 to 77 in a21ed0b
[Claude Fable 5.1]
There was a problem hiding this comment.
Rebased on master after #9267, and the stale TestAdd note is gone from the description.
| // forgetIfOwned cancels and removes the work entry for obj only if that | ||
| // entry still belongs to the timer identified by token. A newer Add for | ||
| // the same obj replaces the entry, and a fired timer's cleanup must not | ||
| // cancel it. |
There was a problem hiding this comment.
The guarantee the callers rely on is documented only here, on an unexported helper. The exported Add doc, and the interface doc at L63, still say only "the previous timer will be cancelled".
All three production callers call Add from inside the reconcile that the fired timer triggered, which is exactly the window this PR protects:
One sentence on the exported Add doc would stop a future simplification from reintroducing #9269. For example: "An Add made while ProcessFunc is still running for obj is kept. The fired timer's cleanup never cancels it."
[Claude Fable 5.1]
There was a problem hiding this comment.
Done. The guarantee is now documented on the exported Add doc in both the interface and the implementation, in your suggested wording.
|
|
||
| mu.Lock() | ||
| defer mu.Unlock() | ||
| assert.Equal(t, []string{"obj", "obj"}, calls) |
There was a problem hiding this comment.
The test checks the call sequence but not that the map drains. A forgetIfOwned that never matches would pass every test in the package while leaking one entry per key for the life of the controller. I confirmed this by changing the guard to ok && false: all tests still pass.
One extra line after the final synctest.Wait() closes the gap. With it, the same mutation fails, and the unmutated code passes -race -count=20.
| assert.Equal(t, []string{"obj", "obj"}, calls) | |
| assert.Equal(t, []string{"obj", "obj"}, calls) | |
| assert.Empty(t, queue.(*scheduledWorkQueue[string]).work) |
A sibling case that calls Forget("obj") then Add("obj", time.Minute) while the first callback is held on release would pin the other half of the ownership contract, but that is optional.
[Claude Fable 5.1]
There was a problem hiding this comment.
Added the drain assertion. Confirmed the gap first: with the ownership check disabled, the test fails with "Should be empty".
|
|
||
| type workEntry struct { | ||
| cancel func() | ||
| token uint64 |
There was a problem hiding this comment.
Suggestion, not a blocker: pointer identity does the same job as the token and removes token, nextToken and the increment. Store *workEntry in the map, capture the pointer in the closure, and compare s.work[obj] == entry in forgetIfOwned. Each &workEntry{} is a distinct allocation (the struct is not zero-sized), so the comparison is a sound "is this still my entry?" check with no counter to keep consistent under the lock.
While here, the delete(s.work, obj) in Add is dead. The key is reassigned unconditionally a few lines later under the same lock.
I tried this on top of a local rebase: gofmt and go vet clean, go test -race -count=10 ./pkg/scheduler/ passes, and the new test still fails when the ownership check is removed. Net 14 insertions, 21 deletions against this branch.
Sketch
type workEntry struct {
cancel func()
}
// in Add
if entry, ok := s.work[obj]; ok {
entry.cancel()
}
entry := &workEntry{}
entry.cancel = afterFunc(s.clock, duration, func() {
defer s.forgetIfOwned(obj, entry)
s.processFunc(obj)
})
s.work[obj] = entry
// forgetIfOwned removes the work entry for obj only if it is still the
// entry that the fired timer installed. A newer Add for the same obj
// replaces the entry, and a fired timer's cleanup must not remove it.
func (s *scheduledWorkQueue[T]) forgetIfOwned(obj T, entry *workEntry) {
s.workLock.Lock()
defer s.workLock.Unlock()
if s.work[obj] == entry {
delete(s.work, obj)
}
}[Claude Fable 5.1]
There was a problem hiding this comment.
Adopted the pointer-identity design from your sketch, including dropping the dead delete in Add.
| defer s.workLock.Unlock() | ||
|
|
||
| if entry, ok := s.work[obj]; ok && entry.token == token { | ||
| entry.cancel() |
There was a problem hiding this comment.
entry.cancel() is a no-op here and can go. The token only matches the entry installed by the timer that is running this cleanup, so that timer has already fired, and afterFunc's goroutine runs defer cancel() as soon as f() returns:
cert-manager/pkg/scheduler/scheduler.go
Lines 39 to 51 in a21ed0b
Keeping it makes the function read as if it could cancel a live timer, which is the confusion #9269 came from. A bare delete(s.work, obj) says what this branch does, and the doc comment can then say "removes" rather than "cancels and removes".
[Claude Fable 5.1]
There was a problem hiding this comment.
Removed the no-op cancel; forgetIfOwned now only deletes.
| queue.Add("obj", time.Minute) // replaces the entry | ||
| close(release) | ||
|
|
||
| synctest.Wait() |
There was a problem hiding this comment.
This synctest.Wait() is redundant. time.Sleep inside a bubble only advances the fake clock once every other goroutine in the bubble is durably blocked, so the callback released on the previous line must finish before the sleep on the next line can return.
I removed it and the test stays green under -race -count=50, and it still fails against the old Forget cleanup. Keeping only the two load-bearing Waits (after the first sleep, and before the assert) makes it clearer what each one is waiting for.
| synctest.Wait() |
[Claude Fable 5.1]
There was a problem hiding this comment.
Removed the redundant Wait; only the two load-bearing ones remain.
ebe7307 to
785e61e
Compare
| synctest.Wait() // timer fired; callback is now blocked on release | ||
|
|
||
| queue.Add("obj", time.Minute) // replaces the entry | ||
| close(release) |
There was a problem hiding this comment.
Non-blocking. The test now catches the old Forget cleanup and a guard that never matches, but not a guard that always matches. If forgetIfOwned deleted unconditionally, the test would still pass: the newer timer still fires from its own goroutine, so the call count is two, and the map ends up empty. In production that variant leaves the newer timer live but unreachable, so Forget cannot cancel it and a later Add starts a duplicate.
Two lines after close(release) pin that half of the contract. The synctest.Wait() here becomes load-bearing again, which corrects my earlier comment: it was redundant only because nothing observed the state between the two callbacks.
| close(release) | |
| close(release) | |
| synctest.Wait() // the first callback's cleanup has run | |
| assert.Len(t, queue.(*scheduledWorkQueue[string]).work, 1) |
Evidence at 785e61e
Mutation of forgetIfOwned |
Current test | With this assertion |
|---|---|---|
defer s.Forget(obj) (old behaviour) |
fails | fails |
if false { (never matches) |
fails, "Should be empty" | fails |
if true { (always matches) |
passes | fails, "should have 1 item(s), but has 0" |
Unmutated code with the assertion: go test -race -count=20 ./pkg/scheduler/ passes.
[Claude Fable 5.1]
There was a problem hiding this comment.
Added the assertion after close(release). Verified all three mutations against the table: old Forget fails, never-matches fails on the drain check, and always-matches now fails with "should have 1 item(s), but has 0". You are right that the Wait became load-bearing again once the intermediate state is observed.
|
/ok-to-test |
…led (cert-manager#9269) The timer callback ran `defer s.Forget(obj)`, which cancels whatever entry is in the work map at that moment, not necessarily the timer that just fired. A reschedule from the reconcile loop (or a concurrent Add) in the window between processFunc returning and the deferred Forget taking the lock was silently cancelled and deleted, so the rescheduled poll was lost until the next informer resync. Store *workEntry pointers in the map and have the fired timer cleanup remove its entry only while the map still points at it (forgetIfOwned), leaving a newer timer for the same object untouched. Add a synctest regression test that holds the callback open while a newer Add replaces the entry; it fails against the old cleanup and also asserts the map drains once both timers have fired. Fixes cert-manager#9269 Signed-off-by: Shashank Varma <[email protected]>
785e61e to
9615665
Compare
|
/retest The e2e-v1-36 job died while building the acmesolver container image (docker buildx gRPC connection canceled, exit 130) before any test ran, so this looks like infra flake tracked under #4950. make-verify, make-test and the e2e upgrade job all passed. |
wallrj
left a comment
There was a problem hiding this comment.
/lgtm
/approve
Thank you. This fixes #9269 and every review comment is addressed.
I verified 9615665 locally: go test -race -count=20 ./pkg/scheduler/ passes, go vet and gofmt are clean, and all three mutations of forgetIfOwned (old Forget cleanup, never matches, always matches) fail the new test. The remaining e2e job failed on an image build infrastructure error before any test ran, so tide will merge once the retest is green.
[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 for v1.21.2 (tracker: #9237). This is a small, self-contained bug fix in [Claude Fable 5.1] |
|
@wallrj: new pull request created: #9312 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. |
|
@shashankvarma499 This change has been included in v1.21.2, which is now published. If you are able to install the release and verify that the change works as expected in your environment, that would be much appreciated. Thank you for the contribution. |
What
The timer callback cleaned itself up with a deferred
Forget(obj), which cancels whatever entry is in the work map at the time it runs, not necessarily the timer that just fired. All three callers reschedule from their reconcile loop, and a concurrentAdd(obj, d2)landing betweenprocessFuncreturning and the deferredForgettaking the lock had its timer cancelled and deleted, silently losing the reschedule until the next informer resync.Fix
workstores*workEntrypointers; each timer captures its own entry.forgetIfOwned, which removes the map entry only while the map still points at that timer's entry. A newerAddfor the same object replaces the pointer, so the older timer's cleanup leaves it untouched.Add's replacement branch no longer deletes the key (it is reassigned under the same lock).Forgetsemantics are unchanged; the guarantee is documented on the exportedAdddocs.Test
TestAddDuringCallbackKeepsNewerTimer(synctest) holds the first callback open while a newerAddreplaces the entry. It asserts the map still holds the newer entry after the first callback's cleanup, and that it is empty once both timers have fired. It fails against the oldForgetcleanup (dropped reschedule), against an ownership check that never matches (map leak), and against one that always matches (unreachable live timer).Verification
go test -race ./pkg/scheduler/ -count=10passes (whole package).gofmtandgo vetclean.Rebased on master after #9267.
Fixes #9269