Skip to content

Add shrinking a la delta debugging#345

Merged
stevana merged 5 commits into
mainfrom
stevan/shrink
Jul 30, 2025
Merged

Add shrinking a la delta debugging#345
stevana merged 5 commits into
mainfrom
stevan/shrink

Conversation

@stevana

@stevana stevana commented Jul 22, 2025

Copy link
Copy Markdown
Contributor

Add shrinking to the simulator, essentially bisecting the input for as long as the same error is returned by the test.

Summary by CodeRabbit

  • New Features

    • Added automatic shrinking of failing simulation inputs, minimizing them to the smallest case that still triggers errors.
    • Introduced delta debugging to help identify minimal failing scenarios in simulations.
    • Added a new function to combine generated vectors element-wise for enhanced test input creation.
  • Refactor

    • Improved simulation test loop structure for better maintainability and error handling.
    • Updated error reporting to provide concise failure messages and display minimized failing inputs.
  • Chores

    • Enhanced message generation in tests to include randomized arrival times for more robust simulation scenarios.

stevana added 4 commits July 21, 2025 14:18
Signed-off-by: Stevan A <stevana@users.noreply.github.com>
Signed-off-by: Stevan A <stevana@users.noreply.github.com>
Signed-off-by: Stevan A <stevana@users.noreply.github.com>
Signed-off-by: Stevan A <stevana@users.noreply.github.com>
@coderabbitai

coderabbitai Bot commented Jul 22, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

A new delta debugging "shrink" module was introduced to minimize failing simulation inputs. The simulation logic was refactored to use this shrinker for property-based tests, with improved error reporting and test input generation via a new generate_zip_with utility. Module declarations and imports were updated accordingly.

Changes

File(s) Change Summary
simulation/amaru-sim/src/simulator/generate.rs Added generate_zip_with, a generic function to combine two generated vectors element-wise.
simulation/amaru-sim/src/simulator/mod.rs Declared new public module shrink.
simulation/amaru-sim/src/simulator/shrink.rs Introduced delta debugging shrinker module with shrink function and unit tests.
simulation/amaru-sim/src/simulator/simulate.rs Refactored simulation loop to use shrinker, reworked test input generation, and improved error handling.

Sequence Diagram(s)

sequenceDiagram
    participant TestRunner
    participant InputGenerator
    participant Simulator
    participant Shrinker

    TestRunner->>InputGenerator: Generate test inputs (using generate_zip_with)
    TestRunner->>Simulator: Run simulation on inputs
    Simulator-->>TestRunner: Return result (history, property check)
    alt Test fails
        TestRunner->>Shrinker: Minimize failing input (shrink)
        Shrinker->>Simulator: Re-run simulation on reduced inputs
        Shrinker-->>TestRunner: Return minimized input, error, shrink count
        TestRunner->>TestRunner: Display failure with minimized input
    end
Loading

Estimated code review effort

4 (~90 minutes)

Possibly related PRs

Suggested reviewers

  • abailly

Poem

🍀
In the code down under, where the bugs may roam,
A shrinker now helps bring failing tests home.
Inputs get zipped, simulations run tight,
Errors get smaller—like a Goomba in fright!
Debugging’s a breeze, with a cheeky new twist,
Now let’s raise a pint—no more bugs on the list!
🍻


📜 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 fcceb41 and bd51bfe.

📒 Files selected for processing (3)
  • simulation/amaru-sim/src/simulator/generate.rs (1 hunks)
  • simulation/amaru-sim/src/simulator/shrink.rs (1 hunks)
  • simulation/amaru-sim/src/simulator/simulate.rs (10 hunks)
🧠 Learnings (2)
📓 Common learnings
Learnt from: stevana
PR: pragma-org/amaru#210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in `simulation/amaru-sim/src/simulator/simulate.rs` with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (`../../target/debug/echo`) and making tests more reliable.
simulation/amaru-sim/src/simulator/simulate.rs (9)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #206
File: crates/pure-stage/src/simulation/running.rs:240-242
Timestamp: 2025-05-09T13:09:47.915Z
Learning: Cloning messages in the pure-stage crate should be avoided for performance reasons. The current implementation in SimulationRunning deliberately avoids duplicating message data structures.

Learnt from: jeluard
PR: #69
File: crates/amaru/src/ledger/state/diff_epoch_reg.rs:112-117
Timestamp: 2025-01-21T15:32:17.911Z
Learning: When suggesting code changes in Rust, always verify that the types align correctly, especially when dealing with references and Options. The Fold::Registered variant in diff_epoch_reg.rs expects a reference &'a V, so unwrapping an Option<&V> requires only a single .expect().

