Skip to content

Conversation

@gartnera
Copy link
Contributor

@gartnera gartnera commented Nov 15, 2024

In the zetaclient logs, you'll see spam of thousands of addresses and OOM crashes

Add unit test to detect this scenario. master fails like this:

discovery_test.go:89:
        	Error Trace:	/Users/alex/workspace/github.com/zeta-chain/go-tss/p2p/discovery_test.go:89
        	Error:      	"5034" is not less than or equal to "4"
        	Test:       	TestDiscovery
        	Messages:   	16Uiu2HAm2BvdrtKF4TQQ51gajCZhYnqkUi99NZ2eCL25dXUxeEKA has more than 4 addresses (5034)?

slices.Compare apparently doesn't actually work on multiaddr.Multiaddr apparently. So the addresses are appended until the process runs out of memory.

Summary by CodeRabbit

  • Bug Fixes

    • Improved address checking logic for peer discovery to ensure accurate tracking of known addresses.
  • Tests

    • Enhanced the TestDiscovery function with additional assertions to verify the state of known peers and enforce limits on the number of addresses per peer.

@gartnera gartnera requested a review from a team November 15, 2024 06:48
@coderabbitai
Copy link

coderabbitai bot commented Nov 15, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The changes in this pull request involve modifications to the addPeer method within the PeerDiscovery struct in p2p/discovery.go, where the method now utilizes multiaddr.Contains instead of slices.Contains for address verification. Additionally, in the p2p/discovery_test.go file, the TestDiscovery function has been enhanced with new assertions to validate the state of the knownPeers collection, ensuring that it contains the expected number of peers and that no peer exceeds the defined address limit.

Changes

File Change Summary
p2p/discovery.go Modified addPeer method to use multiaddr.Contains for checking existing addresses in oldPinfo.Addrs.
p2p/discovery_test.go Added assertions in TestDiscovery to verify that knownPeers has a length of 3 and each peer has no more than 4 addresses.

Sequence Diagram(s)

sequenceDiagram
    participant PeerDiscovery
    participant Multiaddr
    participant KnownPeers

    PeerDiscovery->>Multiaddr: Check if address exists
    Multiaddr-->>PeerDiscovery: Return result
    alt Address does not exist
        PeerDiscovery->>KnownPeers: Add address to known peers
    else Address exists
        PeerDiscovery->>KnownPeers: Skip adding address
    end
Loading

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint

level=warning msg="[config_reader] The configuration option linters.errcheck.ignore is deprecated, please use linters.errcheck.exclude-functions."
level=warning msg="The linter 'golint' is deprecated (since v1.41.0) due to: The repository of the linter has been archived by the owner. Replaced by revive."
level=warning msg="The linter 'deadcode' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter. Replaced by unused."
level=error msg="[linters_context] deadcode: This linter is fully inactivated: it will not produce any reports."
level=error msg="[linters_context] golint: This linter is fully inactivated: it will not produce any reports."


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between ab13fd6 and 184b601.

📒 Files selected for processing (1)
  • p2p/discovery_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • p2p/discovery_test.go

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 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

@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: 2

🧹 Outside diff range and nitpick comments (2)
p2p/discovery_test.go (1)

86-90: Consider strengthening the test assertions

While the new assertions help catch the infinite address leak, there are opportunities to make the test more robust:

  1. The test relies on a 5-second sleep which could be flaky. Consider implementing a retry mechanism with timeout.
  2. The assertion only verifies the count of addresses but not their uniqueness or validity.

Here's a suggested improvement:

- time.Sleep(5 * time.Second)
+ // Helper function to wait for discovery with timeout
+ func waitForDiscovery(t *testing.T, comm *Communication) {
+   start := time.Now()
+   timeout := 10 * time.Second
+   for time.Since(start) < timeout {
+     if len(comm.discovery.knownPeers) == 3 {
+       return
+     }
+     time.Sleep(100 * time.Millisecond)
+   }
+   t.Fatal("Discovery timeout")
+ }
+ 
+ waitForDiscovery(t, comm)
 
 assert.Equal(t, 4, len(comm.host.Peerstore().Peers()))
 assert.Equal(t, 4, len(comm2.host.Peerstore().Peers()))
 assert.Equal(t, 4, len(comm3.host.Peerstore().Peers()))
 assert.Equal(t, 4, len(comm4.host.Peerstore().Peers()))

 assert.Equal(t, 3, len(comm.discovery.knownPeers))
 for peer, knownPeers := range comm.discovery.knownPeers {
-  assert.LessOrEqual(t, len(knownPeers.Addrs), 4, "%s has more than 4 addresses (%d)?", peer.String(), len(knownPeers.Addrs))
+  addrs := knownPeers.Addrs
+  assert.LessOrEqual(t, len(addrs), 4, "%s has more than 4 addresses (%d)?", peer.String(), len(addrs))
+  // Verify address uniqueness
+  seen := make(map[string]bool)
+  for _, addr := range addrs {
+    addrStr := addr.String()
+    assert.False(t, seen[addrStr], "Duplicate address found: %s", addrStr)
+    seen[addrStr] = true
+  }
 }
p2p/discovery.go (1)

Line range hint 1-215: Consider implementing address pruning mechanism

To further prevent address accumulation over time, consider implementing a mechanism to periodically prune old or unreachable addresses. This would add an extra layer of protection against potential memory leaks.

Key considerations for implementation:

  1. Track address last-seen timestamps
  2. Periodically remove addresses that haven't been seen/used
  3. Remove addresses that consistently fail connection attempts
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 12f139f and ab13fd6.

📒 Files selected for processing (2)
  • p2p/discovery.go (1 hunks)
  • p2p/discovery_test.go (1 hunks)

Copy link

@morde08 morde08 left a comment

Choose a reason for hiding this comment

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

LGTM

@gartnera gartnera merged commit 8535262 into master Nov 15, 2024
5 checks passed
@gartnera gartnera deleted the fix-infinite-addresses-leak branch November 15, 2024 16:53
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.

4 participants