The cancel function of a derived context is not called on a path to a return
What it finds
``go ctx, cancel := context.WithTimeout(ctx, time.Second) if cached { return value // cancel is never called } defer cancel() `` A derived context holds a timer and a place in its parent until its cancel function runs. On a path that returns without calling it, both stay until the parent ends, which for a long-lived parent is a leak that grows with every call. Deferring the cancel right after the context is made covers every path.
The rule follows each function through the shared IR from a call of WithCancel, WithTimeout, WithDeadline or their Cause forms of context to every return. A path ends where the cancel function is called, deferred, returned, stored, passed to a function or captured by a function literal. Functions with constructs the lowering does not understand are skipped. A cancel function dropped with _ is the subject of lost-cancel.
From the rule's source, cancel_not_called_on_path.rs.
package p import ( "context" "time") func fetch(ctx context.Context, cached bool) error { ctx, cancel := context.WithTimeout(ctx, time.Second) if cached { return niltx0 reports: cancel is not called before the function returns here } defer cancel() return work(ctx)} func both(ctx context.Context) error { ctx, cancel := context.WithCancel(ctx) defer cancel() return work(ctx)} func handed(ctx context.Context) (context.Context, context.CancelFunc) { ctx, cancel := context.WithCancel(ctx) return ctx, cancel} func work(context.Context) error { return nil } Turn it on, off or suppress it
The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/go:cancel-not-called-on-path" = "warning"To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:
// tx0: ignore[tx0/go:cancel-not-called-on-path] reason="..."tx0 explain tx0/go:cancel-not-called-on-path shows the same in the terminal. Found a false positive? Report it.