zc2 0.0.49

P2P compute broker with yen-denominated billing, WAL, and broker mesh support
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
449
450
451
452
453
454
455
456
//! Running every routing strategy in turn, and showing it happen.
//!
//! A comparison is six benchmarks, and six of anything takes six times as
//! long — on a mesh with one slow node in it, two and a half minutes during
//! which the old code printed a single line and then nothing. The work here
//! is mostly about saying what is going on while it goes on: which strategy
//! is running, how far into it, and what the ones already finished found.

use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Instant;

use super::{BenchConfig, BenchResults, Shared};
use crate::broker::router::RoutingStrategy;

/// The strategies a comparison walks, in the order it walks them: the two
/// people actually choose between first, so the interesting answer is on
/// screen before the slow ones have finished.
pub(crate) const STRATEGIES: [RoutingStrategy; 6] = [
    RoutingStrategy::BestLatency,
    RoutingStrategy::BestPrice,
    RoutingStrategy::RoundRobin,
    RoutingStrategy::WeightedCapacity,
    RoutingStrategy::Random,
    RoutingStrategy::BestAvailability,
];

/// How many requests each strategy gets when `-n` was not given.
///
/// The single-run default is a thousand, and a comparison runs the workload
/// once per strategy. Six thousand requests is a two-and-a-half minute answer
/// to a question that three hundred each answers in forty seconds, and the
/// ranking does not change.
pub(crate) const DEFAULT_REQUESTS_EACH: u64 = 300;

/// What a comparison has found so far, written by the thread running the
/// benchmarks and read by whichever view is drawing them.
#[derive(Default)]
pub(crate) struct Progress {
    /// The strategy being run now, and its live state.
    current: Mutex<Option<(RoutingStrategy, Shared, Instant)>>,
    /// The ones already finished, in the order they finished.
    done: Mutex<Vec<(RoutingStrategy, BenchResults)>>,
    /// How many have been started.
    started: AtomicUsize,
    /// Set when the person asks to stop: the strategy in flight is allowed to
    /// finish, and nothing further is started.
    stop: AtomicBool,
    /// Set when every strategy has been run, or the run was cut short.
    over: AtomicBool,
}

impl Progress {
    pub(crate) fn new() -> Arc<Progress> {
        Arc::new(Progress::default())
    }

    fn begin(&self, strategy: RoutingStrategy) {
        self.started.fetch_add(1, Ordering::Relaxed);
        if let Ok(mut c) = self.current.lock() {
            *c = None;
        }
        let _ = strategy;
    }

    fn publish(&self, strategy: RoutingStrategy, shared: &Shared) {
        if let Ok(mut c) = self.current.lock() {
            *c = Some((strategy, shared.clone(), Instant::now()));
        }
    }

    fn finish(&self, strategy: RoutingStrategy, results: BenchResults) {
        if let Ok(mut d) = self.done.lock() {
            d.push((strategy, results));
        }
        if let Ok(mut c) = self.current.lock() {
            *c = None;
        }
    }

    /// The strategy in flight, its live counters, and when it started.
    pub(crate) fn running(&self) -> Option<(RoutingStrategy, Shared, Instant)> {
        self.current
            .lock()
            .ok()
            .and_then(|c| c.as_ref().map(|(s, sh, t)| (*s, sh.clone(), *t)))
    }

    /// What has finished, in the order it finished.
    pub(crate) fn finished(&self) -> Vec<(RoutingStrategy, BenchResults)> {
        self.done.lock().map(|d| d.clone()).unwrap_or_default()
    }

    pub(crate) fn started(&self) -> usize {
        self.started.load(Ordering::Relaxed)
    }

    pub(crate) fn is_over(&self) -> bool {
        self.over.load(Ordering::Relaxed)
    }

    pub(crate) fn asked_to_stop(&self) -> bool {
        self.stop.load(Ordering::Relaxed)
    }

    /// Stop after the strategy in flight. It is allowed to finish because a
    /// half-measured strategy in the table would be worse than one missing
    /// from it.
    pub(crate) fn ask_to_stop(&self) {
        self.stop.store(true, Ordering::Relaxed);
    }

