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

test(prover): Use separate ports when running 2 provers in test #164

Merged
merged 1 commit into from
Dec 5, 2024

Conversation

jns-ps
Copy link
Contributor

@jns-ps jns-ps commented Dec 5, 2024

Summary by CodeRabbit

  • New Features

    • The web server now binds to an ephemeral port, allowing for dynamic port assignment at runtime.
  • Bug Fixes

    • Adjusted the default port configuration for improved flexibility.

@jns-ps jns-ps requested a review from distractedm1nd December 5, 2024 07:35
@jns-ps jns-ps self-assigned this Dec 5, 2024
Copy link
Contributor

coderabbitai bot commented Dec 5, 2024

Walkthrough

The changes involve a modification to the WebServerConfig struct in the webserver.rs file. The default value of the port field has been updated from 50524 to 0, enabling the web server to bind to an ephemeral port. This allows the operating system to dynamically assign an available port during runtime. No other modifications to the logic, error handling, or control flow have been made.

Changes

File Path Change Summary
crates/node_types/prover/src/webserver.rs Updated default value of port in WebServerConfig from 50524 to 0.

Poem

In the land of code where rabbits play,
A port was changed, hip-hip-hooray!
From five-oh-five to zero it leapt,
Now the server's secrets are adept.
With ports that dance and hop around,
Our web's alive, joyfully unbound! 🐇✨


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

🧹 Outside diff range and nitpick comments (2)
crates/node_types/prover/src/prover/tests.rs (2)

205-208: Consider making the port configuration more robust

The current approach of incrementing the port by 1 works but could be improved:

  1. Consider using a port allocation utility to ensure the chosen port is available
  2. Add cleanup to ensure ports are released after test completion
  3. Consider making the port difference configurable or using a random available port

Here's a suggested improvement:

-    let mut cfg2 = cfg;
-    cfg2.webserver.port += 1;
+    let mut cfg2 = cfg;
+    cfg2.webserver.port = get_available_port().expect("Failed to get available port");
+
+    // Ensure cleanup after test
+    let _cleanup = TestCleanup::new(cfg2.webserver.port);

// Add these utility implementations somewhere in the test module:
fn get_available_port() -> std::io::Result<u16> {
    let socket = std::net::TcpListener::bind("127.0.0.1:0")?;
    Ok(socket.local_addr()?.port())
}

struct TestCleanup {
    port: u16,
}

impl TestCleanup {
    fn new(port: u16) -> Self {
        Self { port }
    }
}

impl Drop for TestCleanup {
    fn drop(&mut self) {
        // Add any necessary cleanup for the port
    }
}

Line range hint 208-214: Improve test robustness with proper task handling

The test spawns async tasks but doesn't handle their cleanup or potential timeouts:

  1. Consider using JoinHandle to properly manage spawned tasks
  2. Add timeout handling for the assertions
  3. Ensure proper cleanup of resources

Here's a suggested improvement:

-    let runner = prover2.clone();
-    spawn(async move { runner.run().await.unwrap() });
-    let epoch = prover2.clone().db.get_epoch().unwrap();
-    assert_eq!(epoch, 4);
-    assert_eq!(
-        prover.get_commitment().await.unwrap(),
-        prover2.get_commitment().await.unwrap()
-    );
+    let runner = prover2.clone();
+    let handle = spawn(async move { runner.run().await.unwrap() });
+    
+    // Add timeout for the assertions
+    let result = tokio::time::timeout(Duration::from_secs(5), async {
+        let epoch = prover2.clone().db.get_epoch().unwrap();
+        assert_eq!(epoch, 4);
+        assert_eq!(
+            prover.get_commitment().await.unwrap(),
+            prover2.get_commitment().await.unwrap()
+        );
+    }).await;
+    
+    // Cleanup
+    handle.abort();
+    assert!(result.is_ok(), "Test timed out");
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 976a354 and c4a87ff.

📒 Files selected for processing (1)
  • crates/node_types/prover/src/prover/tests.rs (1 hunks)

@jns-ps jns-ps force-pushed the fix-prover-test-error branch from c4a87ff to a83d730 Compare December 5, 2024 08:23
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: 0

🧹 Outside diff range and nitpick comments (1)
crates/node_types/prover/src/webserver.rs (1)

39-39: Consider separating test and production configurations

While using port 0 is excellent for testing, consider maintaining separate configuration defaults for testing and production environments. This could be achieved through feature flags or environment-specific configuration files.

Example approaches:

  1. Use a feature flag:
#[cfg(test)]
fn default() -> Self {
    WebServerConfig {
        enabled: true,
        host: "127.0.0.1".to_string(),
        port: 0,
    }
}

#[cfg(not(test))]
fn default() -> Self {
    WebServerConfig {
        enabled: true,
        host: "127.0.0.1".to_string(),
        port: 50524,
    }
}
  1. Or use environment variables/configuration files to specify the port in production.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between c4a87ff and a83d730.

📒 Files selected for processing (1)
  • crates/node_types/prover/src/webserver.rs (1 hunks)
🔇 Additional comments (2)
crates/node_types/prover/src/webserver.rs (2)

Line range hint 115-119: LGTM: Logging implementation correctly handles dynamic ports

The server startup logging is well implemented, using server.local_addr() to log the actual bound port. This is especially important with dynamic port allocation as it allows tests to determine which port was assigned.


39-39: LGTM: Dynamic port allocation will prevent test conflicts

The change to use port 0 is a good practice for testing scenarios, as it allows the OS to dynamically assign available ports, preventing conflicts when running multiple prover instances simultaneously.

Let's verify that the tests are actually using this configuration:

✅ Verification successful

Port 0 configuration is correctly used throughout the codebase

The verification confirms that:

  1. Test prover instances are created using Config::default() which includes WebServerConfig::default()
  2. The default port 0 configuration is consistently used across both test and production code paths
  3. The change is properly integrated into the configuration hierarchy

This dynamic port allocation setup will work correctly for parallel test execution.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for test configurations to ensure they're using the dynamic port allocation
rg -t rust "WebServerConfig|test.*prover.*port" --no-heading

Length of output: 1006


Script:

#!/bin/bash
# Let's check test files for prover configurations and port usage
rg -t rust "test.*prover.*port|test.*webserver.*port" -A 5 --no-heading

# Also check for any test setup code that might be configuring the prover
ast-grep --pattern 'fn test_$_() {
  $$$
  WebServerConfig {
    $$$
  }
  $$$
}'

Length of output: 157


Script:

#!/bin/bash
# Let's check for integration tests that might be using the prover
rg -t rust "async fn test" -A 10 crates/node_types/prover/src/

# Also check for any test modules
rg -t rust "mod tests" -A 10 crates/node_types/prover/src/

Length of output: 6713


Script:

#!/bin/bash
# Let's check the test helper function that creates the test prover
rg -t rust "create_test_prover" -A 15 crates/node_types/prover/src/prover/tests.rs

# And check the Config default implementation
ast-grep --pattern 'impl Default for Config {
  $$$
}'

Length of output: 5588

@distractedm1nd distractedm1nd merged commit 637b3e0 into main Dec 5, 2024
5 checks passed
@jns-ps jns-ps deleted the fix-prover-test-error branch December 5, 2024 09:00
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.

2 participants