Skip to content

Conversation

@KtorZ
Copy link
Contributor

@KtorZ KtorZ commented Apr 28, 2025

This makes the 'BlockValidation' a 3-variant enum, where Exception case reflects exceptional scenarii that aren't expected to occur as part of the normal operations.

Summary by CodeRabbit

  • New Features

    • Enhanced block validation with more flexible and expressive error handling, allowing for both domain-specific and generic errors.
    • Improved error context and propagation for block and header size validation.
  • Refactor

    • Unified success and error result types across validation functions for consistency.
    • Updated validation logic to return detailed invalid block information using option types.
    • Streamlined test cases to match new validation result patterns.
  • Chores

    • Updated dependencies for consistent workspace management.

…rror

  This makes the 'BlockValidation' a 3-variant enum, where the
  `Exception` case reflects exceptional scenarii that aren't expected to
  occur as part of the normal operations.

Signed-off-by: KtorZ <[email protected]>
@KtorZ KtorZ requested review from jeluard and yHSJ April 28, 2025 10:39
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 28, 2025

Walkthrough

Alrighty, here's the lowdown: The changes overhaul the block validation error handling in the ledger rules. The BlockValidation enum is now generic, supporting richer error types and carrying payloads for both valid and invalid results. Functions and tests are updated to use the new structure, returning unit types or propagating errors with context via anyhow. The control flow in the ledger stage is refactored to match on the new enum, cleanly separating generic errors from domain-specific invalid block details. Dependency management is also tweaked to use workspace settings for anyhow. No public APIs are removed, but signatures and error handling are more robust.

Changes

File(s) Change Summary
crates/amaru-ledger/Cargo.toml Added anyhow as a workspace dependency.
crates/amaru-ledger/src/rules.rs Updated test assertion to match BlockValidation::Valid(()) instead of BlockValidation::Valid.
crates/amaru-ledger/src/rules/block.rs Made BlockValidation generic, added error handling methods, implemented Try/Termination, updated execute function.
crates/amaru-ledger/src/rules/block/body_size.rs,
crates/amaru-ledger/src/rules/block/ex_units.rs
Made validation functions generic over error type, updated return types and test assertions to match new enum structure.
crates/amaru-ledger/src/rules/block/header_size.rs Removed InvalidBlockHeader, updated function to use BlockValidation<(), anyhow::Error>, added error context handling.
crates/amaru/src/stages/ledger.rs Refactored roll_forward to return Option<InvalidBlockDetails>, updated control flow to match on new enum variants.

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant ValidateBlockStage
    participant BlockValidation
    participant Store

    Worker->>ValidateBlockStage: roll_forward(point, raw_block)
    ValidateBlockStage->>BlockValidation: execute(raw_block)
    BlockValidation-->>ValidateBlockStage: Valid(()) / Invalid(details) / Err(error)
    ValidateBlockStage-->>Worker: Ok(None) / Ok(Some(details)) / Err(error)
    Worker->>Worker: Match on result
    alt Valid
        Worker->>Store: forward_state()
        Worker->>Worker: BlockValidated
    else Invalid
        Worker->>Worker: BlockValidationFailed
    else Err
        Worker->>Worker: propagate error
    end
Loading

Possibly related PRs

Suggested reviewers

  • jeluard

Poem

G'day, mate, the ledger's new,
With errors caught and handled true.
BlockValidation's now a star,
With context carried near and far.
No more panics, just clean flow,
Like Mario dodging every foe.
So raise a glass, the code's all right—
Another ledger bug takes flight! 🍻🦘

✨ 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 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
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: 3

🧹 Nitpick comments (2)
crates/amaru-ledger/src/rules/block.rs (1)

62-73: Nit: make bail & anyhow generic over impl Into<anyhow::Error>

Hand-rolling two helpers that ultimately wrap anyhow::Error is grand, but we can shave a yak here:

