Skip to content

fix: the statemachine#7169

Merged
SWvheerden merged 5 commits intotari-project:developmentfrom
SWvheerden:sw_fix_state_machine
Jun 3, 2025
Merged

fix: the statemachine#7169
SWvheerden merged 5 commits intotari-project:developmentfrom
SWvheerden:sw_fix_state_machine

Conversation

@SWvheerden
Copy link
Copy Markdown
Collaborator

@SWvheerden SWvheerden commented Jun 3, 2025

Description

Fixes the statemachine to properly do startup-only peer sync.

fixes: #7148

Summary by CodeRabbit

  • New Features
    • Improved handling of peer management and synchronization status for more reliable node operation.
  • Bug Fixes
    • Simplified and streamlined bootstrap and listening state logic for enhanced stability.
    • Improved event handling during node startup, reducing missed events and timeouts.
  • Other Changes
    • Updated debug logging for easier troubleshooting.
    • Adjusted peer flag defaults for seed peers.
    • Enhanced internal debugging capabilities with additional struct support.

@SWvheerden SWvheerden requested a review from a team as a code owner June 3, 2025 12:50
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Jun 3, 2025

Walkthrough

This update integrates a PeerManager handle into the BaseNodeStateMachine, removes all DHT bootstrap event handling and UI bootstrap phase state from the listening state, changes bootstrap event waiting in startup to an asynchronous wait with timeout, modifies peer seed flag usage, and adds a Debug trait derive to UnvalidatedPeerInfo. Additionally, it sets the bootstrap method to SeedStrap upon discovery completion in network discovery state machine.

Changes

Files Summary
base_layer/core/src/base_node/state_machine_service/initializer.rs Added retrieval and passing of peer_manager handle to BaseNodeStateMachine::new
base_layer/core/src/base_node/state_machine_service/state_machine.rs Added peer_manager field and parameter to BaseNodeStateMachine; changed a log level from warn to debug
base_layer/core/src/base_node/state_machine_service/states/listening.rs Removed all DHT bootstrap event handling and bootstrap phase UI state; simplified event loop to chain metadata only
base_layer/core/src/base_node/state_machine_service/states/starting_state.rs Changed DHT bootstrap event waiting from non-blocking try_recv to asynchronous recv with timeout
base_layer/p2p/src/peer_seeds.rs Changed PeerFlags in SeedPeer to Peer conversion from SEED flag to default flags
comms/dht/src/rpc/peer_info.rs Added #[derive(Debug)] to UnvalidatedPeerInfo struct
comms/dht/src/network_discovery/state_machine.rs Added async call to set bootstrap method to SeedStrap upon discovery completion before state transition
base_layer/core/tests/helpers/sync.rs and base_layer/core/tests/tests/node_state_machine.rs Added peer_manager argument to BaseNodeStateMachine constructor calls in tests

Error: Could not generate a valid Mermaid diagram after multiple attempts.

Assessment against linked issues

