Skip to content

Reduce redundancy in main.rs#849

Merged
FabijanC merged 2 commits intomainfrom
reorganize-main
Sep 19, 2025
Merged

Reduce redundancy in main.rs#849
FabijanC merged 2 commits intomainfrom
reorganize-main

Conversation

@FabijanC
Copy link
Copy Markdown
Contributor

@FabijanC FabijanC commented Sep 16, 2025

Usage related changes

None

Development related changes

  • I thought startup time would have been affected, but as evidenced by locally executing the introduced Python script, it is not.
  • Reduce double installation of shutdown_signal.
    • dockerized Devnet not affected

Checklist:

  • Checked out the contribution guidelines
  • Applied formatting - ./scripts/format.sh
  • No linter errors - ./scripts/clippy_check.sh
  • No unused dependencies - ./scripts/check_unused_deps.sh
  • No spelling errors - ./scripts/check_spelling.sh
  • Performed code self-review
  • Rebased to the latest commit of the target branch (or merged it into my branch)
    • Once you make the PR reviewable, please avoid force-pushing
  • Updated the docs if needed - ./website/README.md
  • Linked the issues resolvable by this PR - linking info
  • Updated the tests if needed; all passing - execution info

Summary by CodeRabbit

  • Refactor

    • Reworked startup sequence for more reliable initialization and logging.
    • Improved shutdown handling and task termination, with clearer error propagation.
    • Simplified flow by removing redundant variables and reordering operations.
  • Tests

    • Added a benchmarking script to measure repeated startup times via the health endpoint, with configurable iterations.
    • Automates launching, readiness checks, and clean termination to track total elapsed time.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Sep 16, 2025

Walkthrough

  • Reworks initialization in crates/starknet-devnet/src/main.rs: instantiate Starknet first, adjust calls to use Starknet directly for timestamp shift and predeployed accounts, log accounts before creating Api, then construct Api and JsonRpcHandler.
  • Alters shutdown and task handling: pass api by value to shutdown_signal and propagate task errors via result?? after join_all.
  • Removes temporary predeployed_accounts variable and refactors ordering accordingly.
  • Adds scripts/benchmark/startup_test.py: a CLI tool to spawn an executable repeatedly, poll /is_alive on http://127.0.0.1:5050 with timeouts/retries, then terminate, reporting total elapsed time.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The title "Reduce redundancy in main.rs" is concise, file-specific, and accurately summarizes the primary change shown in the diff (reworking main.rs to remove duplicated shutdown_signal installation and simplify initialization). It is clear and informative for a teammate scanning the commit history.
Description Check ✅ Passed The PR description follows the repository template by including "Usage related changes" (explicitly marked None), a "Development related changes" section that explains the shutdown_signal deduplication and local startup benchmarking, and a completed checklist. The sections are present and contain sufficient, relevant information for reviewers to understand the scope and testing performed.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch reorganize-main

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@FabijanC FabijanC marked this pull request as ready for review September 18, 2025 12:27
@FabijanC
Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Sep 18, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Copy link
Copy Markdown

@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 (8)
crates/starknet-devnet/src/main.rs (2)

300-303: Small readability tweak for timestamp shift.

Pre-compute the shift for clarity; current logic is fine.

-        starknet.set_block_timestamp_shift(
-            start_time as i64 - Starknet::get_unix_timestamp_as_seconds() as i64,
-        );
+        let shift = start_time as i64 - Starknet::get_unix_timestamp_as_seconds() as i64;
+        starknet.set_block_timestamp_shift(shift);

309-312: Avoid taking an extra reference.

If get_predeployed_accounts() returns &Vec<Account>, passing &... makes it &&Vec<_>. Let deref-coercion work by dropping the &.

-    log_predeployed_accounts(
-        &starknet.get_predeployed_accounts(),
-        starknet_config.seed,
-        starknet_config.predeployed_accounts_initial_balance.clone(),
-    );
+    log_predeployed_accounts(
+        starknet.get_predeployed_accounts(),
+        starknet_config.seed,
+        starknet_config.predeployed_accounts_initial_balance.clone(),
+    );
scripts/benchmark/startup_test.py (6)

13-15: Make Devnet URL configurable.

Hardcoding the URL/port limits usefulness. Add a CLI flag (with sane default).

