| 1 |
use std::cmp::min; |
| 2 |
use std::collections::HashSet; |
| 3 |
use std::env; |
| 4 |
use std::fmt::Debug; |
| 5 |
|
| 6 |
use hg::testing::VecGraph; |
| 7 |
use hg::Revision; |
| 8 |
use hg::*; |
| 9 |
use rand::distr::Distribution; |
| 10 |
use rand::distr::Uniform; |
| 11 |
use rand::Rng; |
| 12 |
use rand::RngCore; |
| 13 |
use rand::SeedableRng; |
| 14 |
use rand_distr::LogNormal; |
| 15 |
|
| 16 |
fn build_random_graph( |
| 17 |
nodes_opt: Option<usize>, |
| 18 |
rootprob_opt: Option<f64>, |
| 19 |
mergeprob_opt: Option<f64>, |
| 20 |
prevprob_opt: Option<f64>, |
| 21 |
) -> VecGraph { |
| 22 |
let nodes = nodes_opt.unwrap_or(100); |
| 23 |
let rootprob = rootprob_opt.unwrap_or(0.05); |
| 24 |
let mergeprob = mergeprob_opt.unwrap_or(0.2); |
| 25 |
let prevprob = prevprob_opt.unwrap_or(0.7); |
| 26 |
|
| 27 |
let mut rng = rand::rng(); |
| 28 |
let mut vg: VecGraph = Vec::with_capacity(nodes); |
| 29 |
for i in 0..nodes { |
| 30 |
if i == 0 || rng.random_bool(rootprob) { |
| 31 |
vg.push([NULL_REVISION, NULL_REVISION]) |
| 32 |
} else if i == 1 { |
| 33 |
vg.push([Revision(0), NULL_REVISION]) |
| 34 |
} else if rng.random_bool(mergeprob) { |
| 35 |
let p1 = { |
| 36 |
if i == 2 || rng.random_bool(prevprob) { |
| 37 |
Revision((i - 1) as BaseRevision) |
| 38 |
} else { |
| 39 |
Revision(rng.random_range(0..i - 1) as BaseRevision) |
| 40 |
} |
| 41 |
}; |
| 42 |
// p2 is a random revision lower than i and different from p1 |
| 43 |
let mut p2 = Revision(rng.random_range(0..i - 1) as BaseRevision); |
| 44 |
if p2 >= p1 { |
| 45 |
p2.0 += 1; |
| 46 |
} |
| 47 |
vg.push([p1, p2]); |
| 48 |
} else if rng.random_bool(prevprob) { |
| 49 |
vg.push([Revision((i - 1) as BaseRevision), NULL_REVISION]) |
| 50 |
} else { |
| 51 |
vg.push([ |
| 52 |
Revision(rng.random_range(0..i - 1) as BaseRevision), |
| 53 |
NULL_REVISION, |
| 54 |
]) |
| 55 |
} |
| 56 |
} |
| 57 |
vg |
| 58 |
} |
| 59 |
|
| 60 |
/// Compute the ancestors set of all revisions of a VecGraph |
| 61 |
fn ancestors_sets(vg: &VecGraph) -> Vec<HashSet<Revision>> { |
| 62 |
let mut ancs: Vec<HashSet<Revision>> = Vec::new(); |
| 63 |
(0..vg.len()).for_each(|i| { |
| 64 |
let mut ancs_i = HashSet::new(); |
| 65 |
ancs_i.insert(Revision(i as BaseRevision)); |
| 66 |
for p in vg[i].iter().cloned() { |
| 67 |
if p != NULL_REVISION { |
| 68 |
ancs_i.extend(&ancs[p.0 as usize]); |
| 69 |
} |
| 70 |
} |
| 71 |
ancs.push(ancs_i); |
| 72 |
}); |
| 73 |
ancs |
| 74 |
} |
| 75 |
|
| 76 |
#[allow(unused)] // Useful when debugging |
| 77 |
#[derive(Clone, Debug)] |
| 78 |
enum MissingAncestorsAction { |
| 79 |
InitialBases(HashSet<Revision>), |
| 80 |
AddBases(HashSet<Revision>), |
| 81 |
RemoveAncestorsFrom(HashSet<Revision>), |
| 82 |
MissingAncestors(HashSet<Revision>), |
| 83 |
} |
| 84 |
|
| 85 |
/// An instrumented naive yet obviously correct implementation |
| 86 |
/// |
| 87 |
/// It also records all its actions for easy reproduction for replay |
| 88 |
/// of problematic cases |
| 89 |
struct NaiveMissingAncestors<'a> { |
| 90 |
ancestors_sets: &'a Vec<HashSet<Revision>>, |
| 91 |
graph: &'a VecGraph, // used for error reporting only |
| 92 |
bases: HashSet<Revision>, |
| 93 |
history: Vec<MissingAncestorsAction>, |
| 94 |
// for error reporting, assuming we are in a random test |
| 95 |
random_seed: String, |
| 96 |
} |
| 97 |
|
| 98 |
impl<'a> NaiveMissingAncestors<'a> { |
| 99 |
fn new( |
| 100 |
graph: &'a VecGraph, |
| 101 |
ancestors_sets: &'a Vec<HashSet<Revision>>, |
| 102 |
bases: &HashSet<Revision>, |
| 103 |
random_seed: &str, |
| 104 |
) -> Self { |
| 105 |
Self { |
| 106 |
ancestors_sets, |
| 107 |
bases: bases.clone(), |
| 108 |
graph, |
| 109 |
history: vec![MissingAncestorsAction::InitialBases(bases.clone())], |
| 110 |
random_seed: random_seed.into(), |
| 111 |
} |
| 112 |
} |
| 113 |
|
| 114 |
fn add_bases(&mut self, new_bases: HashSet<Revision>) { |
| 115 |
self.bases.extend(&new_bases); |
| 116 |
self.history.push(MissingAncestorsAction::AddBases(new_bases)) |
| 117 |
} |
| 118 |
|
| 119 |
fn remove_ancestors_from(&mut self, revs: &mut HashSet<Revision>) { |
| 120 |
revs.remove(&NULL_REVISION); |
| 121 |
self.history |
| 122 |
.push(MissingAncestorsAction::RemoveAncestorsFrom(revs.clone())); |
| 123 |
for base in self.bases.iter().cloned() { |
| 124 |
if base != NULL_REVISION { |
| 125 |
for rev in &self.ancestors_sets[base.0 as usize] { |
| 126 |
revs.remove(rev); |
| 127 |
} |
| 128 |
} |
| 129 |
} |
| 130 |
} |
| 131 |
|
| 132 |
fn missing_ancestors( |
| 133 |
&mut self, |
| 134 |
revs: impl IntoIterator<Item = Revision>, |
| 135 |
) -> Vec<Revision> { |
| 136 |
let revs_as_set: HashSet<Revision> = revs.into_iter().collect(); |
| 137 |
|
| 138 |
let mut missing: HashSet<Revision> = HashSet::new(); |
| 139 |
for rev in revs_as_set.iter().cloned() { |
| 140 |
if rev != NULL_REVISION { |
| 141 |
missing.extend(&self.ancestors_sets[rev.0 as usize]) |
| 142 |
} |
| 143 |
} |
| 144 |
self.history |
| 145 |
.push(MissingAncestorsAction::MissingAncestors(revs_as_set)); |
| 146 |
|
| 147 |
for base in self.bases.iter().cloned() { |
| 148 |
if base != NULL_REVISION { |
| 149 |
for rev in &self.ancestors_sets[base.0 as usize] { |
| 150 |
missing.remove(rev); |
| 151 |
} |
| 152 |
} |
| 153 |
} |
| 154 |
let mut res: Vec<Revision> = missing.iter().cloned().collect(); |
| 155 |
res.sort_unstable(); |
| 156 |
res |
| 157 |
} |
| 158 |
|
| 159 |
fn assert_eq<T>(&self, left: T, right: T) |
| 160 |
where |
| 161 |
T: PartialEq + Debug, |
| 162 |
{ |
| 163 |
if left == right { |
| 164 |
return; |
| 165 |
} |
| 166 |
panic!( |
| 167 |
"Equality assertion failed (left != right) |
| 168 |
left={:?} |
| 169 |
right={:?} |
| 170 |
graph={:?} |
| 171 |
current bases={:?} |
| 172 |
history={:?} |
| 173 |
random seed={} |
| 174 |
", |
| 175 |
left, right, self.graph, self.bases, self.history, self.random_seed, |
| 176 |
); |
| 177 |
} |
| 178 |
} |
| 179 |
|
| 180 |
/// Choose a set of random revisions |
| 181 |
/// |
| 182 |
/// The size of the set is taken from a LogNormal distribution |
| 183 |
/// with default mu=1.1 and default sigma=0.8. Quoting the Python |
| 184 |
/// test this is taken from: |
| 185 |
/// the default mu and sigma give us a nice distribution of mostly |
| 186 |
/// single-digit counts (including 0) with some higher ones |
| 187 |
/// The sample may include NULL_REVISION |
| 188 |
fn sample_revs<R: RngCore>( |
| 189 |
rng: &mut R, |
| 190 |
maxrev: Revision, |
| 191 |
mu_opt: Option<f64>, |
| 192 |
sigma_opt: Option<f64>, |
| 193 |
) -> HashSet<Revision> { |
| 194 |
let mu = mu_opt.unwrap_or(1.1); |
| 195 |
let sigma = sigma_opt.unwrap_or(0.8); |
| 196 |
|
| 197 |
let log_normal = LogNormal::new(mu, sigma).unwrap(); |
| 198 |
let nb = min(maxrev.0 as usize, log_normal.sample(rng).floor() as usize); |
| 199 |
|
| 200 |
let dist = Uniform::new(NULL_REVISION.0, maxrev.0).expect("invalid range"); |
| 201 |
rng.sample_iter(&dist).take(nb).map(Revision).collect() |
| 202 |
} |
| 203 |
|
| 204 |
/// Produces the hexadecimal representation of a slice of bytes |
| 205 |
fn hex_bytes(bytes: &[u8]) -> String { |
| 206 |
let mut s = String::with_capacity(bytes.len() * 2); |
| 207 |
for b in bytes { |
| 208 |
s.push_str(&format!("{:x}", b)); |
| 209 |
} |
| 210 |
s |
| 211 |
} |
| 212 |
|
| 213 |
/// Fill a random seed from its hexadecimal representation. |
| 214 |
/// |
| 215 |
/// This signature is meant to be consistent with `RngCore::fill_bytes` |
| 216 |
fn seed_parse_in(hex: &str, seed: &mut [u8]) { |
| 217 |
if hex.len() != 32 { |
| 218 |
panic!("Seed {} is too short for 128 bits hex", hex); |
| 219 |
} |
| 220 |
for i in 0..8 { |
| 221 |
seed[i] = u8::from_str_radix(&hex[2 * i..2 * (i + 1)], 16) |
| 222 |
.unwrap_or_else(|_e| panic!("Seed {} is not 128 bits hex", hex)); |
| 223 |
} |
| 224 |
} |
| 225 |
|
| 226 |
/// Parse the parameters for `test_missing_ancestors()` |
| 227 |
/// |
| 228 |
/// Returns (graphs, instances, calls per instance) |
| 229 |
fn parse_test_missing_ancestors_params(var: &str) -> (usize, usize, usize) { |
| 230 |
let err_msg = "TEST_MISSING_ANCESTORS format: GRAPHS,INSTANCES,CALLS"; |
| 231 |
let params: Vec<usize> = |
| 232 |
var.split(',').map(|n| n.trim().parse().expect(err_msg)).collect(); |
| 233 |
if params.len() != 3 { |
| 234 |
panic!("{}", err_msg); |
| 235 |
} |
| 236 |
(params[0], params[1], params[2]) |
| 237 |
} |
| 238 |
|
| 239 |
#[test] |
| 240 |
/// This test creates lots of random VecGraphs, |
| 241 |
/// and compare a bunch of MissingAncestors for them with |
| 242 |
/// NaiveMissingAncestors that rely on precomputed transitive closures of |
| 243 |
/// these VecGraphs (ancestors_sets). |
| 244 |
/// |
| 245 |
/// For each generater graph, several instances of `MissingAncestors` are |
| 246 |
/// created, whose methods are called and checked a given number of times. |
| 247 |
/// |
| 248 |
/// This test can be parametrized by two environment variables: |
| 249 |
/// |
| 250 |
/// - TEST_RANDOM_SEED: must be 128 bits in hexadecimal |
| 251 |
/// - TEST_MISSING_ANCESTORS: "GRAPHS,INSTANCES,CALLS". The default is |
| 252 |
/// "100,10,10" |
| 253 |
/// |
| 254 |
/// This is slow: it runs on my workstation in about 5 seconds with the |
| 255 |
/// default parameters with a plain `cargo --test`. |
| 256 |
/// |
| 257 |
/// If you want to run it faster, especially if you're changing the |
| 258 |
/// parameters, use `cargo test --release`. |
| 259 |
/// For me, that gets it down to 0.15 seconds with the default parameters |
| 260 |
fn test_missing_ancestors_compare_naive() { |
| 261 |
let (graphcount, testcount, inccount) = |
| 262 |
match env::var("TEST_MISSING_ANCESTORS") { |
| 263 |
Err(env::VarError::NotPresent) => (100, 10, 10), |
| 264 |
Ok(val) => parse_test_missing_ancestors_params(&val), |
| 265 |
Err(env::VarError::NotUnicode(_)) => { |
| 266 |
panic!("TEST_MISSING_ANCESTORS is invalid"); |
| 267 |
} |
| 268 |
}; |
| 269 |
let mut seed: [u8; 16] = [0; 16]; |
| 270 |
match env::var("TEST_RANDOM_SEED") { |
| 271 |
Ok(val) => { |
| 272 |
seed_parse_in(&val, &mut seed); |
| 273 |
} |
| 274 |
Err(env::VarError::NotPresent) => { |
| 275 |
rand::rng().fill_bytes(&mut seed); |
| 276 |
} |
| 277 |
Err(env::VarError::NotUnicode(_)) => { |
| 278 |
panic!("TEST_RANDOM_SEED must be 128 bits in hex"); |
| 279 |
} |
| 280 |
} |
| 281 |
let hex_seed = hex_bytes(&seed); |
| 282 |
eprintln!("Random seed: {}", hex_seed); |
| 283 |
|
| 284 |
let mut rng = rand_pcg::Pcg32::from_seed(seed); |
| 285 |
|
| 286 |
eprint!("Checking MissingAncestors against brute force implementation "); |
| 287 |
eprint!("for {} random graphs, ", graphcount); |
| 288 |
eprintln!( |
| 289 |
"with {} instances for each and {} calls per instance", |
| 290 |
testcount, inccount, |
| 291 |
); |
| 292 |
for g in 0..graphcount { |
| 293 |
if g != 0 && g % 100 == 0 { |
| 294 |
eprintln!("Tested with {} graphs", g); |
| 295 |
} |
| 296 |
let graph = build_random_graph(None, None, None, None); |
| 297 |
let graph_len = Revision(graph.len() as BaseRevision); |
| 298 |
let ancestors_sets = ancestors_sets(&graph); |
| 299 |
for _testno in 0..testcount { |
| 300 |
let bases: HashSet<Revision> = |
| 301 |
sample_revs(&mut rng, graph_len, None, None); |
| 302 |
let mut inc = |
| 303 |
MissingAncestors::<VecGraph>::new(graph.clone(), bases.clone()); |
| 304 |
let mut naive = NaiveMissingAncestors::new( |
| 305 |
&graph, |
| 306 |
&ancestors_sets, |
| 307 |
&bases, |
| 308 |
&hex_seed, |
| 309 |
); |
| 310 |
for _m in 0..inccount { |
| 311 |
if rng.random_bool(0.2) { |
| 312 |
let new_bases = |
| 313 |
sample_revs(&mut rng, graph_len, None, None); |
| 314 |
inc.add_bases(new_bases.iter().cloned()); |
| 315 |
naive.add_bases(new_bases); |
| 316 |
} |
| 317 |
if rng.random_bool(0.4) { |
| 318 |
// larger set so that there are more revs to remove from |
| 319 |
let mut hrevs = |
| 320 |
sample_revs(&mut rng, graph_len, Some(1.5), None); |
| 321 |
let mut rrevs = hrevs.clone(); |
| 322 |
inc.remove_ancestors_from(&mut hrevs).unwrap(); |
| 323 |
naive.remove_ancestors_from(&mut rrevs); |
| 324 |
naive.assert_eq(hrevs, rrevs); |
| 325 |
} else { |
| 326 |
let revs = sample_revs(&mut rng, graph_len, None, None); |
| 327 |
let hm = |
| 328 |
inc.missing_ancestors(revs.iter().cloned()).unwrap(); |
| 329 |
let rm = naive.missing_ancestors(revs.iter().cloned()); |
| 330 |
naive.assert_eq(hm, rm); |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
} |
| 335 |
} |