Objective Addressed Explanation
Remove incorrect base node state machine states and prevent waiting for peer data after failed sync (Issue #7148)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes detected.

Possibly related PRs

  • feat: new bootstrap process #7121: Modifies BaseNodeStateMachine struct and constructor by removing peer_manager and adding dht_event_stream, directly related but with opposite implementation to this PR.
  • feat: add min peer version option #7006: Changes PeerManager internals and constructor signature; related due to overlapping use of peer_manager.
  • (No third PR strongly related based on provided data)

Suggested reviewers

  • hansieodendaal

Poem

🐇
A peer manager joins the dance,
Bootstrap steps lose their stance.
Async waits now keep the beat,
Flags reset, debugging neat.
Listening clears the old scene,
A cleaner sync, fresh and keen!
Hop along, the network’s green! 🌿✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bebb388 and f6e299a.

📒 Files selected for processing (2)
  • base_layer/core/tests/helpers/sync.rs (1 hunks)
  • base_layer/core/tests/tests/node_state_machine.rs (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: test (testnet, esmeralda)
  • GitHub Check: cargo check with stable
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: ci
  • GitHub Check: Cucumber tests / Base Layer
  • GitHub Check: Cucumber tests / FFI
🔇 Additional comments (4)
base_layer/core/tests/tests/node_state_machine.rs (3)

109-109: LGTM! Test updated correctly for new constructor signature.

The addition of alice_node.comms.peer_manager() parameter aligns with the updated BaseNodeStateMachine constructor signature and maintains test compatibility.


253-253: LGTM! Test updated correctly for new constructor signature.

The addition of alice_node.comms.peer_manager() parameter is consistent with the other test updates and properly sources the peer manager from the communications component.


316-316: LGTM! Test updated correctly for new constructor signature.

The addition of node.comms.peer_manager() parameter maintains consistency with the other test updates and correctly provides the required peer manager handle.

base_layer/core/tests/helpers/sync.rs (1)

188-188: LGTM! Helper function updated correctly for new constructor signature.

The addition of node_interface.comms.peer_manager() parameter ensures that all BaseNodeStateMachine instances created by this helper function are properly initialized with the required peer manager handle, maintaining consistency with the updated constructor.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this 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
Copy Markdown
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

🧹 Nitpick comments (3)
base_layer/core/src/base_node/state_machine_service/initializer.rs (1)

46-46: Move the std import to the top of the imports section.

For consistency with Rust conventions, std imports should be grouped together at the top of the file.

Move this import to line 23 with the other standard library imports:

use log::*;
+use std::sync::Arc;
use tari_comms::connectivity::ConnectivityRequester;
base_layer/core/src/base_node/state_machine_service/states/starting_state.rs (1)

56-56: Consider making the bootstrap timeout configurable.

The 120-second timeout is hardcoded. Consider adding this as a configuration parameter in BaseNodeStateMachineConfig to allow flexibility for different network conditions.

Add a configuration field to BaseNodeStateMachineConfig:

pub struct BaseNodeStateMachineConfig {
    // ... existing fields ...
+   /// Timeout duration for waiting for DHT bootstrap events during startup
+   #[serde(with = "serializers::seconds")]
+   pub bootstrap_timeout: Duration,
}

Then use it here:

-let bootstrap_timeout = sleep(Duration::from_secs(120));
+let bootstrap_timeout = sleep(shared.config.bootstrap_timeout);
base_layer/core/src/base_node/state_machine_service/states/listening.rs (1)

211-214: Clarify the magic number in set_peer_metadata call.

The second parameter 1 in the set_peer_metadata call appears to be a magic number. Consider using a named constant or adding a comment to explain what this value represents.

-                        .set_peer_metadata(peer_metadata.node_id(), 1, peer_data.to_bytes())
+                        // The '1' represents the metadata type ID for chain metadata
+                        .set_peer_metadata(peer_metadata.node_id(), 1, peer_data.to_bytes())

Or better yet, define a constant:

+const CHAIN_METADATA_TYPE_ID: u8 = 1;
 // ... later in the code
-                        .set_peer_metadata(peer_metadata.node_id(), 1, peer_data.to_bytes())
+                        .set_peer_metadata(peer_metadata.node_id(), CHAIN_METADATA_TYPE_ID, peer_data.to_bytes())
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8253fae and eac44ff.

📒 Files selected for processing (4)
  • base_layer/core/src/base_node/state_machine_service/initializer.rs (3 hunks)
  • base_layer/core/src/base_node/state_machine_service/state_machine.rs (5 hunks)
  • base_layer/core/src/base_node/state_machine_service/states/listening.rs (1 hunks)
  • base_layer/core/src/base_node/state_machine_service/states/starting_state.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: test (testnet, esmeralda)
  • GitHub Check: cargo check with stable
  • GitHub Check: Cucumber tests / FFI
  • GitHub Check: Cucumber tests / Base Layer
🔇 Additional comments (11)
base_layer/core/src/base_node/state_machine_service/initializer.rs (6)

108-120: LGTM! Peer manager integration looks correct.

The peer manager is properly retrieved from the service handles and passed to the state machine constructor, enabling direct peer metadata management within the state machine.


28-28: LGTM: Clean import addition for peer manager integration.

The import of PeerManager from tari_comms is correctly added and aligns with the refactoring to integrate peer management into the state machine.


46-47: LGTM: Arc import added for thread-safe peer manager sharing.

The addition of std::sync::Arc import is appropriate for wrapping the PeerManager in a thread-safe reference counting pointer, which is consistent with the service architecture.


108-108: LGTM: Proper dependency injection of peer manager.

The retrieval of the Arc<PeerManager> handle from the service context follows the established pattern for dependency injection in this codebase. The use of expect_handle is appropriate here as the peer manager is a required dependency for the state machine.


113-113: LGTM: DHT handle retrieval maintained.

The DHT handle retrieval is preserved and correctly positioned in the initialization sequence.


119-120: LGTM: State machine constructor updated with peer manager dependency.

The addition of the peer_manager parameter to the BaseNodeStateMachine::new constructor call is well-integrated. The positioning between chain_metadata_service.get_event_stream() and dht.subscribe_dht_events() maintains logical grouping of service dependencies.

base_layer/core/src/base_node/state_machine_service/state_machine.rs (2)

94-94: LGTM! Peer manager field properly integrated.

The peer manager is correctly added as a field to the state machine struct with appropriate Arc wrapping for shared ownership.

Also applies to: 116-116, 131-131


316-316: Good change to reduce log noise.

Changing from warn! to debug! is appropriate here since updating the bootstrap flag outside the Listening state is a normal operational event, not a warning condition.

base_layer/core/src/base_node/state_machine_service/states/starting_state.rs (1)

62-101: Well-implemented async bootstrap event handling.

The use of tokio::select! with timeout provides robust handling of DHT bootstrap events. The logic correctly identifies bootstrap completion through either BootstrapMethodDetermined with "ExistingPeers" or PrimaryBootstrapComplete events, and properly handles lagged events.

base_layer/core/src/base_node/state_machine_service/states/listening.rs (2)

185-203: Good implementation of peer ban checking.

The code properly checks if a peer is banned before processing their metadata, with appropriate error handling for both banned peers and peer manager errors.


167-342: Excellent simplification of the event loop.

Removing DHT event handling from the listening state improves code clarity and separation of concerns. The listening state now focuses solely on chain metadata events, making it more maintainable and easier to understand.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Jun 3, 2025

Test Results (Integration tests)

0 tests   0 ✅  0s ⏱️
0 suites  0 💤
0 files    0 ❌

Results for commit bebb388.

♻️ This comment has been updated with latest results.

@github-actions
Copy link
Copy Markdown

github-actions bot commented Jun 3, 2025

Test Results (CI)

0 tests   0 ✅  0s ⏱️
0 suites  0 💤
0 files    0 ❌

Results for commit bebb388.

♻️ This comment has been updated with latest results.

Copy link
Copy Markdown
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: 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 eac44ff and 7900ffa.

📒 Files selected for processing (2)
  • base_layer/p2p/src/peer_seeds.rs (1 hunks)
  • comms/dht/src/rpc/peer_info.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • comms/dht/src/rpc/peer_info.rs
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: test (nextnet, nextnet)
  • GitHub Check: test (mainnet, stagenet)
  • GitHub Check: test (testnet, esmeralda)

@SWvheerden SWvheerden changed the title [wip]fix: the statemachine fix: the statemachine Jun 3, 2025
@SWvheerden SWvheerden force-pushed the sw_fix_state_machine branch from d9b3b18 to 5a15cd9 Compare June 3, 2025 14:25
@SWvheerden SWvheerden force-pushed the sw_fix_state_machine branch from 5a15cd9 to bebb388 Compare June 3, 2025 14:25
@SWvheerden SWvheerden merged commit ca6a03e into tari-project:development Jun 3, 2025
13 of 16 checks passed
@SWvheerden SWvheerden deleted the sw_fix_state_machine branch June 3, 2025 14:53
@coderabbitai coderabbitai bot mentioned this pull request Jun 4, 2025
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.

Base node states machines states are not correct

1 participant