-DEVNET_URL = "http://127.0.0.1:5050"
-REQUEST_TIMEOUT = 2
+DEVNET_URL_DEFAULT = "http://127.0.0.1:5050"
+REQUEST_TIMEOUT = 2

And see arg parsing change below.


17-35: Polling: reduce request timeout and handle readiness quietly.

Current 2s per attempt × 50 can stall >100s. Use short connect/read timeouts; drop the debug print or gate it.

 def ensure_process_started(proc: subprocess.Popen):
     """Ensure the process under test is started"""
     max_retries = 50
     for i in range(max_retries):
         if proc.returncode is not None:
             raise RuntimeError(f"Process exited with returncode {proc.returncode}")

         try:
-            resp = requests.get(f"{DEVNET_URL}/is_alive", timeout=REQUEST_TIMEOUT)
+            # Use short connect/read timeouts for snappy polling
+            resp = requests.get(f"{DEVNET_URL}/is_alive", timeout=(0.2, 0.5))
             if resp.status_code == 200:
-                print(f"DEBUG returning on i={i}")
                 return
         except requests.exceptions.ConnectionError:
             pass

         time.sleep(0.1)

     raise RuntimeError("Could not start process")

37-41: Terminate robustly (fallback to kill on timeout).

Prevents lingering child processes if terminate doesn’t exit promptly.

 def terminate_and_wait(proc: subprocess.Popen):
     """Terminates the process and waits."""
-    proc.terminate()
-    proc.wait()
+    proc.terminate()
+    try:
+        proc.wait(timeout=5)
+    except subprocess.TimeoutExpired:
+        proc.kill()
+        proc.wait()

43-47: Use argparse; validate inputs; allow overriding URL.

Improves UX and safety; integrates URL parameterization from above.

-def main():
-    """Spawn Devnet"""
-    command = sys.argv[1]
-    iterations = int(sys.argv[2])
+def main():
+    """Spawn Devnet"""
+    import argparse
+    parser = argparse.ArgumentParser(description="Measure Devnet startup time.")
+    parser.add_argument("command", help="Path to Devnet executable with args")
+    parser.add_argument("iterations", type=int, help="Number of runs")
+    parser.add_argument("--devnet-url", default=DEVNET_URL_DEFAULT, help="Health-check base URL")
+    args = parser.parse_args()
+    global DEVNET_URL
+    DEVNET_URL = args.devnet_url
+    command = args.command
+    iterations = args.iterations

50-52: Split command safely.

command.split() breaks on quoted args and spaces; use shlex.split.

-        with subprocess.Popen(
-            command.split(), stdout=subprocess.DEVNULL
-        ) as command_proc:
+        import shlex
+        with subprocess.Popen(
+            shlex.split(command), stdout=subprocess.DEVNULL
+        ) as command_proc:

56-56: Friendlier output formatting.

Round to milliseconds for readability.

-    print("Time passed:", time.time() - start_time)
+    elapsed = time.time() - start_time
+    print(f"Time passed: {elapsed:.3f}s")
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9f882e8 and 04dd205.

📒 Files selected for processing (2)
  • crates/starknet-devnet/src/main.rs (2 hunks)
  • scripts/benchmark/startup_test.py (1 hunks)
🧰 Additional context used
🪛 Ruff (0.12.2)
scripts/benchmark/startup_test.py

22-22: Avoid specifying long messages outside the exception class

(TRY003)


34-34: Avoid specifying long messages outside the exception class

(TRY003)


50-50: subprocess call: check for execution of untrusted input

(S603)

🔇 Additional comments (3)
crates/starknet-devnet/src/main.rs (2)

294-294: Starknet-first initialization LGTM.

Creating Starknet before Api simplifies ownership and reduces locking later.


314-316: Api move + handler wiring LGTM.

Passing Api by value here aligns with the consuming shutdown_signal(api) later, while the handler keeps a clone.

scripts/benchmark/startup_test.py (1)

50-50: Note on subprocess safety.

Ensure command originates from trusted input; otherwise restrict or validate it (matches Ruff S603).

@FabijanC FabijanC requested a review from 3alpha September 18, 2025 13:19
@FabijanC FabijanC merged commit cf8b31e into main Sep 19, 2025
1 check passed
@FabijanC FabijanC deleted the reorganize-main branch September 19, 2025 11:22
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