Skip to content

fix: wrap more expensive calls with spawn_blocking#7236

Merged
hanabi1224 merged 3 commits into
mainfrom
hm/warp-more-expensive-fn-with-spawn-blocking
Jun 25, 2026
Merged

fix: wrap more expensive calls with spawn_blocking#7236
hanabi1224 merged 3 commits into
mainfrom
hm/warp-more-expensive-fn-with-spawn-blocking

Conversation

@hanabi1224

@hanabi1224 hanabi1224 commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Summary of changes

Follow-up of #7184

Changes introduced in this pull request:

Reference issue to close (if applicable)

Closes

Other information and links

Change checklist

  • I have performed a self-review of my own code,
  • I have made corresponding changes to the documentation. All new code adheres to the team's documentation standards,
  • I have added tests that prove my fix is effective or that my feature works (if possible),
  • I have made sure the CHANGELOG is up-to-date. All user-facing changes should be reflected in this document.

Outside contributions

  • I have read and agree to the CONTRIBUTING document.
  • I have read and agree to the AI Policy document. I understand that failure to comply with the guidelines will lead to rejection of the pull request.

Summary by CodeRabbit

  • New Features

    • Mining and state-related RPC operations now execute more heavy work in the background to improve responsiveness under load.
    • Circulating supply queries use enhanced async caching for faster repeat lookups.
  • Bug Fixes

    • Improved reliability for code/storage and state calls that require handling expensive fork scenarios, reducing retries and timeouts.
    • Block creation is more robust when cryptographic signing and aggregation are computationally intensive.

@hanabi1224 hanabi1224 added the RPC requires calibnet RPC checks to run on CI label Jun 24, 2026
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e038989a-b5d0-40fb-b5de-5c622262202f

📥 Commits

Reviewing files that changed from the base of the PR and between 048c273 and c47ad91.

📒 Files selected for processing (2)
  • src/rpc/methods/eth.rs
  • src/state_manager/circulating_supply.rs
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • filecoin-project/lotus (manual)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/state_manager/circulating_supply.rs
  • src/rpc/methods/eth.rs

Walkthrough

CPU-intensive state simulation and circulating-supply computation now run through async wrappers backed by tokio::task::spawn_blocking. RPC callers in state.rs, eth.rs, and miner.rs were updated to await the new async signatures and use Arc-wrapped inputs.

Changes

Async spawn_blocking refactor for state ops and crypto

Layer / File(s) Summary
Async StateManager call entrypoints
src/state_manager/message_simulation.rs
call and call_on_state become async methods accepting Arc<Message> and offloading to call_raw_blocking via spawn_blocking; call_blocking and call_on_state_blocking are added as synchronous variants. call_raw is renamed to call_raw_blocking.
State RPC wiring and circulating-supply cache
src/rpc/methods/state.rs, src/state_manager/circulating_supply.rs
StateCall::run becomes async and takes Arc<Message>; its call invocation is awaited using shallow_clone(). StateCirculatingSupply awaits the new async cache API with ctx.db_owned(). get_state_circulating_supply_with_cache is async-ified using get_or_insert_async and spawn_blocking; its raw helper is renamed to get_state_circulating_supply_raw_blocking.
ETH state-call message cloning
src/rpc/methods/eth.rs
eth_getCode and get_storage_at wrap messages in Arc and pass shallow_clone() into the awaited call_on_state retry loop.
Miner block signing and BLS aggregation
src/rpc/methods/miner.rs
BLS aggregation and block-header signing in MinerCreateBlock::handle are awaited via new async wrappers that delegate to existing blocking implementations through spawn_blocking. The block header uses Arc<RawBlockHeader> with Arc::unwrap_or_clone for signature write-back.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • ChainSafe/forest#7061: Directly related — shares the same StateManager::call_raw expensive-fork handling and call/call_on_state delegation in src/state_manager/message_simulation.rs that this PR async-ifies.
  • ChainSafe/forest#7128: Related through the ExpensiveFork retry mechanics in eth_getCode/eth_getStorageAt and StateCall that this PR adjusts when converting to async call_on_state.
  • ChainSafe/forest#7184: Related — establishes the same spawn_blocking/*_blocking async wrapper pattern in state manager execution paths that this PR extends to call/call_on_state and circulating-supply.

Suggested reviewers

  • sudo-shashank
  • LesnyRumcajs
  • akaladarshi
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: moving additional expensive RPC/state operations onto spawn_blocking.
Docstring Coverage ✅ Passed Docstring coverage is 94.44% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch hm/warp-more-expensive-fn-with-spawn-blocking
✨ Simplify code
  • Create PR with simplified code
  • Commit simplified code in branch hm/warp-more-expensive-fn-with-spawn-blocking

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