    /// Abandon the strategy in flight as well.
    pub(crate) fn abandon(&self) {
        self.stop.store(true, Ordering::Relaxed);
        if let Ok(c) = self.current.lock() {
            if let Some((_, shared, _)) = c.as_ref() {
                shared.stop.store(true, Ordering::Relaxed);
            }
        }
    }
}

/// Run every strategy in turn, writing what happens into `progress`.
///
/// Returns what each one found. Runs on its own thread when a view is drawing
/// it, and on the calling thread when nothing is.
pub(crate) fn run_all(
    base: BenchConfig,
    progress: Arc<Progress>,
) -> Vec<(RoutingStrategy, BenchResults)> {
    for strategy in STRATEGIES {
        if progress.asked_to_stop() || super::interrupted() {
            break;
        }
        let mut config = base.clone();
        config.strategy = strategy;
        // Each run is measured, not narrated: the comparison draws its own
        // view and a second one underneath it would be a mess.
        config.silent = true;
        config.no_progress = true;
        progress.begin(strategy);
        let p = progress.clone();
        let results = super::run_benchmark_watched(config, &|shared| p.publish(strategy, shared));
        progress.finish(strategy, results);
    }
    progress.over.store(true, Ordering::Relaxed);
    progress.finished()
}

/// How far ahead of the runner-up a strategy must be before the comparison
/// will name it the winner.
///
/// Six strategies inside two percent of each other are six strategies that
/// did the same thing; declaring one of them "fastest" is sampling noise
/// wearing a rosette, and it is the kind of number that ends up in a commit
/// message. Five percent over three hundred requests is a difference you
/// would still see tomorrow.
pub(crate) const MEANINGFUL_MARGIN: f64 = 0.05;

/// The comparison's verdicts. `None` where nothing was measured, or where
/// nothing separates the strategies.
pub(crate) struct Verdicts {
    pub(crate) fastest: Option<usize>,
    pub(crate) cheapest: Option<usize>,
    pub(crate) freest: Option<usize>,
    /// How far apart the fastest and slowest were, as a fraction of the
    /// fastest. Reported when no winner is named, because "they were all
    /// within 1.5% of each other" is the actual finding.
    pub(crate) rps_spread: f64,
}

/// The share of a run's placed work that cost nothing.
pub(crate) fn free_share(r: &BenchResults) -> f64 {
    match r.ledger.placed() {
        0 => 0.0,
        placed => r.ledger.totals(super::metrics::Placement::Free).0 as f64 / placed as f64,
    }
}

/// A run that measured nothing wins nothing: it spent zero because it did
/// nothing, and it would otherwise be reported as the cheapest.
fn usable(r: &BenchResults) -> bool {
    r.successful > 0
}

/// The index of the strongest candidate on `key`, but only when it is ahead
/// of the runner-up by more than [`MEANINGFUL_MARGIN`].
///
/// `better` orders two values best-first. `relative_gap` says how much better
/// the best is than the second, as a fraction.
fn clear_leader(
    results: &[(RoutingStrategy, BenchResults)],
    key: impl Fn(&BenchResults) -> f64,
    better: impl Fn(f64, f64) -> std::cmp::Ordering,
    relative_gap: impl Fn(f64, f64) -> f64,
) -> Option<usize> {
    let mut ranked: Vec<(usize, f64)> = results
        .iter()
        .enumerate()
        .filter(|(_, (_, r))| usable(r))
        .map(|(i, (_, r))| (i, key(r)))
        .collect();
    ranked.sort_by(|a, b| better(a.1, b.1));
    match ranked.len() {
        0 => None,
        // One strategy measured anything at all: it is the only answer there
        // is, so it is the answer.
        1 => Some(ranked[0].0),
        _ => match relative_gap(ranked[0].1, ranked[1].1) > MEANINGFUL_MARGIN {
            true => Some(ranked[0].0),
            false => None,
        },
    }
}