Learnt from: rkuhn
PR: #263
File: crates/amaru-consensus/src/consensus/store.rs:220-223
Timestamp: 2025-06-14T16:38:35.449Z
Learning: In NetworkName::Preprod.into() when converting to &EraHistory, the From implementation returns a static reference to a constant value, not a temporary. This makes it safe to return directly from functions expecting &EraHistory without storing it in a struct field.

Learnt from: abailly
PR: #195
File: crates/amaru/src/stages/consensus/fetch_block.rs:0-0
Timestamp: 2025-04-23T09:12:58.872Z
Learning: In the amaru codebase, when constructing new events from existing events, it's preferred to take ownership of the original event (with a clone at the call site if needed) rather than taking a reference and explicitly cloning individual fields. This approach makes the code cleaner and more straightforward.

Learnt from: rkuhn
PR: #263
File: crates/pure-stage/src/simulation/state.rs:33-36
Timestamp: 2025-06-14T16:36:04.502Z
Learning: In simulation and replay systems that require cloneable and serializable states, error types must often be converted to String rather than stored as trait objects (like Box or anyhow::Error) because trait objects cannot be cloned, which breaks the snapshotting and replay functionality needed for deterministic simulation.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:0-0
Timestamp: 2025-04-20T17:56:39.223Z
Learning: For mpsc::channel in Tokio-based test code, use buffer sizes larger than 1 (e.g., 8) to avoid potential deadlocks when producers send multiple messages before consumers can process them.

Learnt from: rkuhn
PR: #263
File: simulation/amaru-sim/src/simulator/simulate.rs:298-300
Timestamp: 2025-06-14T16:31:53.134Z
Learning: StageRef in the pure-stage crate supports serde serialization and deserialization (derives serde::Serialize and serde::Deserialize), enabling it to be used in structs that also derive these traits for TraceBuffer and replay functionality.

🚧 Files skipped from review as they are similar to previous changes (2)
  • simulation/amaru-sim/src/simulator/generate.rs
  • simulation/amaru-sim/src/simulator/shrink.rs
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: stevana
PR: pragma-org/amaru#210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in `simulation/amaru-sim/src/simulator/simulate.rs` with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (`../../target/debug/echo`) and making tests more reliable.
simulation/amaru-sim/src/simulator/simulate.rs (9)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #206
File: crates/pure-stage/src/simulation/running.rs:240-242
Timestamp: 2025-05-09T13:09:47.915Z
Learning: Cloning messages in the pure-stage crate should be avoided for performance reasons. The current implementation in SimulationRunning deliberately avoids duplicating message data structures.

Learnt from: jeluard
PR: #69
File: crates/amaru/src/ledger/state/diff_epoch_reg.rs:112-117
Timestamp: 2025-01-21T15:32:17.911Z
Learning: When suggesting code changes in Rust, always verify that the types align correctly, especially when dealing with references and Options. The Fold::Registered variant in diff_epoch_reg.rs expects a reference &'a V, so unwrapping an Option<&V> requires only a single .expect().

Learnt from: rkuhn
PR: #263
File: crates/amaru-consensus/src/consensus/store.rs:220-223
Timestamp: 2025-06-14T16:38:35.449Z
Learning: In NetworkName::Preprod.into() when converting to &EraHistory, the From implementation returns a static reference to a constant value, not a temporary. This makes it safe to return directly from functions expecting &EraHistory without storing it in a struct field.

Learnt from: abailly
PR: #195
File: crates/amaru/src/stages/consensus/fetch_block.rs:0-0
Timestamp: 2025-04-23T09:12:58.872Z
Learning: In the amaru codebase, when constructing new events from existing events, it's preferred to take ownership of the original event (with a clone at the call site if needed) rather than taking a reference and explicitly cloning individual fields. This approach makes the code cleaner and more straightforward.

Learnt from: rkuhn
PR: #263
File: crates/pure-stage/src/simulation/state.rs:33-36
Timestamp: 2025-06-14T16:36:04.502Z
Learning: In simulation and replay systems that require cloneable and serializable states, error types must often be converted to String rather than stored as trait objects (like Box or anyhow::Error) because trait objects cannot be cloned, which breaks the snapshotting and replay functionality needed for deterministic simulation.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:0-0
Timestamp: 2025-04-20T17:56:39.223Z
Learning: For mpsc::channel in Tokio-based test code, use buffer sizes larger than 1 (e.g., 8) to avoid potential deadlocks when producers send multiple messages before consumers can process them.