@hanabi1224 hanabi1224 changed the title fix: warp more expensive calls with spawn_blocking fix: wrap more expensive calls with spawn_blocking Jun 24, 2026
@hanabi1224 hanabi1224 marked this pull request as ready for review June 24, 2026 15:17
@hanabi1224 hanabi1224 requested a review from a team as a code owner June 24, 2026 15:18
@hanabi1224 hanabi1224 requested review from LesnyRumcajs and akaladarshi and removed request for a team June 24, 2026 15:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
src/rpc/methods/miner.rs (1)

246-250: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add context to blocking-task join failures.

Line 249 and Line 275 return JoinError via ? without task-specific context. Add .context(...) on each .await so RPC failures are diagnosable.

As per coding guidelines, "**/*.rs: Use anyhow::Result for most operations and add context with .context() when errors occur".

Suggested patch
 async fn sign_block_header(
     block_header: Arc<RawBlockHeader>,
     worker: Address,
     keystore: Arc<RwLock<KeyStore>>,
 ) -> Result<Signature> {
     tokio::task::spawn_blocking(move || {
         sign_block_header_blocking(&block_header, &worker, &keystore)
     })
-    .await?
+    .await
+    .context("failed to join blocking task for block-header signing")?
 }
@@
 async fn aggregate_from_bls_signatures(bls_sigs: Vec<Signature>) -> anyhow::Result<Signature> {
-    tokio::task::spawn_blocking(move || aggregate_from_bls_signatures_blocking(bls_sigs)).await?
+    tokio::task::spawn_blocking(move || aggregate_from_bls_signatures_blocking(bls_sigs))
+        .await
+        .context("failed to join blocking task for BLS signature aggregation")?
 }

Also applies to: 275-276

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/rpc/methods/miner.rs` around lines 246 - 250, Add task-specific context
to the blocking-task join failures in the RPC methods by updating the
`tokio::task::spawn_blocking(...).await?` calls in the affected miner signing
flow to use `.context(...)` before propagating the error. Make the context
message specific to the operation in `sign_block_header_blocking` and the other
matching blocking-task await in this file so any `JoinError` clearly identifies
which RPC step failed.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/state_manager/circulating_supply.rs`:
- Around line 138-140: The error-string shortening in circulating_supply.rs is
truncating a String at a fixed byte offset, which can panic on UTF-8 boundaries.
Update the logic around the e.to_string() and e.truncate(100) path to shorten
only at a valid character boundary, either by clamping to the nearest char
boundary before truncation or by using a boundary-aware helper, while keeping
the bounded error size behavior.

---

Nitpick comments:
In `@src/rpc/methods/miner.rs`:
- Around line 246-250: Add task-specific context to the blocking-task join
failures in the RPC methods by updating the
`tokio::task::spawn_blocking(...).await?` calls in the affected miner signing
flow to use `.context(...)` before propagating the error. Make the context
message specific to the operation in `sign_block_header_blocking` and the other
matching blocking-task await in this file so any `JoinError` clearly identifies
which RPC step failed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 8baae7be-acce-46d8-9857-0ac797944b3a

📥 Commits

Reviewing files that changed from the base of the PR and between d3ce944 and 048c273.

📒 Files selected for processing (5)
  • src/rpc/methods/eth.rs
  • src/rpc/methods/miner.rs
  • src/rpc/methods/state.rs
  • src/state_manager/circulating_supply.rs
  • src/state_manager/message_simulation.rs
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • filecoin-project/lotus (manual)

Comment thread src/state_manager/circulating_supply.rs
@codecov

codecov Bot commented Jun 24, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 64.58333% with 34 lines in your changes missing coverage. Please review.
✅ Project coverage is 64.02%. Comparing base (cfb1049) to head (c47ad91).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
src/rpc/methods/miner.rs 0.00% 27 Missing ⚠️
src/state_manager/circulating_supply.rs 82.35% 2 Missing and 1 partial ⚠️
src/rpc/methods/state.rs 77.77% 0 Missing and 2 partials ⚠️
src/state_manager/message_simulation.rs 93.10% 0 Missing and 2 partials ⚠️
Additional details and impacted files
Files with missing lines Coverage Δ
src/rpc/methods/eth.rs 65.14% <100.00%> (+0.09%) ⬆️
src/rpc/methods/state.rs 44.50% <77.77%> (+0.11%) ⬆️
src/state_manager/message_simulation.rs 79.22% <93.10%> (+1.63%) ⬆️
src/state_manager/circulating_supply.rs 78.21% <82.35%> (+0.43%) ⬆️
src/rpc/methods/miner.rs 6.50% <0.00%> (-0.93%) ⬇️

... and 10 files with indirect coverage changes


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update cfb1049...c47ad91. Read the comment docs.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@hanabi1224 hanabi1224 added this pull request to the merge queue Jun 25, 2026
Merged via the queue into main with commit c1018d2 Jun 25, 2026
55 of 56 checks passed
@hanabi1224 hanabi1224 deleted the hm/warp-more-expensive-fn-with-spawn-blocking branch June 25, 2026 22:49
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

RPC requires calibnet RPC checks to run on CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants