sim/
sim.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
use std::{
    collections::HashMap,
    io,
    path::{Path, PathBuf},
};

use anyhow::{Context, Result};
use clap::Parser;
use comfy_table::{presets::NOTHING, Cell, CellAlignment, Table};
use iroh_gossip::proto::sim::{
    BootstrapMode, NetworkConfig, RoundStats, RoundStatsAvg, RoundStatsDiff, Simulator,
    SimulatorConfig,
};
use rayon::iter::{IntoParallelIterator, ParallelIterator};
use serde::{Deserialize, Serialize};
use tracing::{error_span, info, warn};

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[allow(clippy::enum_variant_names)]
enum Simulation {
    /// A single sender broadcasts a single message per round.
    GossipSingle,
    /// Each round a different sender is chosen at random, and broadcasts a single message
    GossipMulti,
    /// Each round, all peers broadcast a single message simultaneously.
    GossipAll,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct ScenarioDescription {
    sim: Simulation,
    nodes: u32,
    #[serde(default)]
    bootstrap: BootstrapMode,
    #[serde(default = "defaults::rounds")]
    rounds: u32,
    config: Option<NetworkConfig>,
}

impl ScenarioDescription {
    pub fn label(&self) -> String {
        let &ScenarioDescription {
            sim,
            nodes,
            rounds,
            config: _,
            bootstrap: _,
        } = &self;
        format!("{sim:?}-n{nodes}-r{rounds}")
    }
}

mod defaults {
    pub fn rounds() -> u32 {
        30
    }
}

#[derive(Debug, Serialize, Deserialize)]
struct SimConfig {
    seeds: Vec<u64>,
    config: Option<NetworkConfig>,
    scenario: Vec<ScenarioDescription>,
}

#[derive(Debug, Parser)]
struct Cli {
    #[clap(subcommand)]
    command: Command,
}

#[derive(Debug, Parser)]
enum Command {
    /// Run simulations
    Run {
        #[clap(short, long)]
        config_path: PathBuf,
        #[clap(short, long)]
        out_dir: Option<PathBuf>,
        #[clap(short, long)]
        baseline: Option<PathBuf>,
        #[clap(short, long)]
        single_threaded: bool,
        #[clap(short, long)]
        filter: Vec<String>,
    },
    /// Compare simulation runs
    Compare {
        baseline: PathBuf,
        current: PathBuf,
        #[clap(short, long)]
        filter: Vec<String>,
    },
}

fn main() -> Result<()> {
    tracing_subscriber::fmt::init();
    let args: Cli = Cli::parse();
    match args.command {
        Command::Run {
            config_path,
            out_dir,
            baseline,
            single_threaded,
            filter,
        } => {
            let config_text = std::fs::read_to_string(&config_path)?;
            let config: SimConfig = toml::from_str(&config_text)?;

            let base_config = config.config.unwrap_or_default();
            info!("base config: {base_config:?}");
            let seeds = config.seeds;
            let mut scenarios = config.scenario;
            for scenario in scenarios.iter_mut() {
                scenario.config.get_or_insert_with(|| base_config.clone());
            }

            if let Some(out_dir) = out_dir.as_ref() {
                std::fs::create_dir_all(out_dir)?;
            }

            let filter_fn = |s: &ScenarioDescription| {
                let label = s.label();
                if filter.is_empty() {
                    true
                } else {
                    filter.iter().any(|x| x == &label)
                }
            };

            let results: Result<Vec<_>> = if !single_threaded {
                scenarios
                    .into_par_iter()
                    .filter(filter_fn)
                    .map(|scenario| run_and_save_simulation(scenario, &seeds, out_dir.as_deref()))
                    .collect()
            } else {
                scenarios
                    .into_iter()
                    .filter(filter_fn)
                    .map(|scenario| run_and_save_simulation(scenario, &seeds, out_dir.as_deref()))
                    .collect()
            };
            let mut results = results?;
            results.sort_by(|a, b| a.scenario.label().cmp(&b.scenario.label()));
            for result in results {
                print_result(&result);
            }
            if let (Some(baseline), Some(out_dir)) = (baseline, out_dir) {
                compare_dirs(baseline, out_dir, filter)?;
            }
        }
        Command::Compare {
            baseline,
            current,
            filter,
        } => {
            compare_dirs(baseline, current, filter)?;
        }
    }

    Ok(())
}

fn run_and_save_simulation(
    scenario: ScenarioDescription,
    seeds: &[u64],
    out_dir: Option<&Path>,
) -> Result<SimulationResults> {
    let label = scenario.label();

    if let Some(out_dir) = out_dir.as_ref() {
        let path = out_dir.join(format!("{label}.config.toml"));
        let encoded = toml::to_string(&scenario)?;
        std::fs::write(path, encoded)?;
    }

    let result = run_simulation_with_seeds(scenario, seeds, out_dir)?;

    if let Some(out_dir) = out_dir.as_ref() {
        let path = out_dir.join(format!("{label}.results.json"));
        let encoded = serde_json::to_string(&result)?;
        std::fs::write(path, encoded)?;
    }

    anyhow::Ok(result)
}

#[derive(Debug, Serialize, Deserialize, Clone)]
struct SimulationResults {
    scenario: ScenarioDescription,
    /// Maps seeds to results
    results: HashMap<u64, RoundStatsAvg>,
    average: Option<RoundStatsAvg>,
}

impl SimulationResults {
    fn load_from_file(path: impl AsRef<Path>) -> Result<Self> {
        let s = std::fs::read_to_string(path.as_ref())?;
        let out = serde_json::from_str(&s)?;
        Ok(out)
    }
}

#[derive(Debug, Serialize, Deserialize, Clone, thiserror::Error)]
enum SimulationError {
    #[error("failed to bootstrap")]
    FailedToBootstrap,
}

fn run_simulation_with_seeds(
    scenario: ScenarioDescription,
    seeds: &[u64],
    out_dir: Option<&Path>,
) -> io::Result<SimulationResults> {
    let mut results = HashMap::new();
    for &seed in seeds {
        let result = run_simulation(scenario.clone(), seed, out_dir)?;
        results.insert(seed, result);
    }

    let stats: Vec<_> = results.values().cloned().collect();
    let average = if !stats.is_empty() {
        let avg = RoundStatsAvg::avg(&stats);
        Some(avg)
    } else {
        None
    };
    Ok(SimulationResults {
        average,
        results,
        scenario,
    })
}

fn run_simulation(
    scenario: ScenarioDescription,
    seed: u64,
    out_dir: Option<&Path>,
) -> io::Result<RoundStatsAvg> {
    let span = error_span!("sim", name=%scenario.label(), %seed);
    let _guard = span.enter();

    let label = scenario.label();
    let events_csv_path = out_dir.map(|path| path.join(format!("{label}.events.{seed}.csv")));
    let sim_config = SimulatorConfig {
        rng_seed: seed,
        peers: scenario.nodes as usize,
        events_csv_path,
        ..Default::default()
    };
    let network_config = scenario.config.clone().unwrap_or_default();
    let bootstrap = scenario.bootstrap.clone();
    let mut simulator = Simulator::new(sim_config, network_config.clone());
    info!("start");
    let outcome = simulator.bootstrap(bootstrap);

    if let Some(path) = out_dir.as_ref() {
        let path = path.join(format!("{label}.latencies.{seed}.csv"));
        let mut writer = csv::Writer::from_path(path)?;
        for (from, to, latency) in simulator.network.latencies() {
            writer.write_record([
                from.to_string(),
                to.to_string(),
                latency.as_millis().to_string(),
            ])?;
        }
        writer.flush()?;
    }

    if outcome.has_peers_with_no_neighbors() {
        warn!("not all nodes active after bootstrap: {outcome:?}");
    } else {
        info!("bootstrapped, all nodes active");
    }
    let result = match scenario.sim {
        Simulation::GossipSingle => BigSingle.run(simulator, scenario.rounds as usize),
        Simulation::GossipMulti => BigMulti.run(simulator, scenario.rounds as usize),
        Simulation::GossipAll => BigAll.run(simulator, scenario.rounds as usize),
    };
    info!("done");
    Ok(result)
}

fn print_result(r: &SimulationResults) {
    let seeds = r.results.len();
    println!("{} with {seeds} seeds", r.scenario.label());
    let Some(avg) = r.average.as_ref() else {
        println!("no results, simulation did not complete");
        return;
    };
    let mut table = Table::new();
    let header = ["", "RMR", "LDH", "missed", "duration"]
        .into_iter()
        .map(|s| Cell::new(s).set_alignment(CellAlignment::Right));
    table
        .load_preset(NOTHING)
        .set_header(header)
        .add_row(fmt_round("mean", &avg.mean))
        .add_row(fmt_round("max", &avg.max))
        .add_row(fmt_round("min", &avg.min));
    println!("{table}");
    if avg.max.missed > 0.0 {
        println!("WARN: Messages were missed!")
    }
    println!();
}

trait Scenario {
    fn run(self, sim: Simulator, rounds: usize) -> RoundStatsAvg;
}

struct BigSingle;
impl Scenario for BigSingle {
    fn run(self, mut simulator: Simulator, rounds: usize) -> RoundStatsAvg {
        let from = simulator.random_peer();
        for i in 0..rounds {
            let message = format!("m{i}").into_bytes().into();
            let messages = vec![(from, message)];
            simulator.gossip_round(messages);
        }
        simulator.round_stats_average()
    }
}

struct BigMulti;
impl Scenario for BigMulti {
    fn run(self, mut simulator: Simulator, rounds: usize) -> RoundStatsAvg {
        for i in 0..rounds {
            let from = simulator.random_peer();
            let message = format!("m{i}").into_bytes().into();
            let messages = vec![(from, message)];
            simulator.gossip_round(messages);
        }
        simulator.round_stats_average()
    }
}

struct BigAll;
impl Scenario for BigAll {
    fn run(self, mut simulator: Simulator, rounds: usize) -> RoundStatsAvg {
        let messages_per_peer = 1;
        for i in 0..rounds {
            let mut messages = vec![];
            for id in simulator.network.peer_ids() {
                for j in 0..messages_per_peer {
                    let message: bytes::Bytes = format!("{i}:{j}.{id}").into_bytes().into();
                    messages.push((id, message));
                }
            }
            simulator.gossip_round(messages);
        }
        simulator.round_stats_average()
    }
}

fn compare_dirs(baseline_dir: PathBuf, current_path: PathBuf, filter: Vec<String>) -> Result<()> {
    let mut paths = vec![];
    for entry in std::fs::read_dir(&current_path)?
        .filter_map(Result::ok)
        .filter(|x| x.path().is_file())
    {
        let current_file = entry.path().to_owned();
        let Some(filename) = current_file.file_name().and_then(|s| s.to_str()) else {
            continue;
        };
        let Some(basename) = filename.strip_suffix(".results.json") else {
            continue;
        };
        if !filter.is_empty() && !filter.iter().any(|x| x == basename) {
            continue;
        }
        let baseline_file = baseline_dir.join(filename);
        if !baseline_file.exists() {
            println!("skip {} (not in baseline)", filename);
        }
        paths.push((basename.to_string(), baseline_file, current_file));
    }
    paths.sort();
    for (basename, baseline_file, current_file) in paths {
        println!("comparing {}", basename);
        if let Err(err) = compare_files(&baseline_file, &current_file) {
            println!("  skip (reason: {err:#}");
        }
    }
    Ok(())
}

fn compare_files(baseline: impl AsRef<Path>, current: impl AsRef<Path>) -> Result<()> {
    let baseline =
        SimulationResults::load_from_file(baseline.as_ref()).context("failed to load baseline")?;
    let current =
        SimulationResults::load_from_file(current.as_ref()).context("failed to load current")?;
    compare_results(baseline, current);
    Ok(())
}

fn compare_results(baseline: SimulationResults, current: SimulationResults) {
    match (baseline.average, current.average) {
        (None, Some(_avg)) => {
            println!("baseline run did not finish");
        }
        (Some(_avg), None) => {
            println!("current run did not finish");
        }
        (None, None) => println!("both runs did not finish"),
        (Some(baseline), Some(current)) => {
            let diff = baseline.diff(&current);
            let mut table = Table::new();
            let header = ["", "RMR", "LDH", "missed", "duration"]
                .into_iter()
                .map(|s| Cell::new(s).set_alignment(CellAlignment::Right));
            table
                .load_preset(NOTHING)
                .set_header(header)
                .add_row(fmt_diff_round("mean", &diff.mean))
                .add_row(fmt_diff_round("max", &diff.max))
                .add_row(fmt_diff_round("min", &diff.min));
            println!("{table}");
        }
    }
}

fn fmt_round(label: &str, round: &RoundStats) -> Vec<Cell> {
    [
        label.to_string(),
        format!("{:.2}", round.rmr),
        format!("{:.2}", round.ldh),
        format!("{:.2}", round.missed),
        format!("{}ms", round.duration.as_millis()),
    ]
    .into_iter()
    .map(|s| Cell::new(s).set_alignment(CellAlignment::Right))
    .collect()
}
fn fmt_diff_round(label: &str, round: &RoundStatsDiff) -> Vec<String> {
    vec![
        label.to_string(),
        fmt_percent(round.rmr),
        fmt_percent(round.ldh),
        fmt_percent(round.missed),
        fmt_percent(round.duration),
    ]
}

fn fmt_percent(diff: f32) -> String {
    format!("{:>+10.2}%", diff * 100.)
}