Skip to content

Commit 0fc993c

Browse files
committed
test: add generation arguments
Signed-off-by: etorreborre <etorreborre@yahoo.com>
1 parent 25c8fc3 commit 0fc993c

8 files changed

Lines changed: 76 additions & 11 deletions

File tree

crates/amaru-consensus/src/consensus/headers_tree/data_generation/actions.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,7 @@ use serde::{Deserialize, Deserializer, Serialize, Serializer};
4444
use std::cmp::Reverse;
4545
use std::collections::BTreeMap;
4646
use std::fmt::{Debug, Display, Formatter};
47+
use std::str::FromStr;
4748
use std::sync::Arc;
4849

4950
/// This data type models the events sent by the ChainSync mini-protocol with simplified data for the tests.
@@ -315,6 +316,30 @@ pub fn random_walk(
315316
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
316317
pub struct Ratio(pub u32, pub u32);
317318

319+
impl Display for Ratio {
320+
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
321+
write!(f, "{}/{}", self.0, self.1)
322+
}
323+
}
324+
325+
impl FromStr for Ratio {
326+
type Err = String;
327+
328+
fn from_str(s: &str) -> Result<Self, Self::Err> {
329+
let parts: Vec<&str> = s.split('/').collect();
330+
if parts.len() != 2 {
331+
return Err("Ratio must be in the form 'numerator/denominator'".to_string());
332+
}
333+
let numerator = parts[0]
334+
.parse::<u32>()
335+
.map_err(|_| format!("Invalid numerator in ratio: {}", parts[0]))?;
336+
let denominator = parts[1]
337+
.parse::<u32>()
338+
.map_err(|_| format!("Invalid denominator in ratio: {}", parts[1]))?;
339+
Ok(Ratio(numerator, denominator))
340+
}
341+
}
342+
318343
/// Generate random walks for a fixed number of peers on a given tree of headers.
319344
///
320345
/// The returned list of actions is transposed so that the actions from different peers are interleaved.
@@ -358,8 +383,9 @@ pub fn any_select_chains(
358383
peers_nb: usize,
359384
depth: usize,
360385
rollback_ratio: Ratio,
386+
branching_ratio: Ratio,
361387
) -> impl Strategy<Value = Vec<Action>> {
362-
any_tree_of_headers(depth, Ratio(1, 2)).prop_flat_map(move |tree| {
388+
any_tree_of_headers(depth, branching_ratio).prop_flat_map(move |tree| {
363389
(1..u64::MAX)
364390
.prop_map(move |seed| generate_random_walks(&tree, peers_nb, rollback_ratio, seed))
365391
})

crates/amaru-consensus/src/consensus/headers_tree/headers_tree.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1284,11 +1284,12 @@ mod tests {
12841284
const MAX_LENGTH: usize = 5;
12851285
const TEST_CASES_NB: u32 = 1000;
12861286
const ROLLBACK_RATIO: Ratio = Ratio(1, 2);
1287+
const BRANCHING_RATIO: Ratio = Ratio(1, 2);
12871288

12881289
proptest! {
12891290
#![proptest_config(config_begin().no_shrink().with_cases(TEST_CASES_NB).end())]
12901291
#[test]
1291-
fn run_chain_selection(actions in any_select_chains(DEPTH, 5, ROLLBACK_RATIO)) {
1292+
fn run_chain_selection(actions in any_select_chains(DEPTH, 5, ROLLBACK_RATIO, BRANCHING_RATIO)) {
12921293
let results = execute_actions(MAX_LENGTH, &actions, false).unwrap();
12931294
let actual_chains = make_best_chains_from_results(&results);
12941295
let expected_chains = make_best_chains_from_actions(&actions);

simulation/amaru-sim/src/simulator/args.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
use amaru_consensus::consensus::headers_tree::data_generation::Ratio;
1516
use clap::Parser;
17+
use std::str::FromStr;
1618

1719
#[derive(Debug, Parser, Clone)]
1820
#[clap(name = "Amaru Simulator")]
@@ -39,6 +41,14 @@ pub struct Args {
3941
#[arg(long, default_value = "10")]
4042
pub generated_chain_depth: u64,
4143

44+
/// Ratio of rollbacks in the generated chain for a given peer
45+
#[arg(long, default_value = "1/2", value_parser = Ratio::from_str)]
46+
pub generated_chain_rollback_ratio: Ratio,
47+
48+
/// Ratio of branches generated from a central chain that can be explored by peers during input generation
49+
#[arg(long, default_value = "1/2", value_parser = Ratio::from_str)]
50+
pub generated_chain_branching_ratio: Ratio,
51+
4252
#[arg(long)]
4353
pub disable_shrinking: bool,
4454

simulation/amaru-sim/src/simulator/data_generation/generate.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::simulator::data_generation::base_generators::generate_arrival_times;
1818
use crate::simulator::{Entry, NodeConfig};
1919
use crate::sync::ChainSyncMessage;
2020
use amaru_consensus::IsHeader;
21-
use amaru_consensus::consensus::headers_tree::data_generation::{Action, Ratio, any_select_chains};
21+
use amaru_consensus::consensus::headers_tree::data_generation::{Action, any_select_chains};
2222
use amaru_kernel::peer::Peer;
2323
use amaru_kernel::to_cbor;
2424
use amaru_ouroboros_traits::tests::run_with_rng;
@@ -37,7 +37,8 @@ pub fn generate_entries<R: Rng>(
3737
any_select_chains(
3838
node_config.number_of_upstream_peers as usize,
3939
node_config.generated_chain_depth as usize,
40-
Ratio(1, 2),
40+
node_config.generated_chain_rollback_ratio,
41+
node_config.generated_chain_branching_ratio,
4142
),
4243
);
4344

simulation/amaru-sim/src/simulator/node_config.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,16 @@
1313
// limitations under the License.
1414

1515
use crate::simulator::Args;
16+
use amaru_consensus::consensus::headers_tree::data_generation::Ratio;
1617

1718
/// Configuration for a single node
1819
#[derive(Debug, Clone)]
1920
pub struct NodeConfig {
2021
pub number_of_upstream_peers: u8,
2122
pub number_of_downstream_peers: u8,
2223
pub generated_chain_depth: u64,
24+
pub generated_chain_rollback_ratio: Ratio,
25+
pub generated_chain_branching_ratio: Ratio,
2326
}
2427

2528
impl Default for NodeConfig {
@@ -28,6 +31,8 @@ impl Default for NodeConfig {
2831
number_of_upstream_peers: 2,
2932
number_of_downstream_peers: 1,
3033
generated_chain_depth: 10,
34+
generated_chain_rollback_ratio: Ratio(1, 2),
35+
generated_chain_branching_ratio: Ratio(1, 2),
3136
}
3237
}
3338
}
@@ -38,6 +43,8 @@ impl NodeConfig {
3843
number_of_upstream_peers: args.number_of_upstream_peers,
3944
number_of_downstream_peers: args.number_of_downstream_peers,
4045
generated_chain_depth: args.generated_chain_depth,
46+
generated_chain_rollback_ratio: args.generated_chain_rollback_ratio,
47+
generated_chain_branching_ratio: args.generated_chain_branching_ratio,
4148
}
4249
}
4350

@@ -55,4 +62,14 @@ impl NodeConfig {
5562
self.generated_chain_depth = depth;
5663
self
5764
}
65+
66+
pub fn with_generated_chain_rollback_ratio(mut self, ratio: Ratio) -> Self {
67+
self.generated_chain_rollback_ratio = ratio;
68+
self
69+
}
70+
71+
pub fn with_generated_chain_branching_ratio(mut self, ratio: Ratio) -> Self {
72+
self.generated_chain_branching_ratio = ratio;
73+
self
74+
}
5875
}

simulation/amaru-sim/src/simulator/run.rs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -238,17 +238,17 @@ fn make_chain_selector(
238238
}
239239

240240
/// Property: at the end of the simulation, the chain built from the history of messages received
241-
/// must match one of the best chains that could be built from the entries.
241+
/// downstream must match the best chain built directly from messages coming from upstream peers.
242242
fn chain_property()
243243
-> impl Fn(&[Entry<ChainSyncMessage>], &History<ChainSyncMessage>) -> Result<(), String> {
244244
move |entries, history| {
245-
let expected = make_best_chain_from_entries(
245+
let expected = make_best_chain_from_upstream_messages(
246246
&entries
247247
.iter()
248248
.map(|e| e.envelope.clone())
249249
.collect::<Vec<_>>(),
250250
);
251-
let actual = make_best_chain_from_results(history);
251+
let actual = make_best_chain_from_downstream_messages(history);
252252
let actual_chain = actual.list_to_string(",\n ");
253253
let expected_chain = expected.list_to_string(",\n ");
254254
assert_eq!(
@@ -261,7 +261,7 @@ fn chain_property()
261261
}
262262

263263
/// Build the best chain from messages incoming from upstream peers.
264-
pub fn make_best_chain_from_entries(messages: &[Envelope<ChainSyncMessage>]) -> Chain {
264+
pub fn make_best_chain_from_upstream_messages(messages: &[Envelope<ChainSyncMessage>]) -> Chain {
265265
// keep the chain of each peer
266266
let mut current_chains: BTreeMap<String, Chain> = BTreeMap::new();
267267

@@ -309,9 +309,8 @@ pub fn make_best_chain_from_entries(messages: &[Envelope<ChainSyncMessage>]) ->
309309
current_chains.get(&best_chain_tracker).unwrap().clone()
310310
}
311311

312-
/// Build the best chain from the results by creating a chain corresponding to the ChainSyncMessage emitted
313-
/// by the node.
314-
pub fn make_best_chain_from_results(history: &History<ChainSyncMessage>) -> Chain {
312+
/// Build the best chain from messages sent to downstream peers.
313+
pub fn make_best_chain_from_downstream_messages(history: &History<ChainSyncMessage>) -> Chain {
315314
let mut best_chain = vec![];
316315
for (i, message) in history.0.iter().enumerate() {
317316
// only consider messages sent to the first peer

simulation/amaru-sim/tests/simulation.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,14 @@ fn run_simulator() {
4040
"AMARU_GENERATED_CHAIN_DEPTH",
4141
node_config.generated_chain_depth,
4242
),
43+
generated_chain_rollback_ratio: get_env_var(
44+
"AMARU_GENERATED_CHAIN_ROLLBACK_RATIO",
45+
node_config.generated_chain_rollback_ratio,
46+
),
47+
generated_chain_branching_ratio: get_env_var(
48+
"AMARU_GENERATED_CHAIN_BRANCHING_RATIO",
49+
node_config.generated_chain_branching_ratio,
50+
),
4351
disable_shrinking: is_true("AMARU_DISABLE_SHRINKING"),
4452
seed: get_optional_env_var("AMARU_TEST_SEED"),
4553
persist_on_success: is_true("AMARU_PERSIST_ON_SUCCESS"),

simulation/amaru-sim/tests/traces.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
use amaru_consensus::consensus::headers_tree::data_generation::Ratio;
1516
use amaru_sim::simulator::run::spawn_node;
1617
use amaru_sim::simulator::simulate::simulate;
1718
use amaru_sim::simulator::{Args, NodeConfig, NodeHandle, SimulateConfig, generate_entries};
@@ -31,6 +32,8 @@ fn run_simulator_with_traces() {
3132
number_of_upstream_peers: 1,
3233
number_of_downstream_peers: 1,
3334
generated_chain_depth: 1,
35+
generated_chain_rollback_ratio: Ratio(1, 2),
36+
generated_chain_branching_ratio: Ratio(1, 2),
3437
disable_shrinking: true,
3538
seed: None,
3639
persist_on_success: false,

0 commit comments

Comments
 (0)