-pub fn bail(msg: String) -> Self {
-    BlockValidation::Err(anyhow::Error::msg(msg))
+pub fn bail<M: Into<anyhow::Error>>(msg: M) -> Self {
+    BlockValidation::Err(msg.into())
 }

Keeps call-sites ergonomic (bail("oops")) and avoids the mandatory to_string() dance.

crates/amaru-ledger/src/rules/block/ex_units.rs (1)

19-23: Unused generic E looks like cargo culting

The function never returns BlockValidation::Err(E), so the type parameter is effectively dead weight here.
Either:

  1. Remove the generic and fix the callers, or
  2. Add an early-exit path that can actually yield an Err(E) (e.g., by parameterising the fold or the protocol lookup).

Leaning option-1 unless you’ve a concrete plan for exotic error flavours down the track.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ed1b02 and 2847280.

⛔ Files ignored due to path filters (1)
  • Cargo.lock is excluded by !**/*.lock
📒 Files selected for processing (7)
  • crates/amaru-ledger/Cargo.toml (1 hunks)
  • crates/amaru-ledger/src/rules.rs (1 hunks)
  • crates/amaru-ledger/src/rules/block.rs (5 hunks)
  • crates/amaru-ledger/src/rules/block/body_size.rs (4 hunks)
  • crates/amaru-ledger/src/rules/block/ex_units.rs (3 hunks)
  • crates/amaru-ledger/src/rules/block/header_size.rs (2 hunks)
  • crates/amaru/src/stages/ledger.rs (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
crates/amaru-ledger/src/rules/block/body_size.rs (1)
crates/amaru-ledger/src/rules/block.rs (1)
  • anyhow (67-72)
crates/amaru-ledger/src/rules/block/header_size.rs (1)
crates/amaru-ledger/src/rules/block.rs (1)
  • anyhow (67-72)
crates/amaru-ledger/src/rules/block/ex_units.rs (1)
crates/amaru-kernel/src/lib.rs (2)
  • ex_units (745-745)
  • ex_units (749-755)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Build on windows-latest with target x86_64-pc-windows-msvc
  • GitHub Check: Build on ubuntu-latest with target riscv32im-risc0-zkvm-elf
  • GitHub Check: Snapshots (preprod, 10.1.4)
  • GitHub Check: Build on ubuntu-24.04 with target aarch64-unknown-linux-musl
  • GitHub Check: coverage
🔇 Additional comments (11)
crates/amaru-ledger/Cargo.toml (1)

21-21: Crikey! Adding anyhow for error handling - good stuff!

Adding anyhow as a workspace dependency to streamline error handling. This supports the overall PR objective of promoting 'UncategorizedError' to a top-level anyhow::Error.

crates/amaru-ledger/src/rules.rs (1)

184-184: Updating test assertions to match the new generic BlockValidation - beauty!

The test now properly checks for BlockValidation::Valid(()) pattern which matches the updated return type of the validate_block function. This aligns with the generic BlockValidation<A, E> structure that carries a payload in the Valid variant.

crates/amaru-ledger/src/rules/block/body_size.rs (5)

21-21: Leveled up the function signature like a proper RPG character!

Updated the function signature to be generic over error type E, returning BlockValidation<(), E> instead of the previous non-generic type. This aligns with the PR's goal of promoting better error handling.


32-33: Clean return value with unit type - no worries!

Updated to return BlockValidation::Valid(()) with the unit value to match the new generic type structure. Spot on!


51-52: Updated imports to match the new structure - fair dinkum!

Direct import of BlockValidation keeps the code clean and consistent with other modules.


65-68: Test case matcher updated like a well-oiled machine!

Updated test case matcher to handle the new BlockValidation structure. The pattern matching looks great with the proper destructuring of the InvalidBlockDetails variant.


69-71: Test function return type alignment - that's the ticket!

Updated the test function to explicitly return BlockValidation<(), anyhow::Error>, matching the function's new signature. This keeps your tests in sync with your implementation - as balanced as perfectly matched health and mana bars!

crates/amaru-ledger/src/rules/block/header_size.rs (4)

22-22: Return type update with anyhow::Error - absolute ripper!

Changed the return type from the non-generic BlockValidation to BlockValidation<(), anyhow::Error>, aligning with the improved error handling approach. This matches the PR's focus on using anyhow for better error context.


26-27: Proper error propagation with context - like a well-constructed quest line!

These changes refine the error handling by:

  1. Using map(BlockValidation::Valid) for successful conversion
  2. Using unwrap_or_else with BlockValidation::anyhow(e) and .context() to provide rich error information
  3. Using the ? operator for error propagation

This gives exceptional error handling - better than the shields in Dune!


35-36: Updated return value to match generic structure - deadly!

Now returning BlockValidation::Valid(()) with the unit type to match the generic type parameter. Consistent with the changes in other validation functions.


56-57: Updated test assertion to match the new Valid variant - you beauty!

Test now correctly asserts against BlockValidation::Valid(()) with the unit payload, aligning with the updated enum structure. Keeping your tests in line like a proper formation in Final Fantasy Tactics!

Comment on lines +74 to +82
pub fn context<C>(self, context: C) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
{
match self {
BlockValidation::Err(err) => BlockValidation::Err(err.context(context)),
BlockValidation::Invalid { .. } | BlockValidation::Valid { .. } => self,
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Bracket-vs-Brace mix-up breaks pattern matching, chief

You’re pattern-matching tuple variants with struct syntax ({ … }).
That’ll make the compiler spit the dummy and the build will stop dead in its tracks, long before we can yell “It’s over 9000!”.

-            BlockValidation::Err(err) => BlockValidation::Err(err.context(context)),
-            BlockValidation::Invalid { .. } | BlockValidation::Valid { .. } => self,
+            BlockValidation::Err(err) => BlockValidation::Err(err.context(context)),
+            BlockValidation::Invalid(_) | BlockValidation::Valid(_) => self,

Same salad sneaks in a few lines below (see Termination impl).
Swap the braces for parentheses wherever you’re matching on Valid or Invalid.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn context<C>(self, context: C) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
{
match self {
BlockValidation::Err(err) => BlockValidation::Err(err.context(context)),
BlockValidation::Invalid { .. } | BlockValidation::Valid { .. } => self,
}
}
pub fn context<C>(self, context: C) -> Self
where
C: std::fmt::Display + Send + Sync + 'static,
{
match self {
BlockValidation::Err(err) => BlockValidation::Err(err.context(context)),
BlockValidation::Invalid(_) | BlockValidation::Valid(_) => self,
}
}

Comment on lines +86 to 90
fn report(self) -> ExitCode {
match self {
BlockValidation::Valid => ControlFlow::Continue(()),
BlockValidation::Invalid(e) => ControlFlow::Break(e),
Self::Valid { .. } => ExitCode::SUCCESS,
Self::Invalid { .. } | Self::Err { .. } => ExitCode::FAILURE,
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Termination impl suffers the same brace-itis

Second verse, same as the first – tuple variants need “( … )”, not “{ … }”.

-            Self::Valid { .. } => ExitCode::SUCCESS,
-            Self::Invalid { .. } | Self::Err { .. } => ExitCode::FAILURE,
+            Self::Valid(_) => ExitCode::SUCCESS,
+            Self::Invalid(_) | Self::Err(_) => ExitCode::FAILURE,

Without this, cargo check will rage-quit faster than you can say “mate, where’s my stubby”.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
fn report(self) -> ExitCode {
match self {
BlockValidation::Valid => ControlFlow::Continue(()),
BlockValidation::Invalid(e) => ControlFlow::Break(e),
Self::Valid { .. } => ExitCode::SUCCESS,
Self::Invalid { .. } | Self::Err { .. } => ExitCode::FAILURE,
}
fn report(self) -> ExitCode {
match self {
Self::Valid(_) => ExitCode::SUCCESS,
Self::Invalid(_) | Self::Err(_) => ExitCode::FAILURE,
}

Comment on lines +170 to 176
None => BlockValidationResult::BlockValidated {
point: point.clone(),
span: restore_span(span),
},
Some(_err) => BlockValidationResult::BlockValidationFailed {
point: point.clone(),
span: restore_span(span),
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

We’re losing the juicy error details on the cutting-room floor

Some(_err) gets mapped to BlockValidationFailed, but the actual InvalidBlockDetails vanish into the void.
If downstream consumers ever want to surface what went wrong (UX, metrics, tracing), we’ll be left scratching our heads.

Consider piping the details through:

-                    Some(_err) => BlockValidationResult::BlockValidationFailed {
-                        point: point.clone(),
-                        span: restore_span(span),
-                    },
+                    Some(details) => BlockValidationResult::BlockValidationFailed {
+                        point: point.clone(),
+                        span: restore_span(span),
+                        // new field? or wrap `details` in the enum variant
+                        details,
+                    },

Naturally this means tweaking BlockValidationResult and any callers, but future-you will thank present-you when the dashboard lights up.

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

@yHSJ
Copy link
Contributor

yHSJ commented Apr 28, 2025

Thank you for making this change! I really do think this is much nicer to consume for the call site and clearly communicates the intention. Not sure why that test is failing in the coverage CI run though 😛

@KtorZ
Copy link
Contributor Author

KtorZ commented Apr 28, 2025

Not sure why that test is failing in the coverage CI run though

I have no idea either 😅 ... and it's slightly worrying that it fails on the coverage but not on the classic ones.

}
}

impl<A, E> Termination for BlockValidation<A, E> {
Copy link
Contributor

Choose a reason for hiding this comment

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

This is only useful for the tests? Termination semantic is A trait for implementing arbitrary return types in the main function. so feels a bit unnatural to have it implemented at the BlockValidation level?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Indeed, this is used to satisfy some of the test code.

Although, I don't think the semantic is particularly weird here. On the contrary.

.try_into()
.unwrap_or_else(|_| panic!("Failed to convert u32 to usize"));
.map(BlockValidation::Valid)
.unwrap_or_else(|e| BlockValidation::anyhow(e).context("failed to convert u32 to usize"))?;
Copy link
Contributor

Choose a reason for hiding this comment

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

With a proper error type we wouldn't need to use anyhow here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, but those are exceptions; and I don't think we really care to turn them into user facing errors.

So it seems to be a perfect use case for anyhow?

None => {
return BlockValidation::Invalid(InvalidBlockDetails::UncategorizedError(format!(
// TODO: Define a proper error for this.
return BlockValidation::bail(format!(
Copy link
Contributor

Choose a reason for hiding this comment

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

If we had a proper error here there wouldn't be a need for anyhow at all?

@jeluard jeluard self-requested a review April 28, 2025 14:22
@jeluard
Copy link
Contributor

jeluard commented Apr 28, 2025

I've seen this failure happen sporadically on windows too. Not sure why this test would be flaky.

@codecov
Copy link

codecov bot commented Apr 28, 2025

Codecov Report

Attention: Patch coverage is 53.44828% with 27 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/amaru-ledger/src/rules/block.rs 29.03% 22 Missing ⚠️
crates/amaru/src/stages/ledger.rs 0.00% 5 Missing ⚠️
Files with missing lines Coverage Δ
crates/amaru-ledger/src/rules.rs 90.74% <100.00%> (ø)
crates/amaru-ledger/src/rules/block/body_size.rs 100.00% <100.00%> (ø)
crates/amaru-ledger/src/rules/block/ex_units.rs 100.00% <100.00%> (ø)
crates/amaru-ledger/src/rules/block/header_size.rs 100.00% <100.00%> (ø)
crates/amaru/src/stages/ledger.rs 0.00% <0.00%> (ø)
crates/amaru-ledger/src/rules/block.rs 30.95% <29.03%> (-28.14%) ⬇️

... and 1 file with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jeluard jeluard merged commit e6bfb24 into main Apr 28, 2025
22 of 23 checks passed
@jeluard jeluard deleted the 3-variant-block-validations branch April 28, 2025 14:40
@coderabbitai coderabbitai bot mentioned this pull request Sep 26, 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.

4 participants