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

fix(katana): unbound call execution from the block context limit #3026

Merged
merged 3 commits into from
Feb 13, 2025

Conversation

kariy
Copy link
Member

@kariy kariy commented Feb 13, 2025

Summary by CodeRabbit

  • New Features

    • Introduced a new contract package with advanced workspace configuration supporting multiple compilation targets.
    • Added a contract module providing bounded operations for testing and executing contract calls.
    • Enhanced contract call execution with dynamic gas management and improved error handling.
    • Added a new JSON structure to facilitate interaction with the contract and provide necessary metadata.
  • Refactor & Cleanup

    • Updated internal data structures for improved object handling.
    • Removed outdated utility functions to streamline execution flows.
  • Tests

    • Upgraded test fixtures and environment settings to accommodate extended recursion and validation limits.

Copy link

coderabbitai bot commented Feb 13, 2025

Ohayo, sensei! Here's the updated breakdown of the changes:

Walkthrough

This pull request updates the workspace configuration by adding a new member and introduces a new package for miscellaneous contracts. It adds a new Cairo module with a StarkNet contract, updates the executor to support cloning of call entities, and enhances contract call execution with dynamic gas management. The changes also remove a deprecated function from the utils module and update test fixtures for broader limits.

Changes

File(s) or Path Summary
crates/katana/contracts/Scarb.toml
crates/katana/contracts/misc/Scarb.toml
Updated workspace configuration: added "misc" to the members array and introduced a new package configuration (katana_misc) with workspace dependencies and target settings.
crates/katana/contracts/misc/src/lib.cairo Added a new module CallTest with an empty storage struct and an external function bounded_call that implements a loop based on an iterations parameter.
crates/katana/executor/src/abstraction/mod.rs Updated the EntryPointCall struct to derive Clone in addition to Debug.
crates/katana/executor/src/implementation/blockifier/call.rs
crates/katana/executor/src/implementation/blockifier/mod.rs
Added new functions execute_call and execute_call_inner for dynamic contract call execution, and modified the call method to use the updated call execution logic.
crates/katana/executor/src/implementation/blockifier/utils.rs Removed the deprecated call function and cleaned up unused imports, shifting call logic handling.
crates/katana/executor/tests/fixtures/call_test.json
crates/katana/executor/tests/fixtures/mod.rs
Added a new JSON fixture for the Sierra program and updated test configuration (CfgEnv) to use maximum values for recursion depth and step counts.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant E as Executor
    participant CS as CachedState
    participant BC as BlockContext
    participant CEP as CallEntryPoint

    C->>E: execute_call(request, state, block_context, max_gas)
    E->>CS: Initialize CachedState from state
    E->>BC: Pass block context and gas info
    E->>CEP: Prepare CallEntryPoint with calldata and selector
    CEP-->>E: Return execution info (CallInfo)
    E-->>C: Return result data from execute_call
Loading

Possibly related PRs

  • Convert katana/contracts into a Scarb workspace #2523: The changes in the main PR, which add a new member to the members array in the Scarb.toml file, are related to the changes in the retrieved PR that also modify the Scarb.toml file to establish a workspace configuration, as both involve updates to the same file structure.

Hope that helps, sensei!


🪧 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: 0

🧹 Nitpick comments (4)
crates/katana/executor/src/implementation/blockifier/call.rs (2)

31-69: Ohayo sensei, watch out for potential overflow issues when casting to usize.

On certain 32-bit architectures, converting max_gas from u64 to usize might lead to overflow. Consider adding a safety check or capping the gas to usize::MAX before creating the RunResources.

 fn execute_call_inner<S: StateReader>(
     request: EntryPointCall,
     state: &mut CachedState<S>,
     block_context: &BlockContext,
     max_gas: u64,
 ) -> EntryPointExecutionResult<CallInfo> {
     ...
-    ctx.vm_run_resources = RunResources::new(max_gas as usize);
+    let run_gas = if max_gas as usize as u64 == max_gas {
+        max_gas as usize
+    } else {
+        usize::MAX
+    };
+    ctx.vm_run_resources = RunResources::new(run_gas);
     ...
 }

