Skip to content

feat(linters): add contextcancelnotdeferred analyzer#35304

Merged
pelikhan merged 2 commits into
mainfrom
copilot/feat-contextcancelnotdeferred-linter
May 27, 2026
Merged

feat(linters): add contextcancelnotdeferred analyzer#35304
pelikhan merged 2 commits into
mainfrom
copilot/feat-contextcancelnotdeferred-linter

Conversation

Copilot AI commented May 27, 2026

Copy link
Copy Markdown
Contributor

Adds a new custom Go analyzer to catch context.WithCancel/WithTimeout/WithDeadline cancel funcs that are invoked directly instead of deferred. This targets context/goroutine leak risk when early returns or panics occur between context creation and cancel invocation.

  • Analyzer implementation

    • Added pkg/linters/contextcancelnotdeferred/contextcancelnotdeferred.go.
    • Tracks cancel funcs returned from context.WithCancel, context.WithTimeout, and context.WithDeadline.
    • Reports when cancel() is called directly and no corresponding defer cancel() exists in the same function.
    • Mirrors existing linter conventions:
      • skips test files via filecheck.IsTestFile
      • does not descend into function literals (closure scope isolation)
      • handles reassignment/shadowing via types.Object-based tracking
  • Linter registration

    • Registered contextcancelnotdeferred.Analyzer in cmd/linters/main.go so it runs in the multichecker binary.
  • Analyzer tests and fixtures

    • Added contextcancelnotdeferred_test.go with analysistest.
    • Added fixtures under testdata/src/contextcancelnotdeferred/ covering:
      • flagged direct cancel calls
      • valid deferred cancel patterns
      • closure behavior
      • reassignment and blank identifier cases

Example pattern now flagged:

ctx, cancel := context.WithTimeout(parent, 5*time.Second)
result, err := doWork(ctx)
cancel() // should be defer cancel()

Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com>
Copilot AI changed the title [WIP] Add contextcancelnotdeferred linter feat(linters): add contextcancelnotdeferred analyzer May 27, 2026
Copilot AI requested a review from gh-aw-bot May 27, 2026 21:29
@pelikhan pelikhan marked this pull request as ready for review May 27, 2026 21:30
Copilot AI review requested due to automatic review settings May 27, 2026 21:30
@pelikhan pelikhan merged commit 00ce515 into main May 27, 2026
1 check failed
@pelikhan pelikhan deleted the copilot/feat-contextcancelnotdeferred-linter branch May 27, 2026 21:32
Copilot AI removed the request for review from Copilot May 27, 2026 21:52
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[linter-miner] feat(linters): add contextcancelnotdeferred linter

3 participants