Skip to content

fix(scheduler): keep a newer timer for the same key from being cancelled (#9269) - #9270

Merged
cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
shashankvarma499:scheduler-forget-race-9269
Sep 3, 2026
Merged

cert-manager-prow[bot] merged 1 commit into
cert-manager:masterfrom
shashankvarma499:scheduler-forget-race-9269

Conversation

@shashankvarma499

@shashankvarma499 shashankvarma499 commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

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 concurrent Add(obj, d2) landing between processFunc returning and the deferred Forget taking the lock had its timer cancelled and deleted, silently losing the reschedule until the next informer resync.

Fix

  • work stores *workEntry pointers; each timer captures its own entry.
  • The fired timer's cleanup is forgetIfOwned, which removes the map entry only while the map still points at that timer's entry. A newer Add for 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).
  • Public Forget semantics are unchanged; the guarantee is documented on the exported Add docs.

Test

TestAddDuringCallbackKeepsNewerTimer (synctest) holds the first callback open while a newer Add replaces 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 old Forget cleanup (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=10 passes (whole package).
  • gofmt and go vet clean.

Rebased on master after #9267.

Fixes #9269

Fixed a race in pkg/scheduler where the cleanup of a fired timer could cancel a newer timer scheduled for the same object, silently dropping a rescheduled poll.

@cert-manager-prow cert-manager-prow Bot added release-note Denotes a PR that will be considered when it comes time to generate release notes. dco-signoff: yes Indicates that all commits in the pull request have the valid DCO sign-off message. needs-kind Indicates a PR lacks a `kind/foo` label and requires one. labels Sep 3, 2026
@shashankvarma499

Copy link
Copy Markdown
Contributor Author

/kind bug

@cert-manager-prow cert-manager-prow Bot added the needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. label 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 kind/bug Categorizes issue or PR as related to a bug. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. and removed needs-kind Indicates a PR lacks a `kind/foo` label and requires one. labels Sep 3, 2026
@wallrj
wallrj requested a balanced review from Copilot September 3, 2026 19:54

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 encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

Comment thread pkg/scheduler/scheduler.go Outdated
work map[T]func()
work map[T]workEntry
workLock sync.Mutex
nextToken uint64

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

type scheduledWorkQueue[T comparable] struct {
processFunc ProcessFunc[T]
clock clock.Clock
work map[T]func()
workLock sync.Mutex
}

[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.

Rebased on master after #9267, and the stale TestAdd note is gone from the description.

Comment thread pkg/scheduler/scheduler.go Outdated
// 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.

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

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.

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)

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

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

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.

Added the drain assertion. Confirmed the gap first: with the ownership check disabled, the test fails with "Should be empty".

Comment thread pkg/scheduler/scheduler.go Outdated

type workEntry struct {
cancel func()
token uint64

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.

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]

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.

Adopted the pointer-identity design from your sketch, including dropping the dead delete in Add.

Comment thread pkg/scheduler/scheduler.go Outdated
defer s.workLock.Unlock()

if entry, ok := s.work[obj]; ok && entry.token == token {
entry.cancel()

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.

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:

go func() {
defer cancel()
select {
case <-t.C():
// We don't need to check whether the channel has returned a zero
// value since t.C is never closed as per the timer.Stop
// documentation.
f()
case <-cancelCh:
return
}
}()

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]

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.

Removed the no-op cancel; forgetIfOwned now only deletes.

Comment thread pkg/scheduler/scheduler_test.go Outdated
queue.Add("obj", time.Minute) // replaces the entry
close(release)

synctest.Wait()

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

Suggested change
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.

Removed the redundant Wait; only the two load-bearing ones remain.

synctest.Wait() // timer fired; callback is now blocked on release

queue.Add("obj", time.Minute) // replaces the entry
close(release)

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.

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.

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

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.

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.

@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
…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]>
@shashankvarma499
shashankvarma499 force-pushed the scheduler-forget-race-9269 branch from 785e61e to 9615665 Compare September 3, 2026 21:21
@shashankvarma499

Copy link
Copy Markdown
Contributor Author

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

@wallrj wallrj added the tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges. label Sep 3, 2026
@cert-manager-prow cert-manager-prow Bot added the lgtm Indicates that a PR is ready to be merged. label Sep 3, 2026
@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 the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Sep 3, 2026
@cert-manager-prow
cert-manager-prow Bot merged commit a26ed42 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 for v1.21.2 (tracker: #9237). This is a small, self-contained bug fix in pkg/scheduler: the cleanup of a fired timer could cancel a newer timer for the same key and silently drop a rescheduled poll. That affects certificate renewal scheduling on v1.21.x, so it is worth carrying to the patch release. It applies cleanly on top of #9267 and the package tests pass on release-1.21 with -race.

[Claude Fable 5.1]

@cert-manager-bot

Copy link
Copy Markdown
Contributor

@wallrj: new pull request created: #9312

Details

In response to this:

/cherry-pick release-1.21

Backporting for v1.21.2 (tracker: #9237). This is a small, self-contained bug fix in pkg/scheduler: the cleanup of a fired timer could cancel a newer timer for the same key and silently drop a rescheduled poll. That affects certificate renewal scheduling on v1.21.x, so it is worth carrying to the patch release. It applies cleanly on top of #9267 and the package tests pass on release-1.21 with -race.

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

wallrj commented Sep 11, 2026

Copy link
Copy Markdown
Member

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

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 Denotes a PR that will be considered when it comes time to generate release notes. size/M Denotes a PR that changes 30-99 lines, ignoring generated files. tide/merge-method-squash Denotes a PR that should be squashed by tide when it merges.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

scheduler: deferred Forget in timer callback can cancel a newer timer for the same key

4 participants