-
Notifications
You must be signed in to change notification settings - Fork 55
/
main.rs
1410 lines (1247 loc) · 49.8 KB
/
main.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
#![warn(clippy::pedantic)]
#![warn(clippy::cargo)]
#![allow(clippy::semicolon_if_nothing_returned)]
#![allow(clippy::let_underscore_drop)]
#![allow(clippy::single_match_else)]
use std::env;
use std::ffi::OsString;
use std::fmt;
use std::fs;
use std::path::PathBuf;
use std::process;
use anyhow::{bail, Context};
use chrono::{Duration, NaiveDate, Utc};
use clap::{ArgAction, Parser, ValueEnum};
use colored::Colorize;
use github::get_pr_comments;
use log::debug;
use regex::RegexBuilder;
use reqwest::blocking::Client;
mod bounds;
mod git;
mod github;
mod least_satisfying;
mod repo_access;
mod toolchains;
use crate::bounds::{Bound, Bounds};
use crate::github::get_commit;
use crate::least_satisfying::{least_satisfying, Satisfies};
use crate::repo_access::{AccessViaGithub, AccessViaLocalGit, RustRepositoryAccessor};
use crate::toolchains::{
parse_to_naive_date, DownloadError, DownloadParams, InstallError, TestOutcome, Toolchain,
ToolchainSpec, YYYY_MM_DD,
};
const BORS_AUTHOR: &str = "bors";
#[derive(Debug, Clone, PartialEq)]
pub struct Commit {
pub sha: String,
pub date: GitDate,
pub summary: String,
pub committer: Author,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Author {
pub name: String,
pub email: String,
pub date: GitDate,
}
/// The first commit which build artifacts are made available through the CI for
/// bisection.
///
/// Due to our deletion policy which expires builds after 167 days, the build
/// artifacts of this commit itself is no longer available, so this may not be entirely useful;
/// however, it does limit the amount of commits somewhat.
const EPOCH_COMMIT: &str = "927c55d86b0be44337f37cf5b0a76fb8ba86e06c";
const REPORT_HEADER: &str = "\
==================================================================================
= Please file this regression report on the rust-lang/rust GitHub repository =
= New issue: https://github.com/rust-lang/rust/issues/new =
= Known issues: https://github.com/rust-lang/rust/issues =
= Copy and paste the text below into the issue report thread. Thanks! =
==================================================================================";
#[derive(Debug, Parser)]
#[command(bin_name = "cargo", subcommand_required = true)]
enum Cargo {
BisectRustc(Opts),
}
#[derive(Debug, Parser)]
#[command(
bin_name = "cargo bisect-rustc",
version,
about,
next_display_order = None,
after_help = "Examples:
Run a fully automatic nightly bisect doing `cargo check`:
```
cargo bisect-rustc --start 2018-07-07 --end 2018-07-30 --test-dir ../my_project/ -- check
```
Run a PR-based bisect with manual prompts after each run doing `cargo build`:
```
cargo bisect-rustc --start 6a1c0637ce44aeea6c60527f4c0e7fb33f2bcd0d \\
--end 866a713258915e6cbb212d135f751a6a8c9e1c0a --test-dir ../my_project/ --prompt -- build
```"
)]
#[allow(clippy::struct_excessive_bools)]
struct Opts {
#[arg(
long,
help = "Custom regression definition",
value_enum,
default_value_t = RegressOn::Error,
)]
regress: RegressOn,
#[arg(short, long, help = "Download the alt build instead of normal build")]
alt: bool,
#[arg(
long,
help = "Host triple for the compiler",
default_value = env!("HOST"),
)]
host: String,
#[arg(long, help = "Cross-compilation target platform")]
target: Option<String>,
#[arg(long, help = "Preserve the downloaded artifacts")]
preserve: bool,
#[arg(long, help = "Preserve the target directory used for builds")]
preserve_target: bool,
#[arg(long, help = "Download rust-src [default: no download]")]
with_src: bool,
#[arg(long, help = "Download rustc-dev [default: no download]")]
with_dev: bool,
#[arg(short, long = "component", help = "additional components to install")]
components: Vec<String>,
#[arg(
long,
help = "Root directory for tests",
default_value = ".",
value_parser = validate_dir
)]
test_dir: PathBuf,
#[arg(long, help = "Manually evaluate for regression with prompts")]
prompt: bool,
#[arg(
long,
short,
help = "Assume failure after specified number of seconds (for bisecting hangs)"
)]
timeout: Option<usize>,
#[arg(short, long = "verbose", action = ArgAction::Count)]
verbosity: u8,
#[arg(
help = "Arguments to pass to cargo or the file specified by --script during tests",
num_args = 1..,
last = true
)]
command_args: Vec<OsString>,
#[arg(
long,
help = "Left bound for search (*without* regression). You can use \
a date (YYYY-MM-DD), git tag name (e.g. 1.58.0) or git commit SHA."
)]
start: Option<Bound>,
#[arg(
long,
help = "Right bound for search (*with* regression). You can use \
a date (YYYY-MM-DD), git tag name (e.g. 1.58.0) or git commit SHA."
)]
end: Option<Bound>,
#[arg(long, help = "Bisect via commit artifacts")]
by_commit: bool,
#[arg(long, value_enum, help = "How to access Rust git repository", default_value_t = Access::Github)]
access: Access,
#[arg(long, help = "Install the given artifact")]
install: Option<Bound>,
#[arg(long, help = "Force installation over existing artifacts")]
force_install: bool,
#[arg(long, help = "Script replacement for `cargo build` command")]
script: Option<PathBuf>,
#[arg(long, help = "Do not install cargo [default: install cargo]")]
without_cargo: bool,
#[arg(
long,
help = "Text shown when a test does match the condition requested"
)]
term_new: Option<String>,
#[arg(
long,
help = "Text shown when a test fails to match the condition requested"
)]
term_old: Option<String>,
}
pub type GitDate = NaiveDate;
pub fn today() -> NaiveDate {
Utc::now().date_naive()
}
fn validate_dir(s: &str) -> anyhow::Result<PathBuf> {
let path: PathBuf = s.parse()?;
if path.is_dir() {
Ok(path)
} else {
bail!(
"{} is not an existing directory",
path.canonicalize()?.display()
)
}
}
impl Opts {
fn emit_cargo_output(&self) -> bool {
self.verbosity >= 2
}
}
#[derive(Debug, thiserror::Error)]
struct ExitError(i32);
impl fmt::Display for ExitError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "exiting with {}", self.0)
}
}
impl Config {
fn default_outcome_of_output(&self, output: &process::Output) -> TestOutcome {
let status = output.status;
let stdout_utf8 = String::from_utf8_lossy(&output.stdout).to_string();
let stderr_utf8 = String::from_utf8_lossy(&output.stderr).to_string();
debug!(
"status: {:?} stdout: {:?} stderr: {:?}",
status, stdout_utf8, stderr_utf8
);
let saw_ice = stderr_utf8.contains("error: internal compiler error")
|| stderr_utf8.contains("' has overflowed its stack")
|| stderr_utf8.contains("error: the compiler unexpectedly panicked");
let input = (self.args.regress, status.success());
let result = match input {
(RegressOn::Error, true) | (RegressOn::Success, false) => TestOutcome::Baseline,
(RegressOn::Error, false) | (RegressOn::Success | RegressOn::NonError, true) => {
TestOutcome::Regressed
}
(RegressOn::Ice, _) | (RegressOn::NonError, false) => {
if saw_ice {
TestOutcome::Regressed
} else {
TestOutcome::Baseline
}
}
(RegressOn::NonIce, _) => {
if saw_ice {
TestOutcome::Baseline
} else {
TestOutcome::Regressed
}
}
};
debug!(
"default_outcome_of_output: input: {:?} result: {:?}",
input, result
);
result
}
}
#[derive(Clone, Debug, ValueEnum)]
enum Access {
Checkout,
Github,
}
impl Access {
fn repo(&self) -> Box<dyn RustRepositoryAccessor> {
match self {
Self::Checkout => Box::new(AccessViaLocalGit),
Self::Github => Box::new(AccessViaGithub),
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug, ValueEnum)]
/// Customize what is treated as regression.
enum RegressOn {
/// Marks test outcome as `Regressed` if and only if the `rustc`
/// process reports a non-success status. This corresponds to when `rustc`
/// has an internal compiler error (ICE) or when it detects an error in the
/// input program.
/// This covers the most common use case for `cargo-bisect-rustc` and is
/// thus the default setting.
Error,
/// Marks test outcome as `Regressed` if and only if the `rustc`
/// process reports a success status. This corresponds to when `rustc`
/// believes it has successfully compiled the program. This covers the use
/// case for when you want to bisect to see when a bug was fixed.
Success,
/// Marks test outcome as `Regressed` if and only if the `rustc`
/// process issues a diagnostic indicating that an internal compiler error
/// (ICE) occurred. This covers the use case for when you want to bisect to
/// see when an ICE was introduced on a codebase that is meant to produce
/// a clean error.
Ice,
/// Marks test outcome as `Regressed` if and only if the `rustc`
/// process does not issue a diagnostic indicating that an internal
/// compiler error (ICE) occurred. This covers the use case for when you
/// want to bisect to see when an ICE was fixed.
NonIce,
/// Marks test outcome as `Baseline` if and only if the `rustc`
/// process reports error status and does not issue any diagnostic
/// indicating that an internal compiler error (ICE) occurred. This is the
/// use case if the regression is a case where an ill-formed program has
/// stopped being properly rejected by the compiler.
/// (The main difference between this case and `success` is the handling of
/// ICE: `success` assumes that ICE should be considered baseline;
/// `non-error` assumes ICE should be considered a sign of a regression.)
NonError,
}
impl RegressOn {
fn must_process_stderr(self) -> bool {
match self {
RegressOn::Error | RegressOn::Success => false,
RegressOn::NonError | RegressOn::Ice | RegressOn::NonIce => true,
}
}
}
struct Config {
args: Opts,
bounds: Bounds,
rustup_tmp_path: PathBuf,
toolchains_path: PathBuf,
target: String,
client: Client,
}
impl Config {
fn from_args(args: Opts) -> anyhow::Result<Config> {
let target = args.target.clone().unwrap_or_else(|| args.host.clone());
let mut toolchains_path = home::rustup_home()?;
// We will download and extract the tarballs into this directory before installing.
// Using `~/.rustup/tmp` instead of $TMPDIR ensures we could always perform installation by
// renaming instead of copying the whole directory.
let rustup_tmp_path = toolchains_path.join("tmp");
if !rustup_tmp_path.exists() {
fs::create_dir(&rustup_tmp_path)?;
}
toolchains_path.push("toolchains");
if !toolchains_path.is_dir() {
bail!(
"`{}` is not a directory. Please install rustup.",
toolchains_path.display()
);
}
let bounds = Bounds::from_args(&args)?;
Ok(Config {
args,
bounds,
target,
toolchains_path,
rustup_tmp_path,
client: Client::new(),
})
}
}
// Application entry point
fn run() -> anyhow::Result<()> {
env_logger::try_init()?;
let args = match Cargo::try_parse() {
Ok(Cargo::BisectRustc(args)) => args,
Err(e) => match e.context().next() {
None => {
Cargo::parse();
unreachable!()
}
_ => Opts::parse(),
},
};
let cfg = Config::from_args(args)?;
if let Some(ref bound) = cfg.args.install {
cfg.install(bound)
} else {
cfg.bisect()
}
}
impl Config {
fn install(&self, bound: &Bound) -> anyhow::Result<()> {
match *bound {
Bound::Commit(ref sha) => {
let sha = self.args.access.repo().commit(sha)?.sha;
let mut t = Toolchain {
spec: ToolchainSpec::Ci {
commit: sha,
alt: self.args.alt,
},
host: self.args.host.clone(),
std_targets: vec![self.args.host.clone(), self.target.clone()],
};
t.std_targets.sort();
t.std_targets.dedup();
let dl_params = DownloadParams::for_ci(self);
t.install(&self.client, &dl_params)?;
}
Bound::Date(date) => {
let mut t = Toolchain {
spec: ToolchainSpec::Nightly { date },
host: self.args.host.clone(),
std_targets: vec![self.args.host.clone(), self.target.clone()],
};
t.std_targets.sort();
t.std_targets.dedup();
let dl_params = DownloadParams::for_nightly(self);
t.install(&self.client, &dl_params)?;
}
}
Ok(())
}
fn do_perf_search(&self, result: &BisectionResult) {
let toolchain = &result.searched[result.found];
match self.search_perf_builds(toolchain) {
Ok(result) => {
let bisection = result.bisection;
let url = format!(
"https://github.com/rust-lang-ci/rust/commit/{}",
bisection.searched[bisection.found]
)
.red()
.bold();
eprintln!("Regression in {url}");
// In case the bisected commit has been garbage-collected by github, we show its
// additional context here.
let context = &result.toolchain_descriptions[bisection.found];
eprintln!("The PR introducing the regression in this rollup is {context}");
}
Err(e) => {
eprintln!("ERROR: {e}");
}
}
}
// bisection entry point
fn bisect(&self) -> anyhow::Result<()> {
if let Bounds::Commits { start, end } = &self.bounds {
let bisection_result = self.bisect_ci(start, end)?;
self.print_results(&bisection_result);
self.do_perf_search(&bisection_result);
} else {
let nightly_bisection_result = self.bisect_nightlies()?;
self.print_results(&nightly_bisection_result);
let nightly_regression =
&nightly_bisection_result.searched[nightly_bisection_result.found];
if let ToolchainSpec::Nightly { date } = nightly_regression.spec {
let mut previous_date = date.pred_opt().unwrap();
let working_commit = loop {
match Bound::Date(previous_date).sha() {
Ok(sha) => break sha,
Err(err)
if matches!(
err.downcast_ref::<DownloadError>(),
Some(DownloadError::NotFound(_)),
) =>
{
eprintln!("missing nightly for {}", previous_date.format(YYYY_MM_DD));
previous_date = previous_date.pred_opt().unwrap();
}
Err(err) => return Err(err),
}
};
let bad_commit = Bound::Date(date).sha()?;
eprintln!(
"looking for regression commit between {} and {}",
previous_date.format(YYYY_MM_DD),
date.format(YYYY_MM_DD),
);
let ci_bisection_result = self.bisect_ci_via(&working_commit, &bad_commit)?;
self.print_results(&ci_bisection_result);
self.do_perf_search(&ci_bisection_result);
print_final_report(self, &nightly_bisection_result, &ci_bisection_result);
}
}
Ok(())
}
}
fn searched_range(
cfg: &Config,
searched_toolchains: &[Toolchain],
) -> (ToolchainSpec, ToolchainSpec) {
let first_toolchain = searched_toolchains.first().unwrap().spec.clone();
let last_toolchain = searched_toolchains.last().unwrap().spec.clone();
match (&first_toolchain, &last_toolchain) {
(ToolchainSpec::Ci { .. }, ToolchainSpec::Ci { .. }) => (first_toolchain, last_toolchain),
_ => {
// The searched_toolchains is a subset of the range actually
// searched since they don't always include the complete bounds
// due to `Config::bisect_nightlies` narrowing the range. Show the
// true range of dates searched.
match cfg.bounds {
Bounds::SearchNightlyBackwards { end } => {
(first_toolchain, ToolchainSpec::Nightly { date: end })
}
Bounds::Commits { .. } => unreachable!("expected nightly bisect"),
Bounds::Dates { start, end } => (
ToolchainSpec::Nightly { date: start },
ToolchainSpec::Nightly { date: end },
),
}
}
}
}
impl Config {
fn print_results(&self, bisection_result: &BisectionResult) {
let BisectionResult {
searched: toolchains,
dl_spec,
found,
} = bisection_result;
let (start, end) = searched_range(self, toolchains);
eprintln!("searched toolchains {} through {}", start, end);
if toolchains[*found] == *toolchains.last().unwrap() {
// FIXME: Ideally the BisectionResult would contain the final result.
// This ends up testing a toolchain that was already tested.
// I believe this is one of the duplicates mentioned in
// https://github.com/rust-lang/cargo-bisect-rustc/issues/85
eprintln!("checking last toolchain to determine final result");
let t = &toolchains[*found];
let r = match t.install(&self.client, dl_spec) {
Ok(()) => {
let outcome = t.test(self);
remove_toolchain(self, t, dl_spec);
// we want to fail, so a successful build doesn't satisfy us
match outcome {
TestOutcome::Baseline => Satisfies::No,
TestOutcome::Regressed => Satisfies::Yes,
}
}
Err(_) => {
let _ = t.remove(dl_spec);
Satisfies::Unknown
}
};
match r {
Satisfies::Yes => {}
Satisfies::No | Satisfies::Unknown => {
eprintln!(
"error: The regression was not found. Expanding the bounds may help."
);
return;
}
}
}
let tc_found = format!("Regression in {}", toolchains[*found]);
eprintln!();
eprintln!();
eprintln!("{}", "*".repeat(80).dimmed().bold());
eprintln!("{}", tc_found.red());
eprintln!("{}", "*".repeat(80).dimmed().bold());
eprintln!();
}
}
fn remove_toolchain(cfg: &Config, toolchain: &Toolchain, dl_params: &DownloadParams) {
if cfg.args.preserve {
// If `rustup toolchain link` was used to link to nightly, then even
// with --preserve, the toolchain link should be removed, otherwise it
// will go stale after 24 hours.
let toolchain_dir = cfg.toolchains_path.join(toolchain.rustup_name());
match fs::symlink_metadata(&toolchain_dir) {
Ok(meta) => {
#[cfg(windows)]
let is_junction = {
use std::os::windows::fs::MetadataExt;
(meta.file_attributes() & 1024) != 0
};
#[cfg(not(windows))]
let is_junction = false;
if !meta.file_type().is_symlink() && !is_junction {
return;
}
debug!("removing linked toolchain {}", toolchain);
}
Err(e) => {
debug!(
"remove_toolchain: cannot stat toolchain {}: {}",
toolchain, e
);
return;
}
}
}
if let Err(e) = toolchain.remove(dl_params) {
debug!(
"failed to remove toolchain {} in {}: {}",
toolchain,
cfg.toolchains_path.display(),
e
);
}
}
fn print_final_report(
cfg: &Config,
nightly_bisection_result: &BisectionResult,
ci_bisection_result: &BisectionResult,
) {
let BisectionResult {
searched: nightly_toolchains,
found: nightly_found,
..
} = nightly_bisection_result;
let BisectionResult {
searched: ci_toolchains,
found: ci_found,
..
} = ci_bisection_result;
eprintln!("{}", REPORT_HEADER.dimmed());
eprintln!();
let (start, end) = searched_range(cfg, nightly_toolchains);
eprintln!("searched nightlies: from {} to {}", start, end);
eprintln!("regressed nightly: {}", nightly_toolchains[*nightly_found],);
eprintln!(
"searched commit range: https://github.com/rust-lang/rust/compare/{0}...{1}",
ci_toolchains.first().unwrap(),
ci_toolchains.last().unwrap(),
);
eprintln!(
"regressed commit: https://github.com/rust-lang/rust/commit/{}",
ci_toolchains[*ci_found],
);
eprintln!();
eprintln!("<details>");
eprintln!(
"<summary>bisected with <a href='{}'>cargo-bisect-rustc</a> v{}</summary>",
env!("CARGO_PKG_REPOSITORY"),
env!("CARGO_PKG_VERSION"),
);
eprintln!();
eprintln!();
if let Some(host) = option_env!("HOST") {
eprintln!("Host triple: {}", host);
}
eprintln!("Reproduce with:");
eprintln!("```bash");
eprint!("cargo bisect-rustc ");
for arg in env::args_os()
.map(|arg| arg.to_string_lossy().into_owned())
.skip_while(|arg| arg.ends_with("bisect-rustc"))
{
eprint!("{arg} ");
}
eprintln!();
eprintln!("```");
eprintln!("</details>");
}
struct NightlyFinderIter {
start_date: GitDate,
current_date: GitDate,
}
impl NightlyFinderIter {
fn new(start_date: GitDate) -> Self {
Self {
start_date,
current_date: start_date,
}
}
}
impl Iterator for NightlyFinderIter {
type Item = GitDate;
fn next(&mut self) -> Option<GitDate> {
let current_distance = self.start_date - self.current_date;
let jump_length = if current_distance.num_days() < 7 {
// first week jump by two days
2
} else if current_distance.num_days() < 49 {
// from 2nd to 7th week jump weekly
7
} else {
// from 7th week jump by two weeks
14
};
self.current_date = self.current_date - Duration::days(jump_length);
Some(self.current_date)
}
}
impl Config {
fn install_and_test(
&self,
t: &Toolchain,
dl_spec: &DownloadParams,
) -> Result<Satisfies, InstallError> {
let regress = self.args.regress;
let term_old = self.args.term_old.as_deref().unwrap_or_else(|| {
if self.args.script.is_some() {
match regress {
RegressOn::Error => "Script returned success",
RegressOn::Success => "Script returned error",
RegressOn::Ice => "Script did not ICE",
RegressOn::NonIce => "Script found ICE",
RegressOn::NonError => "Script returned error (no ICE)",
}
} else {
match regress {
RegressOn::Error => "Successfully compiled",
RegressOn::Success => "Compile error",
RegressOn::Ice => "Did not ICE",
RegressOn::NonIce => "Found ICE",
RegressOn::NonError => "Compile error (no ICE)",
}
}
});
let term_new = self.args.term_new.as_deref().unwrap_or_else(|| {
if self.args.script.is_some() {
match regress {
RegressOn::Error => "Script returned error",
RegressOn::Success => "Script returned success",
RegressOn::Ice => "Script found ICE",
RegressOn::NonIce => "Script did not ICE",
RegressOn::NonError => "Script returned success or ICE",
}
} else {
match regress {
RegressOn::Error => "Compile error",
RegressOn::Success => "Successfully compiled",
RegressOn::Ice => "Found ICE",
RegressOn::NonIce => "Did not ICE",
RegressOn::NonError => "Successfully compiled or ICE",
}
}
});
match t.install(&self.client, dl_spec) {
Ok(()) => {
let outcome = t.test(self);
// we want to fail, so a successful build doesn't satisfy us
let r = match outcome {
TestOutcome::Baseline => Satisfies::No,
TestOutcome::Regressed => Satisfies::Yes,
};
eprintln!(
"RESULT: {}, ===> {}",
t,
r.msg_with_context(term_old, term_new)
);
remove_toolchain(self, t, dl_spec);
eprintln!();
Ok(r)
}
Err(error) => {
remove_toolchain(self, t, dl_spec);
Err(error)
}
}
}
fn bisect_to_regression(&self, toolchains: &[Toolchain], dl_spec: &DownloadParams) -> usize {
least_satisfying(toolchains, |t, remaining, estimate| {
eprintln!(
"{remaining} versions remaining to test after this (roughly {estimate} steps)"
);
self.install_and_test(t, dl_spec)
.unwrap_or(Satisfies::Unknown)
})
}
}
impl Config {
// nightlies branch of bisect execution
fn bisect_nightlies(&self) -> anyhow::Result<BisectionResult> {
if self.args.alt {
bail!("cannot bisect nightlies with --alt: not supported");
}
let dl_spec = DownloadParams::for_nightly(self);
// before this date we didn't have -std packages
let end_at = NaiveDate::from_ymd_opt(2015, 10, 20).unwrap();
// The date where a passing build is first found. This becomes
// the new start point of the bisection range.
let mut first_success = None;
// nightly_date is the date we are currently testing to find the start
// point. The loop below modifies nightly_date towards older dates
// as it tries to find the starting point. It will become the basis
// for setting first_success once a passing toolchain is found.
//
// last_failure is the oldest date where a regression was found while
// walking backwards. This becomes the new endpoint of the bisection
// range.
let (mut nightly_date, mut last_failure) = match self.bounds {
Bounds::SearchNightlyBackwards { end } => (end, end),
Bounds::Commits { .. } => unreachable!(),
Bounds::Dates { start, end } => (start, end),
};
let has_start = self.args.start.is_some();
let mut nightly_iter = NightlyFinderIter::new(nightly_date);
// this loop tests nightly toolchains to:
// (1) validate that start date does not have regression (if defined on command line)
// (2) identify a nightly date range for the bisection routine
//
// The tests here must be constrained to dates after 2015-10-20 (`end_at` date)
// because -std packages were not available prior
while nightly_date > end_at {
let mut t = Toolchain {
spec: ToolchainSpec::Nightly { date: nightly_date },
host: self.args.host.clone(),
std_targets: vec![self.args.host.clone(), self.target.clone()],
};
t.std_targets.sort();
t.std_targets.dedup();
if t.is_current_nightly() {
eprintln!(
"checking {} from the currently installed default nightly \
toolchain as the last failure",
t
);
}
eprintln!("checking the start range to find a passing nightly");
match self.install_and_test(&t, &dl_spec) {
Ok(r) => {
// If Satisfies::No, then the regression was not identified in this nightly.
// Break out of the loop and use this as the start date for the
// bisection range
if r == Satisfies::No {
first_success = Some(nightly_date);
break;
} else if has_start {
// If this date was explicitly defined on the command line &
// has regression, then this is an error in the test definition.
// The user must re-define the start date and try again
bail!(
"the start of the range ({}) must not reproduce the regression",
t
);
}
last_failure = nightly_date;
nightly_date = nightly_iter.next().unwrap();
}
Err(InstallError::NotFound { .. }) => {
// go back just one day, presumably missing a nightly
nightly_date = nightly_date.pred_opt().unwrap();
eprintln!(
"*** unable to install {}. roll back one day and try again...",
t
);
if has_start {
bail!("could not find {}", t);
}
}
Err(error) => return Err(error.into()),
}
}
let first_success = first_success.context("could not find a nightly that built")?;
// confirm that the end of the date range has the regression
let mut t_end = Toolchain {
spec: ToolchainSpec::Nightly { date: last_failure },
host: self.args.host.clone(),
std_targets: vec![self.args.host.clone(), self.target.clone()],
};
t_end.std_targets.sort();
t_end.std_targets.dedup();
eprintln!("checking the end range to verify it does not pass");
let result_nightly = self.install_and_test(&t_end, &dl_spec)?;
// The regression was not identified in this nightly.
if result_nightly == Satisfies::No {
bail!(
"the end of the range ({}) does not reproduce the regression",
t_end
);
}
let toolchains = toolchains_between(
self,
ToolchainSpec::Nightly {
date: first_success,
},
ToolchainSpec::Nightly { date: last_failure },
);
let found = self.bisect_to_regression(&toolchains, &dl_spec);
Ok(BisectionResult {
dl_spec,
searched: toolchains,
found,
})
}
}
fn toolchains_between(cfg: &Config, a: ToolchainSpec, b: ToolchainSpec) -> Vec<Toolchain> {
match (a, b) {
(ToolchainSpec::Nightly { date: a }, ToolchainSpec::Nightly { date: b }) => {
let mut toolchains = Vec::new();
let mut date = a;
let mut std_targets = vec![cfg.args.host.clone(), cfg.target.clone()];
std_targets.sort();
std_targets.dedup();
while date <= b {
let t = Toolchain {
spec: ToolchainSpec::Nightly { date },
host: cfg.args.host.clone(),
std_targets: std_targets.clone(),
};
toolchains.push(t);
date = date.succ_opt().unwrap();
}
toolchains
}
_ => unimplemented!(),
}
}
impl Config {
// CI branch of bisect execution
fn bisect_ci(&self, start: &str, end: &str) -> anyhow::Result<BisectionResult> {
eprintln!("bisecting ci builds starting at {start}, ending at {end}");
self.bisect_ci_via(start, end)
}
fn bisect_ci_via(&self, start_sha: &str, end_sha: &str) -> anyhow::Result<BisectionResult> {
let access = self.args.access.repo();
let start = access.commit(start_sha)?;
let end = access.commit(end_sha)?;
let assert_by_bors = |c: &Commit| -> anyhow::Result<()> {
if c.committer.name != BORS_AUTHOR {
bail!(
"Expected author {} to be {BORS_AUTHOR} for {}.\n \
Make sure specified commits are on the master branch \
and refer to a bors merge commit!",
c.committer.name,
c.sha
);
}
Ok(())
};