Skip to content

read the k from epoch when the node starts #4460

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

Merged
merged 1 commit into from
Apr 9, 2025
Merged

Conversation

jackzhhuang
Copy link
Collaborator

@jackzhhuang jackzhhuang commented Apr 9, 2025

Pull request type

Please check the type of change your PR introduces:

  • Bugfix
  • Feature
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Documentation content changes
  • Other (please describe):

What is the current behavior?

Issue Number: N/A

What is the new behavior?

Other information

Summary by CodeRabbit

  • New Features

    • Enhanced the upgrade process to improve state management and ensure smoother transitions when blockchain updates occur.
  • Chores

    • Updated project dependencies to support the expanded functionalities.

@jackzhhuang jackzhhuang requested a review from jolestar as a code owner April 9, 2025 09:49
Copy link

coderabbitai bot commented Apr 9, 2025

Walkthrough

This pull request adds two new workspace dependencies to the Cargo.toml of the flexidag project and updates the check_upgrade functionality. The check_upgrade method in BlockDAG now accepts an additional storage: Arc<Storage> parameter and includes new logic to retrieve blockchain state and epoch data for its upgrade process. The call site in the node service is updated accordingly to supply this new parameter.

Changes

File(s) Change Summary
flexidag/Cargo.toml Added workspace dependencies: starcoin-statedb and starcoin-vm-runtime.
flexidag/src/blockdag.rs, node/…/node.rs Updated the check_upgrade method signature to include storage: Arc<Storage>. Incorporated logic in BlockDAG to retrieve and process state and epoch data, and updated the corresponding call in the node service to pass the storage clone.

Sequence Diagram(s)

sequenceDiagram
    participant NS as NodeService
    participant BD as BlockDAG
    participant ST as Storage
    participant CDB as ChainStateDB
    participant ASR as AccountStateReader
    participant GDM as ghost_dag_manager

    NS->>BD: check_upgrade(main, genesis_id, storage)
    BD->>BD: Evaluate block number vs force upgrade threshold
    alt Upgrade condition met
        BD->>ST: Retrieve state root & chain storage
        BD->>CDB: Initialize ChainStateDB with storage
        CDB->>ASR: Create AccountStateReader
        ASR->>BD: Provide Epoch resource (via genesis address)
        BD->>GDM: Update k using epoch's max uncles value
    else Condition not met
        BD-->>NS: Return without changes
    end
Loading

Poem

