Skip to content

馃悰 Fix goroutine leaks in cache Start() methods - #3565

Merged
kubernetes-prow[bot] merged 1 commit into
kubernetes-sigs:mainfrom
dongjiang1989:fix-leak
Sep 3, 2026
Merged

馃悰 Fix goroutine leaks in cache Start() methods#3565
kubernetes-prow[bot] merged 1 commit into
kubernetes-sigs:mainfrom
dongjiang1989:fix-leak

Conversation

@dongjiang1989

@dongjiang1989 dongjiang1989 commented Aug 3, 2026

Copy link
Copy Markdown
Member

What does this PR do?

This PR fixes goroutine leaks in multiNamespaceCache.Start() and delegatingByGVKCache.Start() methods in the pkg/cache package.

Why do we need it?

Problem

Both Start() methods used unbuffered error channels (errs := make(chan error)) to collect errors from goroutines. This caused goroutine leaks in two scenarios:

  1. Multiple caches return errors simultaneously: The select statement only receives the first error and returns, leaving other goroutines blocked forever on errs <- err with no receiver.

  2. Context cancelled while goroutines try to send errors: When ctx.Done() triggers first, the function returns immediately. Any subsequent error sends from goroutines will block forever.

Example

// Original problematic code
errs := make(chan error)  // unbuffered
for _, cache := range caches {
    go func() {
        if err := cache.Start(ctx); err != nil {
            errs <- err  // blocks forever if no receiver!
        }
    }()
}
select {
case err := <-errs:
    return err  // only receives ONE error, others leak
case <-ctx.Done():
    return nil  // returns immediately, senders leak
}

Fix

  • Use buffered channels sized to the number of caches
  • Use sync.WaitGroup to track all goroutines
  • Wait for all goroutines to complete before returning
// Fixed code
errs := make(chan error, len(caches))  // buffered
var wg sync.WaitGroup
for _, cache := range caches {
    wg.Go(func() {
        if err := cache.Start(ctx); err != nil {
            errs <- err  // never blocks
        }
    })
}
done := make(chan struct{})
go func() { wg.Wait(); close(done) }()
// ... wait for all goroutines to complete

@kubernetes-prow kubernetes-prow Bot added cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. size/L Denotes a PR that changes 100-499 lines, ignoring generated files. labels Aug 3, 2026

@thc1006 thc1006 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

TLDR: the leak is real and worth fixing, but waiting on done after the first error hangs Start whenever any sibling cache is healthy, which is the ordinary case. I ran it against this branch and against main, results below. The existing test only passes because its parent context expires on its own after 50ms.

A healthy Cache.Start runs until its context is cancelled. In the case err := <-errs branch this waits for every other Start goroutine to return, and nothing cancels their context, since the children are handed the same ctx the parent is still using. So done never closes and Start never returns. Both files have this shape.

One child returning a sentinel error, one child on <-ctx.Done(), parent context left alive:

Start returns healthy child sees cancellation
main promptly, with the error no, it keeps running, which is the leak this PR is about
this branch never, 5s timeout in my test n/a
errgroup.WithContext promptly, with the error yes

So the leak is traded for a hang, and only the third row has both properties.

On the tests. TestMultiNamespaceCacheStart_GoroutineLeak_ContextCancelWithError is nearly the right shape already, a slow erroring cache alongside two on <-ctx.Done(), but it builds the parent with context.WithTimeout(t.Context(), 50*time.Millisecond). The timeout fires, the healthy children return, and done closes. Swapping that one line for context.WithCancel and asserting Start returns is enough to turn it red:

NOTIMEOUT Start never returned once the parent context stopped expiring on its own
--- FAIL: TestMultiNamespaceCacheStart_GoroutineLeak_ContextCancelWithError (3.00s)

That matters because a manager's context lives for the process rather than 50ms, so production looks like the WithCancel version.

What worked for me in both files:

group, childCtx := errgroup.WithContext(ctx)
for idx := range allCaches {
	cache := allCaches[idx]
	group.Go(func() error {
		return cache.Start(childCtx)
	})
}
return group.Wait()

The first error is kept, childCtx is cancelled, the healthy children return from their own <-ctx.Done(), and Wait gives back the first error. The buffered channel and the done goroutine both go away with it, so the leak stays fixed. One detail worth deciding: on the plain ctx.Done() path the group returns context.Canceled, where the current code returns nil, so you may want to keep that mapping.

Worth adding the shape that is missing from the suite either way: one cache returning an error immediately, another blocking on <-ctx.Done(), a parent context nobody cancels, asserting the parent returns the sentinel promptly and the blocking child observes cancellation. That case fails on this branch and on main, for different reasons, and passes with the group.

This review was written in part with the assistance of generative AI. Bcuz my English might be sucks.

Comment thread pkg/cache/delegating_by_gvk_cache.go Outdated
Comment thread pkg/cache/multi_namespace_cache.go Outdated
@dongjiang1989

Copy link
Copy Markdown
Member Author

@thc1006 Thanks for the review!

Updated to use errgroup.WithContext() as suggested. Added tests with context.WithCancel to verify healthy children are cancelled and Start() returns promptly.

Comment thread pkg/cache/goroutine_leak_test.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
dongjiang1989 added a commit to dongjiang1989/controller-runtime that referenced this pull request Sep 1, 2026
Address alvaroaleman's review comments on PR kubernetes-sigs#3565:

1. Simplify mockCache by embedding Cache interface (remove 7 boilerplate methods)
2. Replace goleak + time.Sleep with testing/synctest
3. Use gomega assertions (project standard)
4. Check errors properly with MatchError
5. Remove ErrorWithHealthyChildren tests (trust errgroup)
6. Add t.Parallel() to all tests

Result: 375 lines -> 150 lines (60% reduction)

Signed-off-by: dongjiang <dongjiang1989@126.com>
Signed-off-by: dongjiang1989 <dongjiang1989@126.com>
@dongjiang1989

Copy link
Copy Markdown
Member Author

Thanks @alvaroaleman
Please re-check it. thanks

@sbueringer

Copy link
Copy Markdown
Member

/assign
(also want to take a look before merge)

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

Looks good, just the point about ignoreContextCanceled, lets wait for Stefans take there

Comment thread pkg/cache/multi_namespace_cache.go Outdated
Comment thread pkg/cache/multi_namespace_cache.go Outdated
Comment thread pkg/cache/goroutine_leak_test.go Outdated
- Use errgroup.WithContext() in multiNamespaceCache.Start() and
  delegatingByGVKCache.Start() to properly propagate cancellation
  to child goroutines and avoid goroutine leaks.
- Fix ignoreContextCanceled to only ignore context.Canceled errors
  (not all errors when context happens to be cancelled).
- Add tests for Start() behavior using synctest.

@alvaroaleman alvaroaleman 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, leaving on hold so stefan can have a look
/hold

@kubernetes-prow kubernetes-prow Bot added the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Sep 3, 2026
@kubernetes-prow kubernetes-prow Bot added the lgtm "Looks good to me", indicates that a PR is ready to be merged. label Sep 3, 2026
@kubernetes-prow

Copy link
Copy Markdown
Contributor

LGTM label has been added.

DetailsGit tree hash: 79d08313e2ea39643d436524fafa06da3a03580a

@kubernetes-prow kubernetes-prow Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Sep 3, 2026
@sbueringer

Copy link
Copy Markdown
Member

Thx!

/lgtm
/approve
/hold cancel

@kubernetes-prow kubernetes-prow Bot removed the do-not-merge/hold Indicates that a PR should not merge because someone has issued a /hold command. label Sep 3, 2026
@kubernetes-prow

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: alvaroaleman, dongjiang1989, sbueringer

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:
  • OWNERS [alvaroaleman,sbueringer]

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

@kubernetes-prow
kubernetes-prow Bot merged commit 0cc1315 into kubernetes-sigs:main Sep 3, 2026
11 checks passed
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. cncf-cla: yes Indicates the PR's author has signed the CNCF CLA. lgtm "Looks good to me", indicates that a PR is ready to be merged. 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.

4 participants