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

feat(katana): start block timer only if there txs #2950

Merged
merged 3 commits into from
Jan 24, 2025
Merged

Conversation

kariy
Copy link
Member

@kariy kariy commented Jan 24, 2025

Only start the block interval timer when we have executed txs. This means we no longer produce empty blocks after every fixed interval.

Summary by CodeRabbit

Release Notes

  • New Dependencies

    • Added arbitrary and rand as development dependencies
  • Backend Improvements

    • Enhanced Backend struct flexibility
    • Added new constructor method for easier initialization
  • Block Producer Updates

    • Renamed interval to block_time for clarity
    • Added timer management for more precise block production
  • Testing

    • Introduced comprehensive test suite for block producer functionality
    • Added test cases for initial state, force mining, and timed mining scenarios

Copy link

codecov bot commented Jan 24, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 56.70%. Comparing base (7788827) to head (e0b132b).
Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2950      +/-   ##
==========================================
+ Coverage   56.55%   56.70%   +0.14%     
==========================================
  Files         419      420       +1     
  Lines       55475    55554      +79     
==========================================
+ Hits        31376    31502     +126     
+ Misses      24099    24052      -47     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@tarrencev
Copy link
Contributor

LFG

@kariy kariy marked this pull request as ready for review January 24, 2025 20:43
Copy link

coderabbitai bot commented Jan 24, 2025

Walkthrough

Ohayo, sensei! This pull request introduces enhancements to the Katana core crate, focusing on improving the block producer functionality and test coverage. The changes include adding dev dependencies, refactoring the Backend struct to be more flexible, modifying the IntervalBlockProducer, and creating comprehensive test cases for block production mechanisms.

Changes

File Changes
crates/katana/core/Cargo.toml Added dev dependencies: arbitrary and rand with workspace = true
crates/katana/core/src/backend/mod.rs - Simplified Backend struct generic parameter
- Added new new() constructor method
crates/katana/core/src/service/block_producer.rs - Renamed interval to block_time
- Added timer field
- Updated constructor and poll_next method
crates/katana/core/src/service/block_producer_tests.rs - Added test backend helper function
- Introduced three new test functions
- Created dummy_transaction() helper

Sequence Diagram

sequenceDiagram
    participant BP as BlockProducer
    participant Backend as Backend
    participant Blockchain as Blockchain

    BP->>Backend: new(chain_spec, blockchain, gas_oracle, executor_factory)
    Backend-->>BP: Backend Instance
    BP->>BP: Initialize timer
    alt Transactions Queued
        BP->>Blockchain: Mine Block
        Blockchain-->>BP: Block Mined
    end
Loading

Possibly related PRs


🪧 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.

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

🧹 Nitpick comments (5)
crates/katana/core/src/service/block_producer_tests.rs (2)

34-43: Ohayo sensei! Validate forced mining preconditions.

While interval_force_mine_without_transactions ensures a new block is mined with no pending TXs, consider verifying that no leftover TXs from previous states or partial executions would interfere.


45-70: Ohayo sensei! Great coverage of timed mining logic.

The interval_mine_after_timer test effectively verifies the timer-based block production after queuing a transaction and waiting. Consider adding multi-transaction scenarios or random intervals to further validate concurrency.

crates/katana/core/src/backend/mod.rs (1)

49-64: Ohayo sensei! Nice addition of a dedicated constructor.

The Backend::new method cleans up initialization usage nicely. However, ensure any partial logics or side effects (like forcibly updating block_context_generator) are tested consistently.

crates/katana/core/src/service/block_producer.rs (2)

Line range hint 219-243: Ohayo sensei! The factory-based initialization is well-structured.

The IntervalBlockProducer::new method keeps the code DRY by reusing backend dependencies. If you anticipate more advanced block-time scheduling logic, consider splitting the environment update steps into a separate helper function for clarity.


Line range hint 394-434: Ohayo sensei! Thorough state machine for timer + execution + mining.

The loop ensures queued transactions are processed before starting the timer, and the timer triggers block mining only if no mining is ongoing. Consider adding logs when the timer is re-queued (lines 404-406) to aid debugging.

+ tracing::debug!(target: LOG_TARGET, "Timer re-queued because mining is ongoing.");
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7788827 and e0b132b.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (4)
  • crates/katana/core/Cargo.toml (1 hunks)
  • crates/katana/core/src/backend/mod.rs (2 hunks)
  • crates/katana/core/src/service/block_producer.rs (6 hunks)
  • crates/katana/core/src/service/block_producer_tests.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: fmt
🔇 Additional comments (8)
crates/katana/core/src/service/block_producer_tests.rs (3)

14-21: Ohayo sensei! Good test environment setup.

The test_backend helper function nicely encapsulates the ephemeral DB and NoopExecutorFactory creation. This approach ensures an isolated test environment without side effects.


23-32: Ohayo sensei! Consider verifying timer behavior even if interval is set.

Although interval_initial_state checks that producer.timer is None, it might be worth adding a scenario to confirm that if an interval value is specified (e.g., Some(1000)), no timer is actually started without transactions.


72-81: Ohayo sensei! Random transaction generation is neat.

dummy_transaction cleverly uses arbitrary for test coverage. If collisions or reproducibility are crucial, consider seeding randomness for repeatable results.

crates/katana/core/src/backend/mod.rs (1)

37-37: Ohayo sensei! Simplified generic bound fosters code flexibility.

Removing EF: ExecutorFactory constraints from the Backend struct signature broadens usage possibilities for custom executors. Ensure thorough type constraints remain in internal methods.

crates/katana/core/src/service/block_producer.rs (3)

31-34: Ohayo sensei! Kudos for extracting tests into a separate module.

Isolating tests into block_producer_tests.rs helps maintain readability: less clutter in the main file. The #[cfg(test)] usage is straightforward.


188-193: Ohayo sensei! Clarify block-time usage.

The block_time field now only starts the timer after at least one transaction arrives, preventing empty blocks. This is consistent with the PR’s objective of avoiding empty blocks.


211-215: Ohayo sensei! Great doc comment for timer logic.

Documenting the timer field’s conditions clarifies usage. This ensures future maintainers know exactly when the producer’s interval-based block production is active.

crates/katana/core/Cargo.toml (1)

49-52: Ohayo sensei! Additional dev dependencies look good.

Adding arbitrary and rand as dev-dependencies helps with generating more robust tests. Consider pinning minor versions if test determinism becomes critical.

@@ -194,23 +202,21 @@ pub struct IntervalBlockProducer<EF: ExecutorFactory> {
/// Listeners notified when a new executed tx is added.
tx_execution_listeners: RwLock<Vec<Sender<Vec<TxWithOutcome>>>>,

// Usage with `validator`
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Ohayo sensei! Revisit raw unlock usage.

There's an unsafe { self.permit.raw().unlock() }; call. Using raw lock/unlock can risk deadlocks or inconsistent states if not carefully managed. Review if higher-level parking_lot patterns suffice.

- unsafe { self.permit.raw().unlock() };
+ // Consider a more idiomatic .lock() in a smaller scope,
+ // or rely on RAII to avoid manual unlocks.

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

@kariy kariy merged commit 2050c4e into main Jan 24, 2025
15 checks passed
@kariy kariy deleted the katana/interval-mining branch January 24, 2025 21:30
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