Skip to content
Latchkey

go vet "the cancel function is not used on all paths" in CI

The lostcancel analyzer detects a cancel function returned by context.WithCancel, WithTimeout, or WithDeadline that is dropped or not called on some path, which leaks the context.

What this error means

go vet reports "the cancel function is not used on all paths (possible context leak)" or "the cancel function returned by context.WithTimeout should be called, not discarded".

go vet
./fetch.go:15:2: the cancel function returned by context.WithTimeout should be called, not discarded, to avoid a context leak

Common causes

The cancel function is assigned to _ or ignored

Discarding cancel (or never calling it) leaves the derived context and its timer alive until the parent is cancelled.

An early return skips the cancel call

A path returns before reaching cancel(), so on that branch the context is never cancelled.

How to fix it

Defer the cancel right after creating the context

  1. Capture the cancel function returned alongside the context.
  2. Call defer cancel() immediately so every path releases it.
  3. Re-run go vet ./....
fetch.go
ctx, cancel := context.WithTimeout(parent, 5*time.Second)
defer cancel()

Call cancel explicitly on early-return paths

If you cannot defer, ensure every branch that returns calls cancel() first.

How to prevent it

  • Always defer cancel() on the line after creating the context.
  • Run go vet ./... in CI so leaks are caught.
  • Never assign the cancel function to _.

Related guides

Tired of flaky CI? Latchkey auto-heals failed jobs and retries them for you. Start free →