71-162: Ohayo sensei, consider parameterizing your test cases.

Your max_steps test is thorough, but you could reduce repetition by adapting a table-driven approach to test different iteration values, improving readability.

crates/katana/executor/src/abstraction/mod.rs (1)

106-106: Ohayo sensei, deriving Clone may be handy but ensure it's necessary.

If EntryPointCall grows large in future, cloning might be expensive. Consider referencing slices in downstream calls when possible.

crates/katana/executor/src/implementation/blockifier/mod.rs (1)

332-332: Consider making the gas limit configurable.

The hard-coded gas limit of 1_000_000_000 should ideally be configurable through the environment or configuration settings.

Consider introducing a configuration parameter for this value:

-        let retdata = call::execute_call(call, state, block_context, 1_000_000_000)?;
+        let retdata = call::execute_call(call, state, block_context, self.cfg.max_call_gas)?;
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 596f96d and 564ef9d.

⛔ Files ignored due to path filters (1)
  • crates/katana/contracts/Scarb.lock is excluded by !**/*.lock
📒 Files selected for processing (9)
  • crates/katana/contracts/Scarb.toml (1 hunks)
  • crates/katana/contracts/misc/Scarb.toml (1 hunks)
  • crates/katana/contracts/misc/src/lib.cairo (1 hunks)
  • crates/katana/executor/src/abstraction/mod.rs (1 hunks)
  • crates/katana/executor/src/implementation/blockifier/call.rs (1 hunks)
  • crates/katana/executor/src/implementation/blockifier/mod.rs (2 hunks)
  • crates/katana/executor/src/implementation/blockifier/utils.rs (3 hunks)
  • crates/katana/executor/tests/fixtures/call_test.json (1 hunks)
  • crates/katana/executor/tests/fixtures/mod.rs (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • crates/katana/contracts/misc/Scarb.toml
🔇 Additional comments (10)
crates/katana/executor/src/implementation/blockifier/call.rs (1)

19-29: Ohayo sensei, nice approach to returning the contract call results!

The API is concise and straightforward. The direct usage of the returned retdata vector is helpful for immediate consumption in higher-level code.

crates/katana/contracts/misc/src/lib.cairo (1)

1-17: Ohayo sensei, your bounded loop logic is straightforward!

This simple counter increment loop cleanly demonstrates controllable step consumption for testing. No issues found.

crates/katana/executor/tests/fixtures/mod.rs (1)

241-243: Ohayo! Consider the implications of using MAX values in test configuration.

Setting these limits to their maximum values could potentially mask issues that would occur with more realistic limits in production environments.

Could you confirm if these changes are intentional for testing purposes only? We should ensure that production configurations maintain appropriate bounds.

crates/katana/executor/src/implementation/blockifier/mod.rs (1)

5-5: LGTM! New module organization looks clean, sensei.

Good separation of concerns by moving call-related functionality to its own module.

crates/katana/executor/src/implementation/blockifier/utils.rs (1)

7-7: Clean import organization, sensei!

The import cleanup and reorganization improves code maintainability.

Also applies to: 14-14, 19-19

crates/katana/contracts/Scarb.toml (1)

2-2: LGTM! Workspace member addition looks good.

The addition of the "misc" member follows the standard workspace structure.

crates/katana/executor/tests/fixtures/call_test.json (4)

358-364: Ohayo! The contract interface looks clean and focused, sensei!

The bounded_call function has a clear purpose with appropriate parameter type and view mutability.


19-22: Excellent error handling implementation, sensei!

The program includes comprehensive error messages for critical scenarios:

  • Arithmetic overflow protection
  • Deserialization safety
  • Gas exhaustion handling

247-249: Robust gas management implementation, sensei!

The program includes comprehensive gas operations:

  • Granular gas withdrawal
  • Full gas withdrawal
  • Built-in cost tracking

Also applies to: 299-299, 301-301


347-356: Clean entry points configuration, sensei!

The configuration is minimal yet complete with a properly defined external function selector.

Copy link

codecov bot commented Feb 13, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 56.34%. Comparing base (c60392a) to head (886ac5c).
Report is 4 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3026      +/-   ##
==========================================
+ Coverage   56.23%   56.34%   +0.10%     
==========================================
  Files         436      437       +1     
  Lines       58829    58891      +62     
==========================================
+ Hits        33083    33181      +98     
+ Misses      25746    25710      -36     

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

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

🧹 Nitpick comments (2)
crates/katana/executor/src/implementation/blockifier/call.rs (2)

69-69: Ohayo sensei, consider protective casting!
Using max_gas as usize could be problematic if max_gas exceeds the platform’s usize::MAX. A more defensive approach—such as usize::try_from(max_gas)—may prevent overflow.

-    ctx.vm_run_resources = RunResources::new(max_gas as usize);
+    let bounded_gas = usize::try_from(max_gas)
+        .unwrap_or_else(|_| usize::max_value());
+    ctx.vm_run_resources = RunResources::new(bounded_gas);

73-166: Ohayo sensei, comprehensive test coverage—consider boundary tests!
The max_steps test suite thoroughly checks various gas limits. As an extra safeguard, you might include edge cases like extremely small “0 gas” or extremely large gas settings if relevant for your application.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 564ef9d and 6d3ec56.

📒 Files selected for processing (1)
  • crates/katana/executor/src/implementation/blockifier/call.rs (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: clippy
  • GitHub Check: docs
  • GitHub Check: ensure-wasm
🔇 Additional comments (2)
crates/katana/executor/src/implementation/blockifier/call.rs (2)

19-29: Ohayo sensei, this public interface looks well-structured!
The execute_call function neatly delegates implementation details to execute_call_inner, keeping the interface clean.


31-43: Ohayo sensei, cautiously verify default fields!
When using ..Default::default() in CallEntryPoint, ensure all defaulted fields (like class_hash, entry_point_type, etc.) behave correctly. If any defaulted field must be explicitly set, missing it may cause unexpected behavior downstream.

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

🧹 Nitpick comments (2)
crates/katana/executor/src/implementation/blockifier/call.rs (2)

31-71: Consider adding documentation for the inner function, sensei.

While the implementation is solid, adding documentation for execute_call_inner would help explain:

  • The relationship between max_gas and block context limits
  • The manual override of run resources
  • The significance of limit_steps_by_resources

The implementation correctly handles gas limits and execution context. The comments explaining the block context relationship are particularly helpful.


90-164: Excellent test coverage, sensei! Consider a few enhancements.

The test implementation thoroughly verifies gas consumption and limits. A few suggestions to make it even better:

  1. Consider extracting magic numbers into named constants for better readability:
-        let max_gas_1 = 1_000_000;
+        const LOW_GAS_LIMIT: u64 = 1_000_000;
+        let max_gas_1 = LOW_GAS_LIMIT;
  1. Add test cases for edge cases:
    • Zero gas limit
    • Maximum possible gas limit
    • Gas limit exactly at block context limit

The test implementation effectively validates:

  • Gas consumption tracking
  • Resource exhaustion handling
  • Block context independence
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6d3ec56 and 886ac5c.

📒 Files selected for processing (1)
  • crates/katana/executor/src/implementation/blockifier/call.rs (1 hunks)
🔇 Additional comments (1)
crates/katana/executor/src/implementation/blockifier/call.rs (1)

19-29: Ohayo! The public interface looks clean, sensei!

The execute_call function provides a clean interface for contract calls with proper state management and error handling.

@kariy kariy merged commit 6c74cd5 into main Feb 13, 2025
15 checks passed
@kariy kariy deleted the katana/fix-call-gas-upper-bound branch February 13, 2025 20:15
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.

1 participant