Skip to content

go.uncancelled_context

Stability Medium

Detects context.WithCancel() and context.WithTimeout() without calling the cancel function, leaking resources.

Uncancelled contexts cause:

  • Memory leaks — Context goroutines never terminate
  • Resource exhaustion — Over time, leaks accumulate
  • Timer leaks — WithTimeout/WithDeadline leak timers
  • Goroutine leaks — Background goroutines never stop
// ❌ Before (cancel never called)
func process() {
ctx, _ := context.WithTimeout(context.Background(), time.Second)
doWork(ctx)
// Timer goroutine leaked!
}
// ✅ After (cancel called)
func process() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel() // Always call cancel!
doWork(ctx)
}
  • context.WithCancel() with unused cancel func
  • context.WithTimeout() without defer cancel
  • context.WithDeadline() without cleanup
  • Ignored cancel functions (_)

Unfault adds defer cancel():

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()