Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🩹 Fix: goroutine leakage #3306

Conversation

JIeJaitt
Copy link
Contributor

@JIeJaitt JIeJaitt commented Feb 12, 2025

Description

As mentioned in the #3304 , I modified the channel of the Test function to use a buffered channel, and added a unit test to verify goroutine leakage with and without a timeout.

Fixes #3304

Changes introduced

List the new features or adjustments introduced in this pull request. Provide details on benchmarks, documentation updates, changelog entries, and if applicable, the migration guide.

  • Benchmarks: Describe any performance benchmarks and improvements related to the changes.
  • Documentation Update: Detail the updates made to the documentation and links to the changed files.
  • Changelog/What's New: Include a summary of the additions for the upcoming release notes.
  • Migration Guide: If necessary, provide a guide or steps for users to migrate their existing code to accommodate these changes.
  • API Alignment with Express: Explain how the changes align with the Express API.
  • API Longevity: Discuss the steps taken to ensure that the new or updated APIs are consistent and not prone to breaking changes.
  • Examples: Provide examples demonstrating the new features or changes in action.

Type of change

Please delete options that are not relevant.

  • Performance improvement (non-breaking change which improves efficiency)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

@JIeJaitt JIeJaitt requested a review from a team as a code owner February 12, 2025 07:38
@JIeJaitt JIeJaitt requested review from gaby, sixcolors, ReneWerner87 and efectn and removed request for a team February 12, 2025 07:38
Copy link
Contributor

coderabbitai bot commented Feb 12, 2025

Walkthrough

This pull request modifies the error channel in the Test method of the App struct by switching from a non-buffered channel to a buffered channel with a capacity of one. In addition, it introduces a new test function in app_test.go to compare goroutine counts for detecting potential leaks under various handler scenarios. No changes were made to the exported or public entities.

Changes

File(s) Summary
app.go Modified the Test method of the App struct to use a buffered error channel with a capacity of one, preventing blocking during error sending.
app_test.go Added Test_App_Test_Goroutine_Leak_Compare, a new test function that sends multiple requests and compares initial and final goroutine counts to detect leaks.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant A as App.Test
    participant E as Error Channel
    C->>A: Invoke Test connection
    A->>E: Send error to buffered channel
    E-->>A: Return error without blocking
    A->>C: Return response or error
Loading
sequenceDiagram
    participant T as Test Function
    participant A as App Instance
    participant H as Handler
    participant G as Goroutine Monitor

    T->>A: Create new app instance
    T->>G: Record initial goroutine count
    T->>A: Setup GET route with handler H
    T->>A: Send multiple requests
    A->>H: Handle incoming request in goroutine
    T->>G: Record final goroutine count
    T->>T: Assert leak comparison based on expected outcome
Loading

Possibly related PRs

Suggested labels

☢️ Bug, v3

Suggested reviewers

  • sixcolors
  • gaby
  • ReneWerner87
  • efectn

Poem

Hop, skip, and code we go,
A buffered channel lets errors flow.
No more blocked or waiting in line,
Goroutine leaks we detect just fine.
With tests and checks all in a row,
A rabbit cheers—let the improvements show!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented Feb 12, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.06%. Comparing base (a61c8b3) to head (476e7d4).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3306      +/-   ##
==========================================
- Coverage   84.08%   84.06%   -0.03%     
==========================================
  Files         116      116              
  Lines       11551    11551              
==========================================
- Hits         9713     9710       -3     
- Misses       1405     1407       +2     
- Partials      433      434       +1     
Flag Coverage Δ
unittests 84.06% <100.00%> (-0.03%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (4)
app_test.go (3)

60-62: Use a consistent naming convention for clarity.
“Test_App_Test_Goroutine_Leak_Compare” is descriptive but a bit verbose. Consider a name like “TestGoroutineLeaks” for ease of reference.


63-69: Consider adding clarifying comments for each field in the test case struct.
Having brief comments for fields like sleepTime and expectLeak helps future maintainers quickly grasp their usage in test logic.


121-129: Provide explicit synchronization or forced GC for more reliable measurements.
Relying solely on time.Sleep and runtime.NumGoroutine() can be brittle if other goroutines run concurrently (e.g., from parallel tests). Consider more robust signaling (like wait groups) or forcing runtime.GC() to yield more stable results.

app.go (1)

997-1009: Verify success path handling around the buffered channel.
Using a buffered channel helps avoid blocking, but note the extra complexity in the deferred function with returned. Consider simplifying by returning the error immediately if feasible, or rename returned to something more specific (like serveConnCompleted).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a61c8b3 and 476e7d4.

📒 Files selected for processing (2)
  • app.go (1 hunks)
  • app_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: unit (1.23.x, macos-latest)
  • GitHub Check: unit (1.23.x, windows-latest)
  • GitHub Check: repeated
  • GitHub Check: Compare
  • GitHub Check: Analyse
🔇 Additional comments (1)
app_test.go (1)

91-93: Potential parallel test flakiness.
Running both the main loop and each subtest with t.Parallel() can make runtime goroutine counts unpredictable. This might cause intermittent failures in environments with many parallel tests.

Comment on lines +130 to +137
if tc.expectLeak {
// before fix: If blocking exists, leaked goroutines should be at least equal to request count
// after fix: If no blocking exists, leaked goroutines should be less than request count
if leakedGoroutines >= numRequests {
t.Errorf("[%s] Expected at least %d leaked goroutines, but got %d",
tc.name, numRequests, leakedGoroutines)
}
} else if leakedGoroutines >= numRequests { // If no blocking exists, leaked goroutines should be less than request count
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Reevaluate the leak checking logic.
The condition and error message seem inverted. If tc.expectLeak == true, requiring “at least N leaked goroutines,” you might want to flag an error when leakedGoroutines < numRequests instead of >= numRequests. Currently, it flags an error if the condition is satisfied, which contradicts the comment.

Suggest correcting as follows (example flip of condition):

-if leakedGoroutines >= numRequests {
-    t.Errorf("[%s] Expected at least %d leaked goroutines, but got %d", ...)
+if leakedGoroutines < numRequests {
+    t.Errorf("[%s] Expected at least %d leaked goroutines, but got %d", ...)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if tc.expectLeak {
// before fix: If blocking exists, leaked goroutines should be at least equal to request count
// after fix: If no blocking exists, leaked goroutines should be less than request count
if leakedGoroutines >= numRequests {
t.Errorf("[%s] Expected at least %d leaked goroutines, but got %d",
tc.name, numRequests, leakedGoroutines)
}
} else if leakedGoroutines >= numRequests { // If no blocking exists, leaked goroutines should be less than request count
if tc.expectLeak {
// before fix: If blocking exists, leaked goroutines should be at least equal to request count
// after fix: If no blocking exists, leaked goroutines should be less than request count
if leakedGoroutines < numRequests {
t.Errorf("[%s] Expected at least %d leaked goroutines, but got %d",
tc.name, numRequests, leakedGoroutines)
}
} else if leakedGoroutines >= numRequests { // If no blocking exists, leaked goroutines should be less than request count

@ReneWerner87 ReneWerner87 added this to the v3 milestone Feb 12, 2025
@ReneWerner87 ReneWerner87 merged commit b0bc32b into gofiber:main Feb 13, 2025
14 of 15 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
Status: Done
Development

Successfully merging this pull request may close these issues.

[Bug] Possible Blocking Channel Issue in app.go
3 participants