馃悰 Fix goroutine leaks in cache Start() methods - #3565
Conversation
The multiNamespaceCache.Start() and delegatingByGVKCache.Start() methods used unbuffered error channels which could cause goroutine leaks when: 1. Multiple caches return errors simultaneously (only first error received) 2. Context is cancelled while goroutines try to send errors Fix by using buffered channels sized to the number of caches, combined with WaitGroup to ensure all goroutines complete before returning. Added goleak-based unit tests to verify no goroutine leaks occur. Signed-off-by: dongjiang <dongjiang1989@126.com>
|
[APPROVALNOTIFIER] This PR is NOT APPROVED This pull-request has been approved by: dongjiang1989 The full list of commands accepted by this bot can be found here. DetailsNeeds approval from an approver in each of these files:Approvers can indicate their approval by writing |
thc1006
left a comment
There was a problem hiding this comment.
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.
The previous fix used buffered channels and WaitGroup, but it introduced a hang issue: when one cache returns an error, healthy caches continue running (their context is not cancelled), causing <-done to block forever. This commit uses errgroup.WithContext() which: 1. Cancels childCtx when any goroutine returns an error 2. Healthy caches observe cancellation and return promptly 3. Wait() returns the first error This fixes the hang while still preventing goroutine leaks. Added new test cases (ErrorWithHealthyChildren) that verify: - Start() returns promptly when one cache errors - Healthy caches observe context cancellation - No goroutine leaks (verified by goleak) Thanks to @thc1006 for the review and suggesting the errgroup approach. Signed-off-by: dongjiang <dongjiang1989@126.com>
a2888f9 to
54185ed
Compare
|
@thc1006 Thanks for the review! Updated to use |
What does this PR do?
This PR fixes goroutine leaks in
multiNamespaceCache.Start()anddelegatingByGVKCache.Start()methods in thepkg/cachepackage.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:Multiple caches return errors simultaneously: The
selectstatement only receives the first error and returns, leaving other goroutines blocked forever onerrs <- errwith no receiver.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
Fix
sync.WaitGroupto track all goroutines