8000 feat: do not panic when block validation fails by jeluard · Pull Request #259 · pragma-org/amaru · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat: do not panic when block validation fails #259

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 2 commits into from
Jun 13, 2025

Conversation

jeluard
Copy link
Contributor
@jeluard jeluard commented Jun 12, 2025

Let amaru continue validating after a block validation fails.

This currently does not work and still panics higher up in the stack due to a mishandling in the consensus layer. This will be addressed in a subsequent PR.

Summary by CodeRabbit

  • Bug Fixes

    • Improved error handling and logging during block validation to provide clearer feedback when issues occur.
    • Enhanced log output formatting for hash values to aid in debugging.
  • Refactor

    • Streamlined control flow for block validation processes, making error handling more explicit and robust.

jeluard added 2 commits June 11, 2025 20:29
Signed-off-by: jeluard <jeluard@users.noreply.github.com>
Signed-off-by: jeluard <jeluard@users.noreply.github.com>
Copy link
Contributor
coderabbitai bot commented Jun 12, 2025

Walkthrough

This update tweaks error handling and logging in the consensus forward chain and ledger stages. It changes how hash values are shown in logs, simplifies error propagation, and improves explicitness in control flow by matching on results and logging errors directly instead of panicking.

Changes

File(s) Change Summary
crates/amaru/src/stages/consensus/forward_chain.rs Changed hash logging in error branch from display to debug format in the execute method.
crates/amaru/src/stages/ledger.rs Simplified error handling in roll_forward and execute; replaced panic with error logging.

Sequence Diagram(s)

sequenceDiagram
    participant Worker
    participant Ledger

    Worker->>Ledger: roll_forward(block)
    alt roll_forward returns Ok(None)
        Worker-->>Worker: return BlockValidated
    else roll_forward returns Ok(Some(err))
        Worker-->>Worker: return BlockValidationFailed
    else roll_forward returns Err(err)
        Worker->>Worker: log error
        Worker-->>Worker: return BlockValidationFailed
    end
Loading

Possibly related PRs

Suggested reviewers

  • KtorZ

Poem

In the land of logs and hashes,
Where panics once would roam,
Now errors get a gentle nudge,
And hashes call debug home.
With clearer flows and tidier code,
We’re rolling forward, mate—onward we goad!
🍀🦘

✨ 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
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 (2)
crates/amaru/src/stages/ledger.rs (2)

115-118: Missing telemetry of why a block is invalid

You now bubble BlockValidation::Invalid up as Ok(Some(err)), but the caller fully discards err, leaving us none-the-wiser about which rule tripped. A single tracing::warn!(?err, …) right here would give ops folk the clue-bat they need without re-plumbing types downstream.

-    BlockValidation::Invalid(err) => Ok(Some(err)),
+    BlockValidation::Invalid(err) => {
+        tracing::warn!(?err, "block failed ledger rules");
+        Ok(Some(err))
+    },

175-187: Early clones chew memory like Pac-Man – only clone when you know you need ’em

point.clone() and block.to_vec() happen before we know the verdict. For most invalid blocks that’s wasted alloc work. Shuffle the cloning inside each branch and you’ll spare a few cycles per block – not earth-shattering, but every frame counts when you’re chasing 60 fps.

