-
Notifications
You must be signed in to change notification settings - Fork 153
/
Copy pathcomparison.rs
1610 lines (1443 loc) · 52.4 KB
/
comparison.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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Functionality for comparing
//! This is mainly used to build the triage report and the perf
//! comparison endpoints
use crate::api;
use crate::db::{ArtifactId, Benchmark, Lookup, Profile, Scenario};
use crate::github;
use crate::load::SiteCtxt;
use crate::selector::{self, Tag};
use collector::category::Category;
use collector::Bound;
use serde::{Deserialize, Serialize};
use database::CommitType;
use std::collections::{HashMap, HashSet};
use std::error::Error;
use std::fmt::Write;
use std::hash::Hash;
use std::sync::Arc;
type BoxedError = Box<dyn Error + Send + Sync>;
pub async fn handle_triage(
body: api::triage::Request,
ctxt: &SiteCtxt,
) -> api::ServerResult<api::triage::Response> {
log::info!("handle_triage({:?})", body);
let start = body.start;
let end = body.end;
let master_commits = &ctxt.get_master_commits().commits;
let start_artifact = ctxt
.artifact_id_for_bound(start.clone(), true)
.ok_or(format!("could not find start commit for bound {:?}", start))?;
// This gives a better error, but is still not great -- the common case here
// is that we've had a 422 error and as such had a fork. It's possible we
// could diagnose that and give a nicer error here telling the user which
// commit to use.
let mut next = next_commit(&start_artifact, &master_commits)
.map(|c| Bound::Commit(c.sha.clone()))
.ok_or(format!("no next commit for {:?}", start_artifact))?;
let mut report = HashMap::new();
let mut before = start.clone();
let mut num_comparisons = 0;
let metric = Metric::InstructionsUser;
let benchmark_map = ctxt.get_benchmark_category_map().await;
loop {
let comparison =
match compare_given_commits(before, next.clone(), metric, ctxt, &master_commits)
.await
.map_err(|e| format!("error comparing commits: {}", e))?
{
Some(c) => c,
None => {
log::info!(
"No data found for end bound {:?}. Ending comparison...",
next
);
break;
}
};
num_comparisons += 1;
log::info!(
"Comparing {} to {}",
comparison.b.artifact,
comparison.a.artifact
);
// handle results of comparison
populate_report(&comparison, &benchmark_map, &mut report).await;
// Check that there is a next commit and that the
// after commit is not equal to `end`
match comparison.next(&master_commits).map(Bound::Commit) {
Some(n) if Some(&next) != end.as_ref() => {
before = next;
next = n;
}
_ => break,
}
}
let end = end.unwrap_or(next);
// Summarize the entire triage from start commit to end commit
let summary =
match compare_given_commits(start.clone(), end.clone(), metric, ctxt, master_commits)
.await
.map_err(|e| format!("error comparing beginning and ending commits: {}", e))?
{
Some(summary_comparison) => {
let (primary, secondary) = summary_comparison
.clone()
.summarize_by_category(&benchmark_map);
let mut result = String::from("**Summary**:\n\n");
write_summary_table(&primary, &secondary, false, true, &mut result);
result
}
None => String::from("**ERROR**: no data found for end bound"),
};
let report = generate_report(&start, &end, summary, report, num_comparisons).await;
Ok(api::triage::Response(report))
}
pub async fn handle_compare(
body: api::comparison::Request,
ctxt: &SiteCtxt,
) -> api::ServerResult<api::comparison::Response> {
log::info!("handle_compare({:?})", body);
let master_commits = &ctxt.get_master_commits().commits;
let end = body.end;
let comparison =
compare_given_commits(body.start, end.clone(), body.stat, ctxt, master_commits)
.await
.map_err(|e| format!("error comparing commits: {}", e))?
.ok_or_else(|| format!("could not find end commit for bound {:?}", end))?;
let conn = ctxt.conn().await;
let prev = comparison.prev(master_commits);
let next = comparison.next(master_commits);
let is_contiguous = comparison.is_contiguous(&*conn, master_commits).await;
let benchmark_map = conn.get_benchmarks().await;
let comparisons = comparison
.comparisons
.into_iter()
.map(|comparison| api::comparison::Comparison {
benchmark: comparison.benchmark.to_string(),
profile: comparison.profile.to_string(),
scenario: comparison.scenario.to_string(),
is_relevant: comparison.is_relevant(),
significance_factor: comparison.significance_factor(),
statistics: comparison.results,
})
.collect();
let mut new_errors = comparison
.newly_failed_benchmarks
.into_iter()
.collect::<Vec<_>>();
new_errors.sort();
Ok(api::comparison::Response {
prev,
a: comparison.a.into(),
b: comparison.b.into(),
comparisons,
new_errors,
next,
is_contiguous,
benchmark_data: benchmark_map
.into_iter()
.map(|bench| bench.into())
.collect(),
})
}
async fn populate_report(
comparison: &ArtifactComparison,
benchmark_map: &HashMap<Benchmark, Category>,
report: &mut HashMap<Direction, Vec<String>>,
) {
let (primary, secondary) = comparison.clone().summarize_by_category(&benchmark_map);
// Get the combined direction of the primary and secondary summaries
let direction = Direction::join(primary.direction(), secondary.direction());
if direction == Direction::None {
return;
}
let include_in_triage = deserves_attention_icount(&primary, &secondary);
if include_in_triage {
let entry = report.entry(direction).or_default();
entry.push(write_triage_summary(comparison, &primary, &secondary).await);
}
}
/// This enum contains all "known" metrics coming from rustc or profiling tools that we know
/// (and care) about.
#[derive(Copy, Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Metric {
#[serde(rename = "context-switches")]
ContextSwitches,
#[serde(rename = "cpu-clock")]
CpuClock,
#[serde(rename = "cpu-clock:u")]
CpuClockUser,
#[serde(rename = "cycles:u")]
CyclesUser,
#[serde(rename = "faults")]
Faults,
#[serde(rename = "faults:u")]
FaultsUser,
#[serde(rename = "instructions:u")]
InstructionsUser,
#[serde(rename = "max-rss")]
MaxRSS,
#[serde(rename = "task-clock")]
TaskClock,
#[serde(rename = "task-clock:u")]
TaskClockUser,
#[serde(rename = "wall-time")]
WallTime,
#[serde(rename = "branch-misses")]
BranchMisses,
#[serde(rename = "cache-misses")]
CacheMisses,
#[serde(rename = "size:codegen_unit_size_estimate")]
CodegenUnitSize,
#[serde(rename = "size:dep_graph")]
DepGraphSize,
#[serde(rename = "size:linked_artifact")]
LinkedArtifactSize,
#[serde(rename = "size:object_file")]
ObjectFileSize,
#[serde(rename = "size:query_cache")]
QueryCacheSize,
#[serde(rename = "size:work_product_index")]
WorkProductIndexSize,
#[serde(rename = "size:crate_metadata")]
CrateMetadataSize,
#[serde(rename = "size:dwo_file")]
DwoFileSize,
#[serde(rename = "size:assembly_file")]
AssemblyFileSize,
#[serde(rename = "size:llvm_bitcode")]
LlvmBitcodeSize,
#[serde(rename = "size:llvm_ir")]
LlvmIrSize,
}
impl Metric {
pub fn as_str(&self) -> &str {
match self {
Metric::ContextSwitches => "context-switches",
Metric::CpuClock => "cpu-clock",
Metric::CpuClockUser => "cpu-clock:u",
Metric::CyclesUser => "cycles:u",
Metric::Faults => "faults",
Metric::FaultsUser => "faults:u",
Metric::InstructionsUser => "instructions:u",
Metric::MaxRSS => "max-rss",
Metric::TaskClock => "task-clock",
Metric::TaskClockUser => "task-clock:u",
Metric::WallTime => "wall-time",
Metric::BranchMisses => "branch-misses",
Metric::CacheMisses => "cache-misses",
Metric::CodegenUnitSize => "size:codegen_unit_size_estimate",
Metric::DepGraphSize => "size:dep_graph",
Metric::LinkedArtifactSize => "size:linked_artifact",
Metric::ObjectFileSize => "size:object_file",
Metric::QueryCacheSize => "size:query_cache",
Metric::WorkProductIndexSize => "size:work_product_index",
Metric::CrateMetadataSize => "size:crate_metadata",
Metric::DwoFileSize => "size:dwo_file",
Metric::AssemblyFileSize => "size:assembly_file",
Metric::LlvmBitcodeSize => "size:llvm_bitcode",
Metric::LlvmIrSize => "size:llvm_ir",
}
}
/// Determines the magnitude of a percent relative change for a given metric.
///
/// Takes into account how noisy the stat is. For example, instruction
/// count which is normally not very noisy has smaller thresholds than
/// max-rss which can be noisy.
fn relative_change_magnitude(&self, change: f64) -> Magnitude {
let noise_factor = if self.is_typically_noisy() { 2.0 } else { 1.0 };
let change = change / noise_factor;
if change < 0.2 {
Magnitude::VerySmall
} else if change < 1.0 {
Magnitude::Small
} else if change < 2.0 {
Magnitude::Medium
} else if change < 5.0 {
Magnitude::Large
} else {
Magnitude::VeryLarge
}
}
/// Currently, we conservatively consider everything except instructions to be noisy.
fn is_typically_noisy(&self) -> bool {
!matches!(self, Self::InstructionsUser)
}
}
/// A summary of a given comparison
///
/// This summary only includes changes that are significant and relevant (as determined by a change's magnitude).
pub struct ArtifactComparisonSummary {
/// Relevant comparisons ordered from most negative to most positive
relevant_comparisons: Vec<TestResultComparison>,
/// The cached number of comparisons that are improvements
num_improvements: usize,
/// The cached number of comparisons that are regressions
num_regressions: usize,
}
impl ArtifactComparisonSummary {
/// Summarize a collection of `TestResultComparison`
pub fn summarize(comparisons: HashSet<TestResultComparison>) -> Self {
let mut num_improvements = 0;
let mut num_regressions = 0;
let mut relevant_comparisons = comparisons
.into_iter()
.filter(|c| c.is_relevant())
.inspect(|c| {
if c.is_improvement() {
num_improvements += 1;
} else {
num_regressions += 1
}
})
.collect::<Vec<_>>();
let cmp = |b1: &TestResultComparison, b2: &TestResultComparison| {
b1.relative_change()
.partial_cmp(&b2.relative_change())
.unwrap_or(std::cmp::Ordering::Equal)
};
relevant_comparisons.sort_by(cmp);
ArtifactComparisonSummary {
relevant_comparisons,
num_improvements,
num_regressions,
}
}
/// The direction of the changes
pub fn direction(&self) -> Direction {
if self.relevant_comparisons.len() == 0 {
return Direction::None;
}
let (regressions, improvements): (Vec<&TestResultComparison>, _) = self
.relevant_comparisons
.iter()
.partition(|c| c.is_regression());
if regressions.len() == 0 {
return Direction::Improvement;
}
if improvements.len() == 0 {
return Direction::Regression;
}
let total_num = self.relevant_comparisons.len();
let regressions_ratio = regressions.len() as f64 / total_num as f64;
let has_medium_and_above_regressions = regressions
.iter()
.any(|c| c.magnitude().is_medium_or_above());
let has_medium_and_above_improvements = improvements
.iter()
.any(|c| c.magnitude().is_medium_or_above());
match (
has_medium_and_above_improvements,
has_medium_and_above_regressions,
) {
(true, true) => return Direction::Mixed,
(true, false) => {
if regressions_ratio >= 0.15 {
Direction::Mixed
} else {
Direction::Improvement
}
}
(false, true) => {
if regressions_ratio < 0.85 {
Direction::Mixed
} else {
Direction::Regression
}
}
(false, false) => {
if regressions_ratio >= 0.1 && regressions_ratio <= 0.9 {
Direction::Mixed
} else if regressions_ratio <= 0.1 {
Direction::Improvement
} else {
Direction::Regression
}
}
}
}
/// Arithmetic mean of all improvements as a percent
pub fn arithmetic_mean_of_improvements(&self) -> f64 {
self.arithmetic_mean(self.improvements())
}
/// Arithmetic mean of all regressions as a percent
pub fn arithmetic_mean_of_regressions(&self) -> f64 {
self.arithmetic_mean(self.regressions())
}
/// Arithmetic mean of all changes as a percent
pub fn arithmetic_mean_of_changes(&self) -> f64 {
self.arithmetic_mean(self.relevant_comparisons.iter())
}
pub fn is_empty(&self) -> bool {
self.relevant_comparisons.is_empty()
}
fn arithmetic_mean<'a>(
&'a self,
changes: impl Iterator<Item = &'a TestResultComparison>,
) -> f64 {
let mut count = 0;
let mut sum = 0.0;
for r in changes {
sum += r.relative_change();
count += 1;
}
(sum / count as f64) * 100.0
}
fn improvements(&self) -> impl Iterator<Item = &TestResultComparison> {
self.relevant_comparisons
.iter()
.filter(|c| c.is_improvement())
}
fn regressions(&self) -> impl Iterator<Item = &TestResultComparison> {
self.relevant_comparisons
.iter()
.filter(|c| c.is_regression())
}
// This is the most negative result.
fn largest_improvement(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons
.iter()
.find(|s| s.is_improvement())
}
// This is the least negative result.
fn smallest_improvement(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons
.iter()
.rfind(|s| s.is_improvement())
}
// This is the most positive result.
fn largest_regression(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons
.iter()
.rfind(|s| s.is_regression())
}
// This is the least positive result.
fn smallest_regression(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons.iter().find(|s| s.is_regression())
}
// This may be an improvement or a regression.
fn most_positive_change(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons.last()
}
// This may be an improvement or a regression.
fn most_negative_change(&self) -> Option<&TestResultComparison> {
self.relevant_comparisons.first()
}
/// The relevance level of the entire comparison
pub fn is_relevant(&self) -> bool {
!self.is_empty()
}
pub fn num_changes(&self) -> usize {
self.relevant_comparisons.len()
}
pub fn largest_change(&self) -> Option<&TestResultComparison> {
if self.num_changes() == 0 {
None
} else {
let most_pos = self.most_positive_change().unwrap();
let most_neg = self.most_negative_change().unwrap();
let most_pos_abs = most_pos.relative_change().abs();
let most_neg_abs = most_neg.relative_change().abs();
if most_neg_abs.partial_cmp(&most_pos_abs) == Some(std::cmp::Ordering::Greater) {
Some(most_neg)
} else {
Some(most_pos)
}
}
}
}
/// Whether we are confident enough that an artifact comparison represents a real change and thus deserves to be looked at.
///
/// For example, this can be used to determine if artifact comparisons with regressions should be labeled with the
/// `perf-regression` GitHub label or should be shown in the perf triage report.
pub(crate) fn deserves_attention_icount(
primary: &ArtifactComparisonSummary,
secondary: &ArtifactComparisonSummary,
) -> bool {
match (primary.largest_change(), secondary.largest_change()) {
(Some(c), _) if c.magnitude() >= Magnitude::Medium => true,
(_, Some(c)) if c.magnitude() >= Magnitude::Large => true,
_ => {
// How we determine whether a group of small changes deserves attention is and always will be arbitrary,
// but this feels good enough for now. We may choose in the future to become more sophisticated about it.
let primary_n = primary.num_changes();
let secondary_n = secondary.num_changes();
(primary_n * 3 + secondary_n) >= 9
}
}
}
async fn write_triage_summary(
comparison: &ArtifactComparison,
primary: &ArtifactComparisonSummary,
secondary: &ArtifactComparisonSummary,
) -> String {
let mut result = if let Some(pr) = comparison.b.pr {
let title = github::pr_title(pr).await;
format!(
"{} [#{}](https://github.com/rust-lang/rust/pull/{})",
title, pr, pr
)
} else {
String::from("<Unknown Change>")
};
let start = &comparison.a.artifact;
let end = &comparison.b.artifact;
let link = &compare_link(start, end);
write!(&mut result, " [(Comparison Link)]({})\n\n", link).unwrap();
write_summary_table(&primary, &secondary, false, true, &mut result);
result
}
/// Writes a Markdown table containing summary of relevant results.
pub fn write_summary_table(
primary: &ArtifactComparisonSummary,
secondary: &ArtifactComparisonSummary,
with_footnotes: bool,
include_metric: bool,
result: &mut String,
) {
let metric = include_metric
.then(|| {
primary
.relevant_comparisons
.first()
.or(secondary.relevant_comparisons.first())
.map(|m| format!("({})", m.metric.as_str()))
})
.flatten()
.unwrap_or_else(|| String::from(" "));
fn render_stat<F: FnOnce() -> Option<f64>>(count: usize, calculate: F) -> String {
let value = if count > 0 { calculate() } else { None };
value
.map(|value| format!("{value:.1}%"))
.unwrap_or_else(|| "-".to_string())
}
fn render_range<F: FnOnce() -> (f64, f64)>(count: usize, calculate: F) -> String {
if count > 0 {
let (a, b) = calculate();
format!("[{a:.1}%, {b:.1}%]")
} else {
"-".to_string()
}
}
// (label, mean, max, count)
let mut column_data = vec![];
// label
column_data.push(vec![
"Regressions ❌ <br /> (primary)".to_string(),
"Regressions ❌ <br /> (secondary)".to_string(),
"Improvements ✅ <br /> (primary)".to_string(),
"Improvements ✅ <br /> (secondary)".to_string(),
"All ❌✅ (primary)".to_string(),
]);
// mean
column_data.push(vec![
render_stat(primary.num_regressions, || {
Some(primary.arithmetic_mean_of_regressions())
}),
render_stat(secondary.num_regressions, || {
Some(secondary.arithmetic_mean_of_regressions())
}),
render_stat(primary.num_improvements, || {
Some(primary.arithmetic_mean_of_improvements())
}),
render_stat(secondary.num_improvements, || {
Some(secondary.arithmetic_mean_of_improvements())
}),
if primary.is_empty() {
"-".to_string()
} else {
format!("{:.1}%", primary.arithmetic_mean_of_changes())
},
]);
// range
let rel_change = |r: Option<&TestResultComparison>| r.unwrap().relative_change() * 100.0;
column_data.push(vec![
render_range(primary.num_regressions, || {
(
rel_change(primary.smallest_regression()),
rel_change(primary.largest_regression()),
)
}),
render_range(secondary.num_regressions, || {
(
rel_change(secondary.smallest_regression()),
rel_change(secondary.largest_regression()),
)
}),
render_range(primary.num_improvements, || {
(
rel_change(primary.largest_improvement()),
rel_change(primary.smallest_improvement()),
)
}),
render_range(secondary.num_improvements, || {
(
rel_change(secondary.largest_improvement()),
rel_change(secondary.smallest_improvement()),
)
}),
render_range(primary.num_regressions + primary.num_improvements, || {
(
rel_change(primary.most_negative_change()),
rel_change(primary.most_positive_change()),
)
}),
]);
// count
column_data.push(vec![
primary.num_regressions.to_string(),
secondary.num_regressions.to_string(),
primary.num_improvements.to_string(),
secondary.num_improvements.to_string(),
(primary.num_regressions + primary.num_improvements).to_string(),
]);
// This code attempts to space the table cells evenly so that the data is
// easy to read for anyone who is viewing the Markdown source.
let column_labels = [
metric,
format!("mean{}", if with_footnotes { "[^1]" } else { "" }),
"range".to_string(),
format!("count{}", if with_footnotes { "[^2]" } else { "" }),
];
let counts: Vec<usize> = column_labels.iter().map(|s| s.chars().count()).collect();
for column in &column_labels {
write!(result, "| {} ", column).unwrap();
}
result.push_str("|\n");
for &count in &counts {
write!(result, "|:{}:", "-".repeat(count)).unwrap();
}
result.push_str("|\n");
for row in 0..5 {
let row_data = column_data.iter().map(|rows| rows[row].clone());
debug_assert_eq!(row_data.len(), column_labels.len());
for (column, &count) in row_data.zip(&counts) {
write!(result, "| {:<1$} ", column, count).unwrap();
}
result.push_str("|\n");
}
}
pub fn write_summary_table_footer(result: &mut String) {
writeln!(
result,
r#"
[^1]: *the arithmetic mean of the percent change*
[^2]: *number of relevant changes*"#
)
.unwrap();
}
/// Compare two bounds on a given stat
///
/// Returns Ok(None) when no data for the end bound is present
pub async fn compare(
start: Bound,
end: Bound,
metric: Metric,
ctxt: &SiteCtxt,
) -> Result<Option<ArtifactComparison>, BoxedError> {
let master_commits = &ctxt.get_master_commits().commits;
compare_given_commits(start, end, metric, ctxt, master_commits).await
}
/// Compare two bounds on a given metric
async fn compare_given_commits(
start: Bound,
end: Bound,
metric: Metric,
ctxt: &SiteCtxt,
master_commits: &[collector::MasterCommit],
) -> Result<Option<ArtifactComparison>, BoxedError> {
let idx = ctxt.index.load();
let a = ctxt
.artifact_id_for_bound(start.clone(), true)
.ok_or(format!("could not find start commit for bound {:?}", start))?;
let b = match ctxt.artifact_id_for_bound(end.clone(), false) {
Some(b) => b,
None => return Ok(None),
};
let aids = Arc::new(vec![a.clone(), b.clone()]);
// get all crates, cache, and profile combinations for the given metric
let query = selector::Query::new()
.set::<String>(Tag::Benchmark, selector::Selector::All)
.set::<String>(Tag::Scenario, selector::Selector::All)
.set::<String>(Tag::Profile, selector::Selector::All)
.set(Tag::Metric, selector::Selector::One(metric.as_str()));
// `responses` contains series iterators. The first element in the iterator is the data
// for `a` and the second is the data for `b`
let mut responses = ctxt.statistic_series(query.clone(), aids).await?;
let conn = ctxt.conn().await;
let statistics_for_a = statistics_from_series(&mut responses);
let statistics_for_b = statistics_from_series(&mut responses);
let mut historical_data =
HistoricalDataMap::calculate(ctxt, a.clone(), master_commits, metric).await?;
let comparisons = statistics_for_a
.into_iter()
.filter_map(|(test_case, a)| {
statistics_for_b
.get(&test_case)
.map(|&b| TestResultComparison {
benchmark: test_case.0,
profile: test_case.1,
scenario: test_case.2,
metric,
historical_data: historical_data.data.remove(&test_case),
results: (a, b),
})
})
.collect();
let mut errors_in_b = conn.get_error(b.lookup(&idx).unwrap()).await;
let errors_in_a = conn.get_error(a.lookup(&idx).unwrap()).await;
for (name, _) in errors_in_a {
errors_in_b.remove(&name);
}
Ok(Some(ArtifactComparison {
a: ArtifactDescription::for_artifact(&*conn, a.clone(), master_commits).await,
b: ArtifactDescription::for_artifact(&*conn, b.clone(), master_commits).await,
comparisons,
newly_failed_benchmarks: errors_in_b.into_iter().collect(),
}))
}
fn previous_commits(
mut from: ArtifactId,
n: usize,
master_commits: &[collector::MasterCommit],
) -> Vec<ArtifactId> {
let mut prevs = Vec::with_capacity(n);
while prevs.len() < n {
match prev_commit(&from, master_commits) {
Some(c) => {
let new = ArtifactId::Commit(database::Commit {
sha: c.sha.clone(),
date: database::Date(c.time),
r#type: CommitType::Master,
});
from = new.clone();
prevs.push(new);
}
None => break,
}
}
prevs
}
/// Detailed description of a specific artifact
#[derive(Debug, Clone)]
pub struct ArtifactDescription {
/// The artifact in question
pub artifact: ArtifactId,
/// The pr of the artifact if known
pub pr: Option<u32>,
/// Bootstrap data in the form "$crate" -> nanoseconds
pub bootstrap: HashMap<String, u64>,
pub bootstrap_total: u64,
}
type StatisticsMap = HashMap<TestCase, f64>;
type TestCase = (Benchmark, Profile, Scenario);
impl ArtifactDescription {
/// For the given `ArtifactId`, consume the first datapoint in each of the given `SeriesResponse`
///
/// It is assumed that the provided `ArtifactId` matches the artifact id of the next data
/// point for all of `SeriesResponse<T>`. If this is not true, this function will panic.
async fn for_artifact(
conn: &dyn database::Connection,
artifact: ArtifactId,
master_commits: &[collector::MasterCommit],
) -> Self {
let bootstrap = conn
.get_bootstrap_by_crate(&[conn.artifact_id(&artifact).await])
.await;
let bootstrap_total = bootstrap
.values()
.filter_map(|v| {
v.get(0)
.copied()
.unwrap_or_default()
.map(|v| v.as_nanos() as u64)
})
.sum::<u64>();
let bootstrap = bootstrap
.into_iter()
.filter_map(|(k, mut v)| {
v.pop()
.unwrap_or_default()
// FIXME: if we're hovering right at the 1 second mark,
// this might mean we end up with a Some for one commit and
// a None for the other commit. Ultimately it doesn't matter
// that much -- we'll mostly just ignore such results.
// Anything less than a second in wall-time measurements is
// always going to be pretty high variance just from process
// startup overheads and such, though, so we definitely
// don't want to compare those values.
.filter(|v| v.as_secs() >= 1)
.map(|v| (k, v.as_nanos() as u64))
})
.collect::<HashMap<_, _>>();
let pr = if let ArtifactId::Commit(c) = &artifact {
if let Some(m) = master_commits.iter().find(|m| m.sha == c.sha) {
m.pr
} else {
conn.pr_of(&c.sha).await
}
} else {
None
};
Self {
pr,
artifact,
bootstrap,
bootstrap_total,
}
}
}
fn statistics_from_series<T>(series: &mut [selector::SeriesResponse<T>]) -> StatisticsMap
where
T: Iterator<Item = (ArtifactId, Option<f64>)>,
{
let mut stats: StatisticsMap = HashMap::new();
for response in series {
let (_, point) = response.series.next().expect("must have element");
let value = if let Some(v) = point {
v
} else {
continue;
};
let benchmark = *response.path.get::<Benchmark>().unwrap();
let profile = *response.path.get::<Profile>().unwrap();
let scenario = *response.path.get::<Scenario>().unwrap();
stats.insert((benchmark, profile, scenario), value);
}
stats
}
impl From<ArtifactDescription> for api::comparison::ArtifactDescription {
fn from(data: ArtifactDescription) -> Self {
api::comparison::ArtifactDescription {
commit: match data.artifact.clone() {
ArtifactId::Commit(c) => c.sha,
ArtifactId::Tag(t) => t,
},
date: if let ArtifactId::Commit(c) = &data.artifact {
Some(c.date)
} else {
None
},
pr: data.pr,
bootstrap: data.bootstrap,
bootstrap_total: data.bootstrap_total,
}
}
}
// A comparison of two artifacts
#[derive(Clone)]
pub struct ArtifactComparison {
pub a: ArtifactDescription,
pub b: ArtifactDescription,
/// Test result comparisons between the two artifacts
pub comparisons: HashSet<TestResultComparison>,
/// A map from benchmark name to an error which occured when building `b` but not `a`.
pub newly_failed_benchmarks: HashMap<String, String>,
}
impl ArtifactComparison {
/// Gets the previous commit before `a`
pub fn prev(&self, master_commits: &[collector::MasterCommit]) -> Option<String> {
prev_commit(&self.a.artifact, master_commits).map(|c| c.sha.clone())
}
/// Determines if `a` and `b` are contiguous
pub async fn is_contiguous(
&self,
conn: &dyn database::Connection,
master_commits: &[collector::MasterCommit],
) -> bool {
match (&self.a.artifact, &self.b.artifact) {
(ArtifactId::Commit(a), ArtifactId::Commit(b)) => {
if let Some(b) = master_commits.iter().find(|c| c.sha == b.sha) {
b.parent_sha == a.sha
} else {
conn.parent_of(&b.sha).await.map_or(false, |p| p == a.sha)
}
}
_ => false,
}
}
/// Gets the sha of the next commit after `b`
pub fn next(&self, master_commits: &[collector::MasterCommit]) -> Option<String> {
next_commit(&self.b.artifact, master_commits).map(|c| c.sha.clone())
}
/// Splits an artifact comparison into primary and secondary summaries based on benchmark category
pub fn summarize_by_category(
self,
category_map: &HashMap<Benchmark, Category>,
) -> (ArtifactComparisonSummary, ArtifactComparisonSummary) {
let (primary, secondary) = self
.comparisons
.into_iter()
.partition(|s| category_map.get(&s.benchmark()) == Some(&Category::Primary));
(
ArtifactComparisonSummary::summarize(primary),
ArtifactComparisonSummary::summarize(secondary),
)
}
}
/// The historical data for a certain benchmark
pub struct HistoricalDataMap {
/// Historical data on a per test case basis
pub data: HashMap<(Benchmark, Profile, Scenario), HistoricalData>,
}
impl HistoricalDataMap {
const NUM_PREVIOUS_COMMITS: usize = 100;
const MIN_PREVIOUS_COMMITS: usize = 50;
async fn calculate(
ctxt: &SiteCtxt,
from: ArtifactId,
master_commits: &[collector::MasterCommit],
metric: Metric,
) -> Result<Self, BoxedError> {
let mut historical_data = HashMap::new();
let previous_commits = Arc::new(previous_commits(
from,
Self::NUM_PREVIOUS_COMMITS,
master_commits,
));
// Return early if we don't have enough data for historical analysis
if previous_commits.len() < Self::MIN_PREVIOUS_COMMITS {
return Ok(Self {
data: historical_data,
});
}
// get all crates, cache, and profile combinations for the given metric