Learnt from: rkuhn
PR: #263
File: simulation/amaru-sim/src/simulator/simulate.rs:298-300
Timestamp: 2025-06-14T16:31:53.134Z
Learning: StageRef in the pure-stage crate supports serde serialization and deserialization (derives serde::Serialize and serde::Deserialize), enabling it to be used in structs that also derive these traits for TraceBuffer and replay functionality.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
  • GitHub Check: Build on ubuntu-latest with target riscv32im-risc0-zkvm-elf
  • GitHub Check: Snapshots (preprod, 1, 10.1.4)
  • GitHub Check: Build on windows-latest with target x86_64-pc-windows-msvc
  • GitHub Check: Coverage
🔇 Additional comments (9)
simulation/amaru-sim/src/simulator/simulate.rs (9)

28-28: Solid import addition, mate!

Adding the shrink module import to enable delta debugging - this is exactly what we need to minimize those pesky failing test cases.


253-274: Nice refactor - cleaner than a freshly washed kangaroo!

The run_test helper function properly encapsulates the simulation test logic. The closure approach is elegant and makes the code more modular. Good work avoiding the double cloning issue from the past review by cloning the history once and reusing it.


289-289: G'day! Small but meaningful change.

Changing the test loop to start from 1 instead of 0 makes the test numbering more intuitive for humans - we don't usually say "test 0 failed", do we?


292-313: Shrinking integration looks ace!

The integration with the shrink function is well done. You're calling shrink with the test runner, original entries, and a predicate to check if the error matches. The tuple unpacking cleanly captures the shrunk entries, result, and shrink count. This is exactly what delta debugging should look like - finding the minimal failing case like a detective narrowing down clues!


324-324: Display improvements are spot on!

Adding the shrink count parameter and displaying it in the failure message gives users valuable insight into how much the input was minimized. The "Minimised input (X shrinks)" format is clear and informative - like showing how many iterations it took to solve a Rubik's cube!

Also applies to: 347-348


411-413: Import party - everyone's invited!

Good addition of the new generator functions from the generate module. The generate_zip_with function looks like it'll be the star of the show for combining generators.


459-459: Debug print hibernation mode activated!

Commenting out the debug print is sensible - probably got a bit chatty during development. Sometimes you need to tell your code to pipe down!


475-492: Generator upgrade - now with more chaos!

The switch to generate_zip_with combining message generation with randomized arrival times is brilliant! This creates much more realistic test scenarios than fixed arrival times. It's like upgrading from a metronome to actual music - way more interesting interleavings will emerge from this.


525-529: Error message makeover - less is more!

Simplifying the error message to just show the problematic message rather than building a multiline string with full history is a good call. When you're debugging, you want the key info front and center, not buried in a novel-length output. Clean and crisp like a good lager!

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (3)
simulation/amaru-sim/src/simulator/generate.rs (1)

380-396: Consider using iterators for a more rustic approach, mate!

While your implementation works like a charm, you could make it more idiomatic by using zip and map. It's like choosing between manual transmission and automatic - both get you there, but one's more elegant!

 pub fn generate_zip_with<A: Copy, B: Copy, C>(
     generator1: impl Fn(&mut StdRng) -> Vec<A>,
     generator2: impl Fn(&mut StdRng) -> Vec<B>,
     f: impl Fn(A, B) -> C,
 ) -> impl Fn(&mut StdRng) -> Vec<C> {
     move |rng| {
         let xs = generator1(rng);
         let ys = generator2(rng);
         assert_eq!(xs.len(), ys.len());
-        let mut zs = Vec::with_capacity(xs.len());
-
-        for i in 0..xs.len() {
-            zs.push(f(xs[i], ys[i]));
-        }
-        zs
+        xs.into_iter()
+            .zip(ys)
+            .map(|(x, y)| f(x, y))
+            .collect()
     }
 }
simulation/amaru-sim/src/simulator/shrink.rs (1)

57-57: Minor nitpick on the granularity adjustment

-                n = n.saturating_sub(1).max(2);
+                n = n.max(2) - 1;

Since we know n >= 2 from the algorithm logic, this simplification works just as well and is a tad cleaner!

simulation/amaru-sim/src/simulator/simulate.rs (1)

266-286: Clever extraction of the test logic, but could be cleaner!

The nested function approach works, but it's like having a game within a game - sometimes it's better to make it a proper standalone level!

Consider extracting this to a separate function at module level for better readability and potential reuse. The closure captures make it a bit dense to follow.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7757809 and fcceb41.

📒 Files selected for processing (4)
  • simulation/amaru-sim/src/simulator/generate.rs (1 hunks)
  • simulation/amaru-sim/src/simulator/mod.rs (1 hunks)
  • simulation/amaru-sim/src/simulator/shrink.rs (1 hunks)
  • simulation/amaru-sim/src/simulator/simulate.rs (9 hunks)