-            ValidateBlockEvent::Validated { point, block, span } => {
-                let point = point.clone();
-                let block = block.to_vec();
+            ValidateBlockEvent::Validated { point, block, span } => {
                 let span = restore_span(span);

-                match stage.roll_forward(point.clone(), block.clone()) {
-                    Ok(None) => BlockValidationResult::BlockValidated { point, block, span },
-                    Ok(Some(_)) => BlockValidationResult::BlockValidationFailed { point, span },
+                match stage.roll_forward(point.clone(), block.to_vec()) {
+                    Ok(None) => BlockValidationResult::BlockValidated {
+                        point: point.clone(),
+                        block: block.to_vec(),
+                        span,
+                    },
+                    Ok(Some(_)) => BlockValidationResult::BlockValidationFailed { point: point.clone(), span },
                     Err(err) => {
                         error!(?err, "Failed to validate block");
                         BlockValidationResult::BlockValidationFailed { point: point.clone(), span }
                     }
                 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8b8c09b and 07abcb1.

📒 Files selected for processing (2)
  • crates/amaru/src/stages/consensus/forward_chain.rs (1 hunks)
  • crates/amaru/src/stages/ledger.rs (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Coverage
  • GitHub Check: Build on ubuntu-latest with target riscv32im-risc0-zkvm-elf
  • GitHub Check: Snapshots (preprod, 10.1.4)
  • GitHub Check: Simulation
  • GitHub Check: Build on ubuntu-latest with target x86_64-unknown-linux-gnu
  • GitHub Check: Build on ubuntu-latest with target wasm32-unknown-unknown
  • GitHub Check: Build on windows-latest with target x86_64-pc-windows-msvc
  • GitHub Check: Build on ubuntu-latest with target aarch64-unknown-linux-musl
  • GitHub Check: Build on macos-latest with target aarch64-apple-darwin
  • GitHub Check: Sanity
🔇 Additional comments (1)
crates/amaru/src/stages/consensus/forward_chain.rs (1)

318-323: Sweet catch swapping to {:?} – avoids a compile-time face-plant

Switching to the debug formatter removes the need for an explicit Display impl on Hash<32>, neatly dodging the old “doesn’t implement fmt::Display” panic-fest. Logs still print the hex thanks to Debug on Hash, so we keep human-readability.

No further action from me; log on, mate.

Copy link
codecov bot commented Jun 12, 2025

Codecov Report

Attention: Patch coverage is 0% with 12 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/amaru/src/stages/ledger.rs 0.00% 11 Missing ⚠️
crates/amaru/src/stages/consensus/forward_chain.rs 0.00% 1 Missing ⚠️
Files with missing lines Coverage Δ
crates/amaru/src/stages/consensus/forward_chain.rs 72.08% <0.00%> (ø)
crates/amaru/src/stages/ledger.rs 35.29% <0.00%> (+1.20%) ⬆️

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

@yHSJ
Copy link
Contributor
yHSJ commented Jun 12, 2025

Great, thank you! For now, while we're receiving invalid blocks from upstream (trusted) peers, we know that something is wrong with our logic. But once we're connected to unknown peers we'll have to handle this appropriately. This is one piece of that.

@abailly
Copy link
Contributor
abailly commented Jun 12, 2025

What we need to do in this case is to disconnect from the upstream peer which for all intents and purposes, in the current stage of the system, translates to crashing. What do you refer to

due to a mishandling in the consensus layer.

@jeluard
Copy link
Contributor Author
jeluard commented Jun 12, 2025

@abailly I refer to this panic: thread '<unnamed>' panicked at crates/amaru/src/stages/consensus/forward_chain.rs:270:21: that can be seen here. Might be more complex than that but amaru as a node should just continue processing new blocks even when invalid ones are received?

@yHSJ
Copy link
Contributor
yHSJ commented Jun 12, 2025

but amaru as a node should just continue processing new blocks even when invalid ones are received?

Yes, from the ledger perspective it should just continue processing blocks. There is consensus and networking things that have to occur, as Arnaud said, such as removing the peer. When we have a single peer, that is effectively stopping the process, so it's no different than the current situation. But I don't mind removing the panic and preparing for more robust logic. I don't know enough about the networking/consensus specs, so @abailly will be better for that side

@jeluard
Copy link
Contributor Author
jeluard commented Jun 12, 2025

@yHSJ right, I meant the consensus panic not the ledger one

@abailly
Copy link
Contributor
abailly commented Jun 12, 2025

Might be more complex than that but amaru as a node should just continue processing new blocks even when invalid ones are received?

Definitely! But as I said, the correct behaviour when a block is invalid is to assume the remote peer is adversarial and therefore to disconnect from it. In the current state of amaru this is exactly equivalent to crashing, because there's no more progress the node can make once disconnected from its one and only peer.

So do you suggest we just ignore block validation failures and assume we can proceed, at least until we add this disconnection behaviour?

@jeluard
Copy link
Contributor Author
jeluard commented Jun 12, 2025

In the absence of node rating and eventual subsequent disconnection I would assume we consider them honest. Thus amaru should keep accepting blocks from them?
If the node was disconnected amaru should just stay up, maybe with some special logs if there's no more peers?

The current error sounds a bit unrelated.

@abailly
Copy link
Contributor
abailly commented Jun 12, 2025

Once a block fails to validate, the tip of the chain is not updated and therefore all subsequent blocks will fail to validate isn't it? There's another issue in the chain_selection that we update the tip of our chain whether or not the block is valid which I am aware of and should be changed, but that won't solve the issue and would only make the chain stall earlier in the process.

@abailly
Copy link
Contributor
abailly commented Jun 12, 2025

As I said on discord, happy to discuss f2f if that helps

@jeluard
Copy link
Contributor Author
jeluard commented Jun 12, 2025

Right! I think it shouldn't crash amaru in this case and probably just log an infinite stream of errors. Happy to implement it as it's the idea behind this PR, just want to make sure this is the right error we hit and not a side-effect of not testing those scenarios. We probably should come up with a list of concrete criteria for which amaru should fail.
Let's discuss more next week then.

@abailly
Copy link
Contributor
abailly commented Jun 12, 2025

Fair enough. Then happy to go down that path, let's talk on Monday?

@jeluard jeluard merged commit 5b67cec into main Jun 13, 2025
13 of 14 checks passed
@jeluard jeluard deleted the jeluard/do-not-panic-when-invalid-tx branch June 13, 2025 19:06
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.

3 participants
0