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

refactor(prover): Using some std libs instead of thirdparty lib #1573

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

ariesdevil
Copy link

@ariesdevil ariesdevil commented Dec 12, 2024

Purpose or design rationale of this PR

Using some std libs instead of third-party lib, and removing unnecessary deps.
This PR also removes some unnecessary unsafe blocks.

PR title

Your PR title must follow conventional commits (as we are doing squash merge for each PR), so it must start with one of the following types:

  • build: Changes that affect the build system or external dependencies (example scopes: yarn, eslint, typescript)
  • ci: Changes to our CI configuration files and scripts (example scopes: vercel, github, cypress)
  • docs: Documentation-only changes
  • feat: A new feature
  • fix: A bug fix
  • perf: A code change that improves performance
  • refactor: A code change that doesn't fix a bug, or add a feature, or improves performance
  • style: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc)
  • test: Adding missing tests or correcting existing tests

Deployment tag versioning

Has tag in common/version.go been updated or have you added bump-version label to this PR?

  • No, this PR doesn't involve a new deployment, git tag, docker image tag
  • Yes

Breaking change label

Does this PR have the breaking-change label?

  • No, this PR is not a breaking change
  • Yes

Summary by CodeRabbit

  • New Features

    • Enhanced thread-safety for various static variables across the application.
  • Bug Fixes

    • Improved safety and reliability by eliminating unsafe operations in variable handling.
  • Refactor

    • Updated dependency management by removing unnecessary packages.
    • Replaced mutable static variables with thread-safe alternatives for better concurrency practices.
    • Changed variable types to enhance thread safety during initialization.

Copy link

coderabbitai bot commented Dec 12, 2024

Walkthrough

The changes involve modifications to the prover package, focusing on dependency management and enhancing thread safety. The Cargo.toml file has had several dependencies removed, reducing the overall dependency footprint. Additionally, several Rust source files have transitioned from using mutable static variables and OnceCell to OnceLock, improving safety and concurrency handling. These updates include changes to how environment variables are initialized and accessed, ensuring that unsafe code is minimized or eliminated throughout the codebase.

Changes

File Path Change Summary
prover/Cargo.toml Removed dependencies: futures, snark-verifier-sdk, once_cell. Retained prover_darwin and prover_darwin_v2 unchanged.
prover/src/config.rs Updated SCROLL_PROVER_ASSETS_DIRS from mutable Vec<String> to OnceLock<Vec<String>>, removed unsafe blocks, added debug_assert!.
prover/src/version.rs Changed VERSION from OnceCell<String> to OnceLock<String>, removed unsafe access.
prover/src/zk_circuits_handler/common.rs Updated PARAMS_MAP from OnceCell<Rc<BTreeMap<u32, ParamsKZG<Bn256>>> to OnceLock<Arc<BTreeMap<u32, ParamsKZG<Bn256>>>, removed unsafe block.
prover/src/zk_circuits_handler/darwin.rs Changed several static variables from Lazy to LazyLock for thread-safe initialization, including OUTPUT_DIR, WORK_DIR, etc.
prover/src/zk_circuits_handler/darwin_v2.rs Changed OUTPUT_DIR from Lazy<Option<String>> to LazyLock<Option<String>>, added LazyLock import.

Poem

In the code where bunnies play,
Dependencies hopped away,
OnceLock now keeps things tight,
Safe and sound, both day and night.
With every change, we cheer and dance,
For safer code, we take a chance! 🐇✨


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

@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)
prover/src/version.rs (1)

17-17: Consider removing unnecessary clone()

The clone() call creates an unnecessary copy of the string. Since OnceLock::get_or_init returns a reference, we can return it directly.

-    VERSION.get_or_init(init_version).clone()
+    VERSION.get_or_init(init_version).to_string()
prover/src/zk_circuits_handler/common.rs (1)

14-17: Consider simplifying lifetime parameter

The function signature uses an explicit lifetime 'a which might be unnecessary since OnceLock provides static references.

-pub fn get_params_map_instance<'a, F>(load_params_func: F) -> &'a BTreeMap<u32, ParamsKZG<Bn256>>
+pub fn get_params_map_instance<F>(load_params_func: F) -> &'static BTreeMap<u32, ParamsKZG<Bn256>>
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 33b1b3c and ba33131.

⛔ Files ignored due to path filters (1)
  • prover/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • prover/Cargo.toml (0 hunks)
  • prover/src/config.rs (3 hunks)
  • prover/src/version.rs (2 hunks)
  • prover/src/zk_circuits_handler/common.rs (1 hunks)
  • prover/src/zk_circuits_handler/darwin.rs (1 hunks)
  • prover/src/zk_circuits_handler/darwin_v2.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • prover/Cargo.toml
🔇 Additional comments (8)
prover/src/version.rs (1)

1-1: LGTM! Good transition to standard library

The change from OnceCell to OnceLock improves thread safety while reducing third-party dependencies. The initialization remains correct and the unsafe block is properly eliminated.

Also applies to: 4-4

prover/src/zk_circuits_handler/common.rs (2)

3-6: LGTM! Clean import organization

Good organization of imports, properly bringing in Arc and OnceLock from std::sync.


8-8: LGTM! Proper thread-safe static initialization

Good transition from Rc to Arc for thread-safe reference counting, combined with OnceLock for safe initialization.

prover/src/config.rs (1)

54-54: LGTM! Thread-safe static initialization

Good transition to OnceLock for thread-safe initialization of the assets directories.

prover/src/zk_circuits_handler/darwin.rs (2)

19-19: LGTM! Good use of standard library for thread-safe lazy initialization.

The change from once_cell::Lazy to std::sync::LazyLock aligns well with the PR objective of using standard library features instead of third-party dependencies. LazyLock provides the same thread-safe initialization guarantees.