Hi there, I'm a coding bunny on the run,
Leaping through dependencies under the sun.
New storage in place, upgrades now in swing,
With state and epoch, my code starts to sing.
Hoppy changes abound—oh, what fun! 🐰✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 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.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@jackzhhuang jackzhhuang requested review from sanlee42 and removed request for jolestar April 9, 2025 09:49
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 6e1e928 and 5b65062.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (3)
  • flexidag/Cargo.toml (1 hunks)
  • flexidag/src/blockdag.rs (3 hunks)
  • node/src/node.rs (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
flexidag/src/blockdag.rs (7)
vm/types/src/account_config/constants/addresses.rs (1)
  • genesis_address (16-18)
vm/vm-runtime/src/force_upgrade_management.rs (1)
  • get_force_upgrade_block_number (10-24)
node/src/lib.rs (1)
  • storage (125-129)
state/api/src/chain_state.rs (1)
  • state_root (128-128)
flexidag/src/consensusdb/db.rs (1)
  • new (43-45)
flexidag/src/ghostdag/protocol.rs (2)
  • new (19-23)
  • new (56-70)
vm/types/src/on_chain_resource/epoch.rs (1)
  • epoch (138-140)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build and test
🔇 Additional comments (5)
flexidag/Cargo.toml (1)

31-32:

✅ Verification successful

Confirm correct usage of newly added workspace dependencies.

The additions of starcoin-statedb and starcoin-vm-runtime look consistent with the new storage and upgrade logic introduced in the BlockDAG. Ensure that these dependencies are actually required for the new logic and do not introduce unnecessary overhead or duplication.

Would you like to verify if any references to these crates remain unused in the codebase?


🏁 Script executed:

#!/bin/bash
# Check for any usage references of starcoin-statedb and starcoin-vm-runtime
rg --context 5 'starcoin-statedb|starcoin-vm-runtime'

Length of output: 38428


Dependency usage confirmed:
After verifying with a search across the repository, both starcoin-statedb and starcoin-vm-runtime are frequently referenced in multiple Cargo files and in the lock file. This consistent usage across the codebase—covering areas such as state management, storage, and VM components—indicates that their inclusion is intentional and aligns with the new storage and upgrade logic in the BlockDAG. There is no evidence of unnecessary overhead or duplication.

node/src/node.rs (1)

309-313:

❓ Verification inconclusive

Ensure proper error handling when calling check_upgrade.

The newly added storage.clone() parameter supplies the BlockDAG upgrade logic with persistent storage. This may fail if storage is not fully initialized or if there are concurrency concerns. Verify that any potential errors returned by check_upgrade (e.g. missing epoch, I/O issues) are handled gracefully and do not crash the node unexpectedly.


🏁 Script executed:

#!/bin/bash
# Description: Search for try/catch or appropriate error handling around `dag.check_upgrade`.
rg -A 5 "dag.check_upgrade"

Length of output: 272


Ensure Proper Propagation and Handling of Errors from check_upgrade

The current implementation uses the ? operator here:

    dag.check_upgrade(
        chain_info.status().head(),
        genesis.block().id(),
        storage.clone(),
    )?;

While propagating errors using ? is idiomatic in Rust, please verify that these errors—whether they stem from storage initialization, missing epochs, or potential I/O/concurrency issues—are caught and managed appropriately by the caller. In particular, ensure that the upstream error handling logs sufficient context and avoids causing an unexpected node crash. If additional contextual wrapping or a more granular recovery mechanism is required at this stage, please adjust accordingly.

flexidag/src/blockdag.rs (3)

34-37: Validate new imports for consistency.

New imports—AccountStateReader, ChainStateDB, IntoSuper, and Storage—are used in the check_upgrade logic. Confirm these are only introduced where needed, as extraneous imports can cause clutter and raise maintenance.


43-44: Usage of get_force_upgrade_block_number and Epoch identified.

These imports align with the forced upgrade logic. No immediate issues. Just ensure that your code handles different chain IDs correctly and that the Epoch type is stable.


1021-1026: New check_upgrade signature requires storage.

Adding storage: Arc<Storage> to check_upgrade centralizes all relevant state logic in a single call, which can improve clarity. However, ensure that concurrency is handled properly: if multiple callers invoke check_upgrade in parallel, shared data in storage must remain consistent.

Would you like a shell script to grep for all invocations of this method to ensure it’s not called concurrently from multiple services?

Comment on lines +1070 to +1082
// update k
if main.number() >= get_force_upgrade_block_number(&main.chain_id()) {
let state_root = main.state_root();
let state_db = ChainStateDB::new(storage.clone().into_super_arc(), Some(state_root));
let account_reader = AccountStateReader::new(&state_db);
let epoch = account_reader
.get_resource::<Epoch>(genesis_address())?
.ok_or_else(|| format_err!("Epoch is none."))?;

self.ghost_dag_manager()
.update_k(u16::try_from(epoch.max_uncles_per_block())?);
}

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update the DAG's k value from on-chain Epoch.

When the block number exceeds get_force_upgrade_block_number, the code retrieves the on-chain epoch information and updates ghost_dag_manager().update_k(...). Confirm that:

  1. The code handles any errors in reading the Epoch resource (for example, if the resource is absent or corrupted).
  2. The DAG remains valid if k changes during runtime.
  3. Adequate tests exist to validate this dynamic reconfiguration.

Otherwise, the logic is sound.

Consider adding additional logging or fallback handling if the epoch resource is unavailable. This prevents ungraceful failures in production.

@jackzhhuang jackzhhuang merged commit 54af0b8 into dag-master Apr 9, 2025
4 of 5 checks passed
@jackzhhuang jackzhhuang deleted the fix-k-update branch April 9, 2025 11:06
Copy link

github-actions bot commented Apr 9, 2025

Benchmark for b224784

Click to view benchmark
Test Base PR %
accumulator_append 730.4±55.69µs 740.4±72.18µs +1.37%
block_apply/block_apply_10 363.1±4.94ms 370.5±5.83ms +2.04%
block_apply/block_apply_1000 39.2±0.59s 40.0±1.98s +2.04%
get_with_proof/db_store 44.8±6.62µs 43.9±2.25µs -2.01%
get_with_proof/mem_store 35.7±0.66µs 37.1±5.25µs +3.92%
put_and_commit/db_store/1 109.7±4.05µs 117.8±18.95µs +7.38%
put_and_commit/db_store/10 1019.9±66.75µs 1086.3±93.28µs +6.51%
put_and_commit/db_store/100 9.5±0.53ms 9.9±1.33ms +4.21%
put_and_commit/db_store/5 544.0±25.62µs 534.3±27.86µs -1.78%
put_and_commit/db_store/50 4.8±0.19ms 4.7±0.27ms -2.08%
put_and_commit/mem_store/1 69.7±8.17µs 69.1±8.96µs -0.86%
put_and_commit/mem_store/10 651.4±57.05µs 654.8±62.24µs +0.52%
put_and_commit/mem_store/100 6.3±0.30ms 6.2±0.33ms -1.59%
put_and_commit/mem_store/5 321.9±29.19µs 326.6±31.83µs +1.46%
put_and_commit/mem_store/50 3.1±0.17ms 3.1±0.16ms 0.00%
query_block/query_block_in(10)_times(100) 8.0±0.32ms 8.2±0.42ms +2.50%
query_block/query_block_in(10)_times(1000) 84.4±5.69ms 81.8±2.11ms -3.08%
query_block/query_block_in(10)_times(10000) 844.8±61.86ms 833.4±20.76ms -1.35%
query_block/query_block_in(1000)_times(100) 1196.7±53.93µs 1178.6±15.65µs -1.51%
query_block/query_block_in(1000)_times(1000) 11.9±0.58ms 12.0±0.59ms +0.84%
query_block/query_block_in(1000)_times(10000) 115.6±2.14ms 139.6±47.57ms +20.76%
storage_transaction 1101.4±403.04µs 1134.7±438.41µs +3.02%
vm/transaction_execution/1 390.0±6.00ms 394.0±10.39ms +1.03%
vm/transaction_execution/10 121.9±2.24ms 124.5±6.82ms +2.13%
vm/transaction_execution/20 117.7±4.10ms 117.0±3.00ms -0.59%
vm/transaction_execution/5 152.6±3.09ms 152.5±5.24ms -0.07%
vm/transaction_execution/50 133.8±4.07ms 134.8±3.11ms +0.75%

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