pub(crate) fn verdicts(results: &[(RoutingStrategy, BenchResults)]) -> Verdicts {
    let rates: Vec<f64> = results
        .iter()
        .filter(|(_, r)| usable(r))
        .map(|(_, r)| r.rps)
        .collect();
    let rps_spread = match rates.len() {
        0 | 1 => 0.0,
        _ => {
            let hi = rates.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            let lo = rates.iter().copied().fold(f64::INFINITY, f64::min);
            match hi > 0.0 {
                true => (hi - lo) / hi,
                false => 0.0,
            }
        }
    };

    Verdicts {
        fastest: clear_leader(
            results,
            |r| r.rps,
            |a, b| b.total_cmp(&a),
            |best, second| match best > 0.0 {
                true => (best - second) / best,
                false => 0.0,
            },
        ),
        cheapest: clear_leader(
            results,
            |r| r.total_charged,
            |a, b| a.total_cmp(&b),
            // Cheaper is lower. Everything at zero — the common case while
            // #297 is open — is no difference at all, not a tie won by
            // whichever happened to be measured last.
            |best, second| match second > 0.0 {
                true => (second - best) / second,
                false => 0.0,
            },
        ),
        // "most free" is only a finding when the strategies actually differ.
        // With every one of them at 100% free, naming a winner picks one
        // arbitrarily and reads as though it beat the others.
        freest: match spread(results) > 0.01 {
            true => clear_leader(
                results,
                free_share,
                |a, b| b.total_cmp(&a),
                |best, second| best - second,
            ),
            false => None,
        },
        rps_spread,
    }
}

