| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! The landing simulation: many seeds in memory, a few on the real store. |
| 5 | //! |
| 6 | //! - `BRAID_SIM_SEEDS=<n>` runs seeds `0..n` in memory instead of the default |
| 7 | //! number, for long runs; `BRAID_SIM_STORE_SEEDS=<n>` does the same on the |
| 8 | //! store. |
| 9 | //! - `BRAID_SIM_SEED=<s>` replays one seed, in memory and on the store, and |
| 10 | //! prints its whole trace (pass `--nocapture` to see it). |
| 11 | //! - `BRAID_SIM_AGENTS=<n>` changes the number of agents. |
| 12 | |
| 13 | use std::panic::{AssertUnwindSafe, catch_unwind}; |
| 14 | use std::sync::Mutex; |
| 15 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 16 | |
| 17 | use braid_sim::{Config, Failure, Outcome, Report, run_memory, run_store}; |
| 18 | |
| 19 | /// Seeds the default run covers in memory. |
| 20 | const MEMORY_SEEDS: u64 = 40; |
| 21 | |
| 22 | /// Seeds the default run covers on the store, where every landing syncs. |
| 23 | const STORE_SEEDS: u64 = 3; |
| 24 | |
| 25 | fn env_number(name: &str) -> Option<u64> { |
| 26 | let value = std::env::var(name).ok()?; |
| 27 | Some( |
| 28 | value |
| 29 | .trim() |
| 30 | .parse() |
| 31 | .unwrap_or_else(|_| panic!("{name} must be a number, not {value:?}")), |
| 32 | ) |
| 33 | } |
| 34 | |
| 35 | fn memory_config() -> Config { |
| 36 | let mut config = Config::default(); |
| 37 | if let Some(agents) = env_number("BRAID_SIM_AGENTS") { |
| 38 | config.agents = agents as usize; |
| 39 | } |
| 40 | config |
| 41 | } |
| 42 | |
| 43 | /// Fewer agents and changes: on the store every landing is a synced |
| 44 | /// transaction. |
| 45 | fn store_config() -> Config { |
| 46 | let mut config = memory_config(); |
| 47 | if env_number("BRAID_SIM_AGENTS").is_none() { |
| 48 | config.agents = 4; |
| 49 | } |
| 50 | config.tasks = 6; |
| 51 | config |
| 52 | } |
| 53 | |
| 54 | /// Runs `run` for seeds `0..count` on every core, and returns the summed |
| 55 | /// report, or the failure of the smallest seed that failed. |
| 56 | fn run_seeds( |
| 57 | backend: &'static str, |
| 58 | count: u64, |
| 59 | run: impl Fn(u64) -> Result<Outcome, Failure> + Sync, |
| 60 | ) -> Report { |
| 61 | let next = AtomicU64::new(0); |
| 62 | let results = Mutex::new(Vec::new()); |
| 63 | let threads = std::thread::available_parallelism() |
| 64 | .map_or(4, |n| n.get()) |
| 65 | .min(count.max(1) as usize); |
| 66 | std::thread::scope(|scope| { |
| 67 | for _ in 0..threads { |
| 68 | scope.spawn(|| { |
| 69 | loop { |
| 70 | let seed = next.fetch_add(1, Ordering::Relaxed); |
| 71 | if seed >= count { |
| 72 | break; |
| 73 | } |
| 74 | let result = match catch_unwind(AssertUnwindSafe(|| run(seed))) { |
| 75 | Ok(result) => result.map(|outcome| outcome.report), |
| 76 | Err(panic) => Err(panicked(backend, seed, panic)), |
| 77 | }; |
| 78 | results.lock().unwrap().push((seed, result)); |
| 79 | } |
| 80 | }); |
| 81 | } |
| 82 | }); |
| 83 | let mut results = results.into_inner().unwrap(); |
| 84 | results.sort_by_key(|(seed, _)| *seed); |
| 85 | let mut total = Report::default(); |
| 86 | let mut failures = Vec::new(); |
| 87 | for (_, result) in results { |
| 88 | match result { |
| 89 | Ok(report) => total.add(&report), |
| 90 | Err(failure) => failures.push(failure), |
| 91 | } |
| 92 | } |
| 93 | if let Some(first) = failures.first() { |
| 94 | panic!( |
| 95 | "{} of {count} seeds failed; the first:\n{first}", |
| 96 | failures.len() |
| 97 | ); |
| 98 | } |
| 99 | total |
| 100 | } |
| 101 | |
| 102 | fn panicked(backend: &'static str, seed: u64, panic: Box<dyn std::any::Any + Send>) -> Failure { |
| 103 | let message = panic |
| 104 | .downcast_ref::<String>() |
| 105 | .cloned() |
| 106 | .or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string())) |
| 107 | .unwrap_or_default(); |
| 108 | Failure { |
| 109 | seed, |
| 110 | backend, |
| 111 | step: 0, |
| 112 | invariant: "panic", |
| 113 | message, |
| 114 | trace: Vec::new(), |
| 115 | full_trace: Vec::new(), |
| 116 | } |
| 117 | } |
| 118 | |
| 119 | fn print_run(title: &str, outcome: &Outcome) { |
| 120 | eprintln!("{title}"); |
| 121 | for line in &outcome.trace { |
| 122 | eprintln!(" {line}"); |
| 123 | } |
| 124 | eprintln!("{}", outcome.report); |
| 125 | } |
| 126 | |
| 127 | #[test] |
| 128 | fn landing_in_memory() { |
| 129 | let config = memory_config(); |
| 130 | if let Some(seed) = env_number("BRAID_SIM_SEED") { |
| 131 | match run_memory(seed, &config) { |
| 132 | Ok(outcome) => print_run(&format!("seed {seed} in memory"), &outcome), |
| 133 | Err(failure) => panic!( |
| 134 | "{failure}\nthe whole run:\n {}", |
| 135 | failure.full_trace.join("\n ") |
| 136 | ), |
| 137 | } |
| 138 | return; |
| 139 | } |
| 140 | let seeds = env_number("BRAID_SIM_SEEDS").unwrap_or(MEMORY_SEEDS); |
| 141 | let report = run_seeds("memory", seeds, |seed| run_memory(seed, &config)); |
| 142 | eprintln!("in memory:\n{report}"); |
| 143 | assert_eq!(report.seeds, seeds); |
| 144 | assert!(report.landings() > 0, "{report}"); |
| 145 | if seeds >= MEMORY_SEEDS && env_number("BRAID_SIM_AGENTS").is_none() { |
| 146 | // The default run must keep reaching what it is there for. |
| 147 | let reached = [ |
| 148 | ("fast-forwards", report.fast_forwards), |
| 149 | ("rebases", report.rebased), |
| 150 | ("merged paths", report.merged_paths), |
| 151 | ("answers of already applied", report.already_applied), |
| 152 | ("lost answers", report.lost_acks), |
| 153 | ("duplicate requests", report.duplicates), |
| 154 | ("resubmissions", report.resubmits), |
| 155 | ("lander crashes", report.crashes), |
| 156 | ("redone changes", report.redos), |
| 157 | ("pairs landed in both orders", report.commutations), |
| 158 | ("crossings of the flat limit", report.wide_crossings), |
| 159 | ]; |
| 160 | for (what, count) in reached { |
| 161 | assert!(count > 0, "the run reached no {what}:\n{report}"); |
| 162 | } |
| 163 | for kind in [ |
| 164 | "CONTENT", |
| 165 | "MODIFY_DELETE", |
| 166 | "MODE", |
| 167 | "DF", |
| 168 | "DIR_REMOVED", |
| 169 | "CASE", |
| 170 | ] { |
| 171 | assert!( |
| 172 | report.conflict_kinds.contains_key(kind), |
| 173 | "the run reached no {kind} conflict:\n{report}" |
| 174 | ); |
| 175 | } |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | #[test] |
| 180 | fn landing_on_the_store() { |
| 181 | let config = store_config(); |
| 182 | let run = |seed: u64| -> Result<Outcome, Failure> { |
| 183 | let dir = tempfile::tempdir().expect("a temporary directory"); |
| 184 | let outcome = run_store(seed, &config, &dir.path().join("store"))?; |
| 185 | // The same seed in memory makes the same decisions, so main must go |
| 186 | // through the same changesets. |
| 187 | let memory = run_memory(seed, &config)?; |
| 188 | assert_eq!( |
| 189 | outcome.heads, memory.heads, |
| 190 | "seed {seed}: the store and memory runs landed different changesets" |
| 191 | ); |
| 192 | Ok(outcome) |
| 193 | }; |
| 194 | if let Some(seed) = env_number("BRAID_SIM_SEED") { |
| 195 | match run(seed) { |
| 196 | Ok(outcome) => print_run(&format!("seed {seed} on the store"), &outcome), |
| 197 | Err(failure) => panic!( |
| 198 | "{failure}\nthe whole run:\n {}", |
| 199 | failure.full_trace.join("\n ") |
| 200 | ), |
| 201 | } |
| 202 | return; |
| 203 | } |
| 204 | let seeds = env_number("BRAID_SIM_STORE_SEEDS").unwrap_or(STORE_SEEDS); |
| 205 | let report = run_seeds("store", seeds, run); |
| 206 | eprintln!("on the store:\n{report}"); |
| 207 | assert_eq!(report.seeds, seeds); |
| 208 | assert!(report.landings() > 0); |
| 209 | } |