Also applies to: 22-22


Line range hint 271-287: LGTM! Consistent use of LazyLock across test configuration.

The change to LazyLock has been consistently applied across all static configuration variables in the test module, maintaining the same initialization patterns and functionality.

prover/src/zk_circuits_handler/darwin_v2.rs (2)

19-19: LGTM! Consistent implementation with darwin.rs.

The change to LazyLock mirrors the implementation in darwin.rs, maintaining consistency across both handler implementations while benefiting from standard library features.

Also applies to: 22-22


Line range hint 402-418: LGTM! Consistent test configuration with darwin.rs.

The change to LazyLock has been consistently applied across all static configuration variables, maintaining parity with the implementation in darwin.rs. The only difference is the use of DARWIN_V2_TEST_DIR environment variable for the work directory, which is appropriate for this V2 implementation.

Comment on lines +66 to +71

SCROLL_PROVER_ASSETS_DIRS.get_or_init(|| dirs.into_iter().map(|s| s.to_string()).collect());
log::info!(
"init SCROLL_PROVER_ASSETS_DIRS: {:?}",
SCROLL_PROVER_ASSETS_DIRS
);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider improving error handling in initialization

The initialization could benefit from better error handling and validation.

 pub fn init() -> Result<()> {
     let value = std::env::var(SCROLL_PROVER_ASSETS_DIR_ENV_NAME)?;
     let dirs: Vec<&str> = value.split(',').collect();
     if dirs.len() != 2 {
         bail!("env variable SCROLL_PROVER_ASSETS_DIR value must be 2 parts seperated by comma.")
     }
-    SCROLL_PROVER_ASSETS_DIRS.get_or_init(|| dirs.into_iter().map(|s| s.to_string()).collect());
+    if SCROLL_PROVER_ASSETS_DIRS.set(dirs.into_iter().map(|s| s.to_string()).collect()).is_err() {
+        bail!("SCROLL_PROVER_ASSETS_DIRS was already initialized");
+    }
     log::info!(
         "init SCROLL_PROVER_ASSETS_DIRS: {:?}",
         SCROLL_PROVER_ASSETS_DIRS
     );
     Ok(())

Committable suggestion skipped: line range outside the PR's diff.

@ariesdevil
Copy link
Author

Do you have time to review this PR? @georgehao

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between ba33131 and 82fab1a.

⛔ Files ignored due to path filters (1)
  • prover/Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (6)
  • prover/Cargo.toml (0 hunks)
  • prover/src/config.rs (3 hunks)
  • prover/src/version.rs (2 hunks)
  • prover/src/zk_circuits_handler/common.rs (1 hunks)
  • prover/src/zk_circuits_handler/darwin.rs (1 hunks)
  • prover/src/zk_circuits_handler/darwin_v2.rs (1 hunks)
💤 Files with no reviewable changes (1)
  • prover/Cargo.toml
🚧 Files skipped from review as they are similar to previous changes (4)
  • prover/src/zk_circuits_handler/darwin_v2.rs
  • prover/src/version.rs
  • prover/src/zk_circuits_handler/common.rs
  • prover/src/zk_circuits_handler/darwin.rs
🔇 Additional comments (3)
prover/src/config.rs (3)

4-4: Good use of std::sync::OnceLock for thread-safety!

The transition from a mutable static to OnceLock is a great improvement that aligns with Rust's safety principles and the PR's objective of utilizing standard library features.

Also applies to: 54-54


66-71: Consider improving error handling in initialization

The initialization could benefit from better error handling and validation.


76-87: Refactor repeated code in enable methods

The enable_first and enable_second methods contain significant code duplication and multiple unwrap calls.

Also applies to: 91-102

Comment on lines +76 to +87
debug_assert!(
SCROLL_PROVER_ASSETS_DIRS.get().is_some()
&& SCROLL_PROVER_ASSETS_DIRS.get().unwrap().len() >= 2
);
log::info!(
"set env {SCROLL_PROVER_ASSETS_DIR_ENV_NAME} to {}",
&SCROLL_PROVER_ASSETS_DIRS.get().unwrap()[0]
);
std::env::set_var(
SCROLL_PROVER_ASSETS_DIR_ENV_NAME,
&SCROLL_PROVER_ASSETS_DIRS.get().unwrap()[0],
);
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Based on the search results, I can now generate the final response:

Environment variable usage is consistent but has multiple setters

The SCROLL_PROVER_ASSETS_DIR environment variable is used consistently across the codebase, but there are multiple locations where it's being set:

  • prover/src/config.rs: Sets the variable twice with different values from a split array
  • common/libzkp/impl/src/verifier.rs: Sets using low_conf.assets_path
  • common/libzkp/impl/src/verifier/darwin.rs: Sets using assets_dir
  • common/libzkp/impl/src/verifier/darwin_v2.rs: Sets using assets_dir

The variable is properly validated in config.rs to ensure it contains at least 2 comma-separated paths, but the other setters might not follow this requirement. Consider centralizing the environment variable management to avoid potential conflicts.

🔗 Analysis chain

Verify environment variable usage across the codebase

Let's ensure that the SCROLL_PROVER_ASSETS_DIR environment variable is consistently used and that there are no conflicting usages.

Also applies to: 91-102

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for consistent usage of SCROLL_PROVER_ASSETS_DIR environment variable

# Search for all occurrences of the environment variable
echo "Searching for environment variable usage..."
rg -A 2 "SCROLL_PROVER_ASSETS_DIR" 

# Search for potential environment variable setters
echo "Checking for environment variable setters..."
ast-grep --pattern 'std::env::set_var($name, $value)'

Length of output: 3884

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.

1 participant