/// How far apart the strategies' free shares are. Zero when they all placed
/// their work the same way.
fn spread(results: &[(RoutingStrategy, BenchResults)]) -> f64 {
    let shares: Vec<f64> = results
        .iter()
        .filter(|(_, r)| usable(r))
        .map(|(_, r)| free_share(r))
        .collect();
    match shares.len() {
        0 | 1 => 0.0,
        _ => {
            let lo = shares.iter().copied().fold(f64::INFINITY, f64::min);
            let hi = shares.iter().copied().fold(f64::NEG_INFINITY, f64::max);
            hi - lo
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn run(rps: f64, yen: f64, ok: u64) -> BenchResults {
        let mut r = BenchResults::new();
        r.rps = rps;
        r.total_charged = yen;
        r.successful = ok;
        r
    }

    #[test]
    fn a_comparison_costs_a_fraction_of_six_full_runs() {
        // Six times the single-run default took two and a half minutes on a
        // mesh with one slow node in it, and printed one line for the whole
        // of it. The ranking does not need that many samples.
        let single = BenchConfig::default().requests;
        assert!(
            DEFAULT_REQUESTS_EACH < single,
            "{DEFAULT_REQUESTS_EACH} per strategy is not smaller than the single-run {single}"
        );
        assert!(
            DEFAULT_REQUESTS_EACH * STRATEGIES.len() as u64 <= single * 2,
            "the whole comparison should cost about two single runs"
        );
    }

    #[test]
    fn an_explicit_n_is_honoured() {
        // The smaller default is a default, not a cap: someone who asks for
        // ten thousand each is asking for a long, precise comparison.
        let c = BenchConfig {
            requests: 10_000,
            requests_explicit: true,
            ..Default::default()
        };
        assert!(c.requests_explicit && c.requests == 10_000);
    }

    #[test]
    fn the_two_strategies_people_choose_between_are_measured_first() {
        assert_eq!(STRATEGIES[0], RoutingStrategy::BestLatency);
        assert_eq!(STRATEGIES[1], RoutingStrategy::BestPrice);
    }

    #[test]
    fn the_verdicts_name_the_fastest_and_cheapest_when_they_lead_clearly() {
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.9, 300)),
            (RoutingStrategy::BestPrice, run(300.0, 0.1, 300)),
        ];
        let v = verdicts(&results);
        assert_eq!(v.fastest, Some(0), "400 vs 300 is a 25% lead");
        assert_eq!(v.cheapest, Some(1), "0.1 vs 0.9 is 89% cheaper");
    }

    #[test]
    fn a_one_percent_lead_names_no_winner() {
        // The real run this came from: six strategies between 2841.9 and
        // 2889.9 req/s, and the one that happened to come top by 1.5% was
        // reported as "fastest and cheapest".
        let results = vec![
            (RoutingStrategy::BestLatency, run(2841.9, 0.0, 300)),
            (RoutingStrategy::BestPrice, run(2847.8, 0.0, 300)),
            (RoutingStrategy::RoundRobin, run(2848.0, 0.0, 300)),
            (RoutingStrategy::BestAvailability, run(2889.9, 0.0, 300)),
        ];
        let v = verdicts(&results);
        assert!(v.fastest.is_none(), "1.5% is noise, not a winner");
        assert!(v.cheapest.is_none(), "all of them spent nothing");
        assert!(
            (v.rps_spread - 0.0166).abs() < 0.001,
            "the spread is the finding: {}",
            v.rps_spread
        );
    }

    #[test]
    fn everything_spending_zero_names_no_cheapest() {
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.0, 300)),
            (RoutingStrategy::BestPrice, run(100.0, 0.0, 300)),
        ];
        let v = verdicts(&results);
        assert!(v.cheapest.is_none(), "nothing separates them on cost");
        assert_eq!(v.fastest, Some(0), "but speed still separates them");
    }

    #[test]
    fn free_beats_paid_even_though_the_gap_is_measured_against_zero() {
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.0, 300)),
            (RoutingStrategy::BestPrice, run(400.0, 2.5, 300)),
        ];
        assert_eq!(verdicts(&results).cheapest, Some(0));
    }

    #[test]
    fn the_only_strategy_that_measured_anything_is_the_answer() {
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.9, 300)),
            (RoutingStrategy::Random, run(0.0, 0.0, 0)),
        ];
        let v = verdicts(&results);
        assert_eq!(v.fastest, Some(0));
        assert_eq!(v.cheapest, Some(0));
    }

    #[test]
    fn most_free_is_not_reported_when_every_strategy_is_equally_free() {
        // Six strategies all at 100% free: there is no winner to name, and
        // naming one reads as though it beat the others.
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.0, 300)),
            (RoutingStrategy::Random, run(200.0, 0.0, 300)),
        ];
        assert!(verdicts(&results).freest.is_none());
    }

    #[test]
    fn most_free_is_reported_when_they_differ() {
        let mut mixed = run(200.0, 0.4, 300);
        mixed
            .ledger
            .record("i9-w0", Some("quic"), Some(3.6), 1000, 0.4, None);
        let mut all_free = run(400.0, 0.0, 300);
        all_free
            .ledger
            .record("a-w0", Some("local"), Some(0.0), 1000, 0.0, None);
        let results = vec![
            (RoutingStrategy::BestLatency, mixed),
            (RoutingStrategy::BestPrice, all_free),
        ];
        assert_eq!(verdicts(&results).freest, Some(1));
    }

    #[test]
    fn a_strategy_that_measured_nothing_wins_nothing() {
        // It spent a zero balance because it did zero work, and reporting it as
        // the cheapest is how a broken route gets recommended.
        let results = vec![
            (RoutingStrategy::BestLatency, run(400.0, 0.9, 300)),
            (RoutingStrategy::BestPrice, run(390.0, 0.8, 300)),
            (RoutingStrategy::Random, run(0.0, 0.0, 0)),
        ];
        assert_ne!(verdicts(&results).cheapest, Some(2));
    }

    #[test]
    fn nothing_measured_at_all_names_no_winner() {
        let v = verdicts(&[(RoutingStrategy::Random, run(0.0, 0.0, 0))]);
        assert!(v.fastest.is_none() && v.cheapest.is_none() && v.freest.is_none());
    }

    #[test]
    fn stopping_lets_the_strategy_in_flight_finish() {
        let p = Progress::new();
        assert!(!p.asked_to_stop());
        p.ask_to_stop();
        assert!(p.asked_to_stop());
        // A half-measured strategy in the table is worse than one missing
        // from it, so asking to stop does not set the run's own stop flag.
        assert!(p.running().is_none());
    }
}