🧠 Learnings (5)
📓 Common learnings
Learnt from: stevana
PR: pragma-org/amaru#210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in `simulation/amaru-sim/src/simulator/simulate.rs` with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (`../../target/debug/echo`) and making tests more reliable.
simulation/amaru-sim/src/simulator/mod.rs (1)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

simulation/amaru-sim/src/simulator/shrink.rs (2)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

simulation/amaru-sim/src/simulator/generate.rs (1)

Learnt from: stevana
PR: #236
File: simulation/amaru-sim/src/simulator/generate.rs:181-181
Timestamp: 2025-06-02T12:55:45.985Z
Learning: In recent versions of the rand crate, the gen_range method has been deprecated and renamed to random_range. The random_range method is the current, correct method to use for generating random numbers within a range.

simulation/amaru-sim/src/simulator/simulate.rs (6)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #206
File: crates/pure-stage/src/simulation/running.rs:240-242
Timestamp: 2025-05-09T13:09:47.915Z
Learning: Cloning messages in the pure-stage crate should be avoided for performance reasons. The current implementation in SimulationRunning deliberately avoids duplicating message data structures.

Learnt from: rkuhn
PR: #263
File: crates/pure-stage/src/simulation/state.rs:33-36
Timestamp: 2025-06-14T16:36:04.502Z
Learning: In simulation and replay systems that require cloneable and serializable states, error types must often be converted to String rather than stored as trait objects (like Box or anyhow::Error) because trait objects cannot be cloned, which breaks the snapshotting and replay functionality needed for deterministic simulation.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:0-0
Timestamp: 2025-04-20T17:56:39.223Z
Learning: For mpsc::channel in Tokio-based test code, use buffer sizes larger than 1 (e.g., 8) to avoid potential deadlocks when producers send multiple messages before consumers can process them.

Learnt from: rkuhn
PR: #263
File: simulation/amaru-sim/src/simulator/simulate.rs:298-300
Timestamp: 2025-06-14T16:31:53.134Z
Learning: StageRef in the pure-stage crate supports serde serialization and deserialization (derives serde::Serialize and serde::Deserialize), enabling it to be used in structs that also derive these traits for TraceBuffer and replay functionality.

🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: stevana
PR: pragma-org/amaru#210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in `simulation/amaru-sim/src/simulator/simulate.rs` with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (`../../target/debug/echo`) and making tests more reliable.
simulation/amaru-sim/src/simulator/mod.rs (1)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

simulation/amaru-sim/src/simulator/shrink.rs (2)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

simulation/amaru-sim/src/simulator/generate.rs (1)

Learnt from: stevana
PR: #236
File: simulation/amaru-sim/src/simulator/generate.rs:181-181
Timestamp: 2025-06-02T12:55:45.985Z
Learning: In recent versions of the rand crate, the gen_range method has been deprecated and renamed to random_range. The random_range method is the current, correct method to use for generating random numbers within a range.

simulation/amaru-sim/src/simulator/simulate.rs (6)

Learnt from: stevana
PR: #210
File: simulation/amaru-sim/src/simulator/simulate.rs:264-277
Timestamp: 2025-05-12T14:21:27.470Z
Learning: The team plans to replace the out-of-process test in simulation/amaru-sim/src/simulator/simulate.rs with an in-process NodeHandle implementation in the future, eliminating the need for hard-coded binary paths (../../target/debug/echo) and making tests more reliable.

Learnt from: rkuhn
PR: #206
File: crates/pure-stage/src/simulation/running.rs:240-242
Timestamp: 2025-05-09T13:09:47.915Z
Learning: Cloning messages in the pure-stage crate should be avoided for performance reasons. The current implementation in SimulationRunning deliberately avoids duplicating message data structures.

Learnt from: rkuhn
PR: #263
File: crates/pure-stage/src/simulation/state.rs:33-36
Timestamp: 2025-06-14T16:36:04.502Z
Learning: In simulation and replay systems that require cloneable and serializable states, error types must often be converted to String rather than stored as trait objects (like Box or anyhow::Error) because trait objects cannot be cloned, which breaks the snapshotting and replay functionality needed for deterministic simulation.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:272-285
Timestamp: 2025-04-20T17:57:23.233Z
Learning: In test infrastructure code, rkuhn prefers explicit panics (using .unwrap() or similar) over returning Result types, as test failures should be immediate and obvious.

Learnt from: rkuhn
PR: #149
File: crates/amaru/src/stages/consensus/chain_forward/test_infra.rs:0-0
Timestamp: 2025-04-20T17:56:39.223Z
Learning: For mpsc::channel in Tokio-based test code, use buffer sizes larger than 1 (e.g., 8) to avoid potential deadlocks when producers send multiple messages before consumers can process them.

Learnt from: rkuhn
PR: #263
File: simulation/amaru-sim/src/simulator/simulate.rs:298-300
Timestamp: 2025-06-14T16:31:53.134Z
Learning: StageRef in the pure-stage crate supports serde serialization and deserialization (derives serde::Serialize and serde::Deserialize), enabling it to be used in structs that also derive these traits for TraceBuffer and replay functionality.

🔇 Additional comments (7)
simulation/amaru-sim/src/simulator/mod.rs (1)

56-56: G'day mate, module declaration looks spot on!

Clean addition of the shrink module to the simulator's public API. Like adding a new character to your party in Final Fantasy - simple but essential for the quest ahead!

simulation/amaru-sim/src/simulator/shrink.rs (3)

15-23: Ripper documentation, cobber!

Love the clear explanation of Zeller's delta debugging algorithm. It's like the debugging equivalent of a binary search boss fight - keep halving the problem until you find the weak spot!


50-52: Smart move treating different errors as passing tests!

This is a clever design choice - like how in Dark Souls, different death animations mean different things. It ensures the shrinker focuses on the specific error you're hunting.


75-161: Top-notch test coverage, legend!

The test suite is comprehensive - covering successful shrinking, unresolved cases, and the panic scenario. Like a well-designed game tutorial that covers all the mechanics!

simulation/amaru-sim/src/simulator/simulate.rs (3)

293-298: Solid integration of the shrinking functionality!

The way you've wired up the shrinker is ace - passing the error predicate to ensure we're shrinking the right failure. It's like having the perfect combo move in Street Fighter!


346-347: Nice touch showing the shrink count in the failure message!

The minimized input display with shrink count gives great debugging context. Like showing the speedrun timer - you know exactly how much work went into finding that minimal repro!


475-491: Smooth use of the new generate_zip_with function!

The random arrival times make the tests more realistic - like adding RNG to your game instead of fixed spawn patterns. Much better coverage of timing-related bugs!

Comment thread simulation/amaru-sim/src/simulator/simulate.rs Outdated
@codecov

codecov Bot commented Jul 22, 2025

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.57576% with 4 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
simulation/amaru-sim/src/simulator/shrink.rs 98.09% 2 Missing ⚠️
simulation/amaru-sim/src/simulator/simulate.rs 95.83% 2 Missing ⚠️
Files with missing lines Coverage Δ
simulation/amaru-sim/src/simulator/generate.rs 99.38% <100.00%> (+<0.01%) ⬆️
simulation/amaru-sim/src/simulator/mod.rs 61.23% <ø> (ø)
simulation/amaru-sim/src/simulator/shrink.rs 98.09% <98.09%> (ø)
simulation/amaru-sim/src/simulator/simulate.rs 72.46% <95.83%> (+2.93%) ⬆️

... and 2 files 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.

Signed-off-by: Stevan A <stevana@users.noreply.github.com>
@stevana stevana requested a review from rkuhn July 22, 2025 11:03
@stevana stevana requested a review from abailly July 29, 2025 14:11

@abailly abailly left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

nice job! Just minor suggestion which might or might not work


match world.run_world() {
Err((reason, history)) => {
match run_test(config.number_of_nodes, &spawn, &property)(&entries) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

can you reuse run_test(..) here, eg. something like

let test = run_test(config.number_of_nodes, &spawn, &property)
match test(&entries) {
...
}

Did not try it so take with a grain of salt

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Seems to work, will make it part of next PR, thanks!

@stevana stevana merged commit 8cc6d30 into main Jul 30, 2025
13 checks passed
@stevana stevana deleted the stevan/shrink branch July 30, 2025 11:17
@coderabbitai coderabbitai Bot mentioned this pull request Jul 30, 2025

@rkuhn rkuhn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I know I’m late, but there are some questions I have on this one.

Comment thread simulation/amaru-sim/src/simulator/generate.rs
Comment thread simulation/amaru-sim/src/simulator/shrink.rs
let mut start = 0;
let subset_length = input.len() / n;
let mut some_complement_is_failing = false;
while start < input.len() {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

when input.len() is odd, this will run a third time with a single input element removed at the end — is this required by the algorithm, or shouldn’t we rather round up and change the second extend_from_slice to just cap the copy?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I think removing a single input element from the end is correct...

Comment thread simulation/amaru-sim/src/simulator/simulate.rs
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