use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;
use serde::{Deserialize, Serialize};
use crate::run::{CommandOutcome, E2eStatus, RunState, summarize_verify};
pub const MAX_TERMINAL_FAILURES: usize = 32;
pub const MAX_INTERMEDIATE_NAMES: usize = 8;
pub const ATTEMPT_EXCERPT_MAX: usize = 4_000;
pub const DISPLAY_FAILURE_LIMIT: usize = 6;
pub const LEGACY_FAILED_TWICE_PREFIX: &str =
"[this command failed twice on the same commit; the output below is the second attempt's]";
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct TerminalFailure {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub suite: Option<String>,
pub test: String,
}
impl TerminalFailure {
pub fn display_name(&self) -> String {
match &self.suite {
Some(suite) if !suite.is_empty() => format!("{suite} {}", self.test),
_ => self.test.clone(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct IntermediateNotes {
#[serde(default)]
pub try_failure_count: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub try_failures: Vec<String>,
#[serde(default)]
pub flaky_count: usize,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flaky: Vec<String>,
#[serde(default)]
pub cancelled: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub not_run_count: Option<usize>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub long_running: Vec<String>,
}
impl IntermediateNotes {
pub fn is_empty(&self) -> bool {
self.try_failure_count == 0
&& self.try_failures.is_empty()
&& self.flaky_count == 0
&& self.flaky.is_empty()
&& !self.cancelled
&& self.not_run_count.is_none()
&& self.long_running.is_empty()
}
fn record_try(&mut self, label: String) {
self.try_failure_count += 1;
push_bounded_unique(&mut self.try_failures, label, MAX_INTERMEDIATE_NAMES);
}
fn record_flaky(&mut self, label: String) {
if !self.flaky.contains(&label) {
self.flaky_count += 1;
push_bounded_unique(&mut self.flaky, label, MAX_INTERMEDIATE_NAMES);
}
}
fn record_long_running(&mut self, label: String) {
push_bounded_unique(&mut self.long_running, label, MAX_INTERMEDIATE_NAMES);
}
pub fn summary(&self) -> Option<String> {
let mut parts = Vec::new();
if self.try_failure_count > 0 {
if self.try_failures.is_empty() {
parts.push(format!(
"{} intermediate TRY failure(s)",
self.try_failure_count
));
} else {
parts.push(format!(
"{} intermediate TRY failure(s) ({})",
self.try_failure_count,
join_bounded(&self.try_failures, 3)
));
}
}
if self.flaky_count > 0 {
if self.flaky.is_empty() {
parts.push(format!("{} FLAKY pass(es)", self.flaky_count));
} else {
parts.push(format!(
"{} FLAKY pass(es) ({})",
self.flaky_count,
join_bounded(&self.flaky, 3)
));
}
}
if self.cancelled {
match self.not_run_count {
Some(n) if n > 0 => parts.push(format!("cancelled ({n} test(s) not run)")),
_ => parts.push("cancelled".to_owned()),
}
}
if !self.long_running.is_empty() {
parts.push(format!(
"long-running test(s): {}",
join_bounded(&self.long_running, 3)
));
}
(!parts.is_empty()).then(|| parts.join("; "))
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FailureExtraction {
Confirmed {
failures: Vec<TerminalFailure>,
},
Unknown {
reason: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FailureEvidence {
pub extraction: FailureExtraction,
#[serde(default)]
pub intermediate: IntermediateNotes,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AttemptEvidence {
pub attempt: u8,
pub code: Option<i32>,
#[serde(default)]
pub duration_ms: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub artifact: Option<String>,
#[serde(default)]
pub excerpt: String,
pub extraction: FailureExtraction,
#[serde(default)]
pub intermediate: IntermediateNotes,
}
impl AttemptEvidence {
pub fn from_outcome(attempt: u8, outcome: &CommandOutcome) -> Self {
let (extraction, intermediate) = match &outcome.failure_evidence {
Some(ev) => (ev.extraction.clone(), ev.intermediate.clone()),
None => (
FailureExtraction::Unknown {
reason: "no raw failure extraction recorded".to_owned(),
},
IntermediateNotes::default(),
),
};
Self {
attempt,
code: outcome.code,
duration_ms: outcome.duration_ms,
artifact: outcome.artifact.clone(),
excerpt: summarize_verify(&outcome.output_tail, ATTEMPT_EXCERPT_MAX),
extraction,
intermediate,
}
}
pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
let mut copy = self.clone();
copy.excerpt = scrub(©.excerpt);
copy
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ComparisonVerdict {
Matching {
failures: Vec<TerminalFailure>,
},
Distinct {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
common: Vec<TerminalFailure>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
first_only: Vec<TerminalFailure>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
second_only: Vec<TerminalFailure>,
},
Unknown {
reason: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RerunComparison {
pub head: String,
pub first: AttemptEvidence,
pub second: AttemptEvidence,
pub verdict: ComparisonVerdict,
}
impl RerunComparison {
pub fn scrubbed(&self, scrub: impl Fn(&str) -> String) -> Self {
Self {
head: self.head.clone(),
first: self.first.scrubbed(&scrub),
second: self.second.scrubbed(&scrub),
verdict: self.verdict.clone(),
}
}
}
pub fn legacy_failed_twice(output_tail: &str) -> bool {
output_tail
.trim_start()
.starts_with(LEGACY_FAILED_TWICE_PREFIX)
}
pub fn strip_ansi(line: &str) -> String {
let line = line.strip_suffix('\r').unwrap_or(line);
let mut out = String::with_capacity(line.len());
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
match chars.peek().copied() {
Some('[') => {
chars.next();
for ch in chars.by_ref() {
if ('@'..='~').contains(&ch) {
break;
}
}
}
Some(']') => {
chars.next();
while let Some(ch) = chars.next() {
if ch == '\x07' {
break;
}
if ch == '\x1b' && chars.peek() == Some(&'\\') {
chars.next();
break;
}
}
}
_ => {}
}
} else {
out.push(c);
}
}
out
}
pub fn extract_streams(
code: Option<i32>,
build_failed: bool,
stdout: &str,
stderr: &str,
) -> FailureEvidence {
let out_lines: Vec<String> = stdout.lines().map(strip_ansi).collect();
let err_lines: Vec<String> = stderr.lines().map(strip_ansi).collect();
extract_line_streams(code, build_failed, &[&out_lines, &err_lines])
}
pub fn extract_combined(code: Option<i32>, build_failed: bool, body: &str) -> FailureEvidence {
let lines: Vec<String> = body.lines().map(strip_ansi).collect();
extract_line_streams(code, build_failed, &[&lines])
}
fn extract_line_streams(
code: Option<i32>,
build_failed: bool,
streams: &[&[String]],
) -> FailureEvidence {
let mut intermediate = IntermediateNotes::default();
let mut libtest_total = LibtestSummary::default();
let mut nextest_total = NextestSummary::default();
for lines in streams {
let (lib, captured_ranges) = parse_libtest_stream(lines, &mut intermediate);
libtest_total.merge(lib);
let nx = parse_nextest_stream(lines, &captured_ranges, &mut intermediate);
nextest_total.merge(nx);
}
if libtest_total.runs == 1 && libtest_total.suites == 1 {
for failure in &mut libtest_total.failures {
if failure.suite.is_none() {
failure.suite.clone_from(&libtest_total.only_suite);
}
}
}
let extraction = if code.is_none() {
FailureExtraction::Unknown {
reason: "command timed out or terminated without an exit code".to_owned(),
}
} else if code == Some(0) {
FailureExtraction::Unknown {
reason: "command exited 0".to_owned(),
}
} else if build_failed {
FailureExtraction::Unknown {
reason: "command failed to build or link".to_owned(),
}
} else if libtest_total.incomplete || nextest_total.incomplete {
FailureExtraction::Unknown {
reason: "test run did not finish with a final summary".to_owned(),
}
} else if libtest_total.overflow || nextest_total.overflow {
FailureExtraction::Unknown {
reason: format!(
"more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
),
}
} else if libtest_total.inconsistent || nextest_total.inconsistent {
FailureExtraction::Unknown {
reason: "reported failure count did not match listed terminal failures".to_owned(),
}
} else if libtest_total.failed_runs > 0 && nextest_total.failed_runs > 0 {
FailureExtraction::Unknown {
reason: "multiple test runners reported failures in one command; completeness cannot be confirmed"
.to_owned(),
}
} else if nextest_total.failed_runs > 0 {
finalize_confirmed(nextest_total.expected_failures, nextest_total.failures)
} else if libtest_total.failed_runs > 0 {
finalize_confirmed(libtest_total.expected_failures, libtest_total.failures)
} else {
FailureExtraction::Unknown {
reason: "command exited non-zero without a complete failing test summary".to_owned(),
}
};
FailureEvidence {
extraction,
intermediate,
}
}
fn finalize_confirmed(expected: usize, raw: Vec<TerminalFailure>) -> FailureExtraction {
if expected == 0 || raw.is_empty() {
return FailureExtraction::Unknown {
reason: "no terminal test failures were listed in the final summary".to_owned(),
};
}
if expected > MAX_TERMINAL_FAILURES || raw.len() > MAX_TERMINAL_FAILURES {
return FailureExtraction::Unknown {
reason: format!(
"more than {MAX_TERMINAL_FAILURES} terminal test failures reported; complete comparison unavailable"
),
};
}
let set: BTreeSet<TerminalFailure> = raw.into_iter().collect();
if set.len() != expected {
return FailureExtraction::Unknown {
reason: format!(
"reported failure count ({expected}) did not match distinct terminal failures ({})",
set.len()
),
};
}
FailureExtraction::Confirmed {
failures: set.into_iter().collect(),
}
}
pub fn compare_attempts(
head: &str,
first: &CommandOutcome,
second: &CommandOutcome,
) -> RerunComparison {
let first_ev = AttemptEvidence::from_outcome(1, first);
let second_ev = AttemptEvidence::from_outcome(2, second);
let verdict = match (&first_ev.extraction, &second_ev.extraction) {
(
FailureExtraction::Confirmed { failures: f1 },
FailureExtraction::Confirmed { failures: f2 },
) if !f1.is_empty() && !f2.is_empty() => {
if f1.iter().chain(f2).any(|f| f.suite.is_none()) {
ComparisonVerdict::Unknown {
reason: "terminal failure has no confirmed test binary".to_owned(),
}
} else if f1 == f2 {
ComparisonVerdict::Matching {
failures: f1.clone(),
}
} else {
let s1: BTreeSet<&TerminalFailure> = f1.iter().collect();
let s2: BTreeSet<&TerminalFailure> = f2.iter().collect();
let common = s1.intersection(&s2).map(|f| (*f).clone()).collect();
let first_only = s1.difference(&s2).map(|f| (*f).clone()).collect();
let second_only = s2.difference(&s1).map(|f| (*f).clone()).collect();
ComparisonVerdict::Distinct {
common,
first_only,
second_only,
}
}
}
(FailureExtraction::Unknown { reason: r1 }, FailureExtraction::Unknown { reason: r2 }) => {
ComparisonVerdict::Unknown {
reason: if r1 == r2 {
format!("both attempts: {r1}")
} else {
format!("attempt 1: {r1}; attempt 2: {r2}")
},
}
}
(FailureExtraction::Unknown { reason }, _) => ComparisonVerdict::Unknown {
reason: format!("attempt 1: {reason}"),
},
(_, FailureExtraction::Unknown { reason }) => ComparisonVerdict::Unknown {
reason: format!("attempt 2: {reason}"),
},
_ => ComparisonVerdict::Unknown {
reason: "empty confirmed terminal failure set".to_owned(),
},
};
RerunComparison {
head: head.to_owned(),
first: first_ev,
second: second_ev,
verdict,
}
}
#[derive(Default)]
struct LibtestSummary {
runs: usize,
suites: usize,
only_suite: Option<String>,
failed_runs: usize,
expected_failures: usize,
failures: Vec<TerminalFailure>,
incomplete: bool,
inconsistent: bool,
overflow: bool,
}
impl LibtestSummary {
fn merge(&mut self, other: Self) {
self.runs += other.runs;
self.suites += other.suites;
if other.only_suite.is_some() {
self.only_suite = other.only_suite;
}
self.failed_runs += other.failed_runs;
self.expected_failures += other.expected_failures;
self.failures.extend(other.failures);
self.incomplete |= other.incomplete;
self.inconsistent |= other.inconsistent;
self.overflow |= other.overflow;
}
}
struct ActiveLibtest {
expected_total: usize,
suite: Option<String>,
live_failed: BTreeSet<String>,
in_failures_section: bool,
captured_start: Option<usize>,
collecting_list: bool,
current_list: Vec<String>,
last_valid_closing: Option<(usize, usize, Vec<String>)>,
saw_overflow: bool,
}
struct LibtestResultLine {
ok: bool,
passed: usize,
failed: usize,
ignored: usize,
measured: usize,
}
impl LibtestResultLine {
fn total(&self) -> usize {
self.passed + self.failed + self.ignored + self.measured
}
}
fn parse_libtest_stream(
lines: &[String],
intermediate: &mut IntermediateNotes,
) -> (LibtestSummary, Vec<(usize, usize)>) {
let mut summary = LibtestSummary::default();
let mut captured_ranges: Vec<(usize, usize)> = Vec::new();
let mut pending_suite: Option<String> = None;
let mut active: Option<ActiveLibtest> = None;
let mut standalone_collecting = false;
let mut standalone_list: Vec<String> = Vec::new();
let mut nextest_captured: Option<NextestCapturedMode> = None;
let commit_active = |run: ActiveLibtest,
summary: &mut LibtestSummary,
captured_ranges: &mut Vec<(usize, usize)>| {
if run.saw_overflow {
summary.overflow = true;
} else if let Some((end_line, expected_f, list)) = run.last_valid_closing {
if let Some(start) = run.captured_start {
captured_ranges.push((start, end_line));
}
summary.failed_runs += 1;
summary.expected_failures += expected_f;
for test in list {
summary.failures.push(TerminalFailure {
suite: run.suite.clone(),
test,
});
}
} else {
summary.incomplete = true;
}
};
for (idx, line) in lines.iter().enumerate() {
let trimmed = line.trim();
let top_level = is_top_level(line);
if let Some(run) = active.as_ref()
&& run.in_failures_section
&& run.last_valid_closing.is_some()
&& ((top_level && parse_libtest_running_header(trimmed).is_some())
|| parse_cargo_running_suite(trimmed).is_some()
|| parse_nextest_summary_header(trimmed).is_some()
|| (top_level && is_nextest_rule(trimmed)))
&& let Some(finished) = active.take()
{
commit_active(finished, &mut summary, &mut captured_ranges);
}
if active.is_none() {
if let Some(mode) = parse_nextest_captured_header(line) {
nextest_captured = Some(mode);
continue;
}
if let Some(mode) = nextest_captured {
if top_level && is_nextest_rule(trimmed) {
nextest_captured = None;
continue;
}
match mode {
NextestCapturedMode::Indented => {
if !trimmed.is_empty() && !line.starts_with(" ") {
nextest_captured = None;
} else {
continue;
}
}
NextestCapturedMode::Unindented => {
if trimmed.starts_with("Cancelling due to ")
|| trimmed == "test run cancelled"
|| is_nextest_starting_line(trimmed)
{
nextest_captured = None;
} else {
continue;
}
}
}
}
}
if let Some(run) = active.as_mut() {
if !run.in_failures_section {
if top_level && trimmed == "failures:" {
run.in_failures_section = true;
run.captured_start = Some(idx);
run.collecting_list = true;
run.current_list.clear();
} else if top_level && let Some(name) = parse_libtest_live_failed(trimmed) {
run.live_failed.insert(name);
} else if top_level && let Some(name) = parse_libtest_long_running(trimmed) {
intermediate.record_long_running(name);
} else if top_level && let Some(res) = parse_libtest_result(trimmed) {
if res.ok
&& res.failed == 0
&& res.total() == run.expected_total
&& run.live_failed.is_empty()
{
active = None;
} else {
summary.inconsistent = true;
active = None;
}
} else if (top_level && parse_libtest_running_header(trimmed).is_some())
|| parse_nextest_summary_header(trimmed).is_some()
{
if let Some(unfinished) = active.take() {
commit_active(unfinished, &mut summary, &mut captured_ranges);
}
if top_level && let Some(total) = parse_libtest_running_header(trimmed) {
summary.runs += 1;
active = Some(new_active_libtest(total, pending_suite.take()));
}
}
} else {
if top_level && trimmed == "failures:" {
run.collecting_list = true;
run.current_list.clear();
} else if run.collecting_list {
if line.starts_with(" ")
&& !trimmed.is_empty()
&& !trimmed.starts_with("---- ")
{
if run.current_list.len() <= MAX_TERMINAL_FAILURES {
run.current_list.push(trimmed.to_owned());
}
} else if trimmed.is_empty() {
run.collecting_list = false;
} else if top_level && let Some(res) = parse_libtest_result(trimmed) {
run.collecting_list = false;
try_close_libtest(run, idx, &res);
} else {
run.collecting_list = false;
run.current_list.clear();
}
} else if top_level && let Some(res) = parse_libtest_result(trimmed) {
try_close_libtest(run, idx, &res);
}
}
continue;
}
if let Some(suite) = parse_cargo_running_suite(trimmed) {
summary.suites += 1;
summary.only_suite = Some(suite.clone());
pending_suite = Some(suite);
standalone_collecting = false;
standalone_list.clear();
} else if top_level && let Some(total) = parse_libtest_running_header(trimmed) {
summary.runs += 1;
standalone_collecting = false;
standalone_list.clear();
active = Some(new_active_libtest(total, pending_suite.take()));
} else if top_level && trimmed == "failures:" {
standalone_collecting = true;
standalone_list.clear();
} else if standalone_collecting {
if line.starts_with(" ") && !trimmed.is_empty() && !trimmed.starts_with("---- ") {
if standalone_list.len() <= MAX_TERMINAL_FAILURES {
standalone_list.push(trimmed.to_owned());
}
} else if trimmed.is_empty() {
standalone_collecting = false;
} else if top_level && let Some(res) = parse_libtest_result(trimmed) {
standalone_collecting = false;
record_standalone_libtest(&res, &standalone_list, &mut summary);
standalone_list.clear();
} else {
standalone_collecting = false;
standalone_list.clear();
}
} else if top_level && let Some(res) = parse_libtest_result(trimmed) {
record_standalone_libtest(&res, &standalone_list, &mut summary);
standalone_list.clear();
pending_suite = None;
} else if top_level && let Some(name) = parse_libtest_long_running(trimmed) {
intermediate.record_long_running(name);
}
}
if let Some(run) = active.take() {
commit_active(run, &mut summary, &mut captured_ranges);
}
(summary, captured_ranges)
}
fn new_active_libtest(expected_total: usize, suite: Option<String>) -> ActiveLibtest {
ActiveLibtest {
expected_total,
suite,
live_failed: BTreeSet::new(),
in_failures_section: false,
captured_start: None,
collecting_list: false,
current_list: Vec::new(),
last_valid_closing: None,
saw_overflow: false,
}
}
fn try_close_libtest(run: &mut ActiveLibtest, idx: usize, res: &LibtestResultLine) {
if res.ok || res.failed == 0 || res.total() != run.expected_total {
return;
}
if res.failed > MAX_TERMINAL_FAILURES || run.current_list.len() > MAX_TERMINAL_FAILURES {
run.saw_overflow = true;
return;
}
if run.current_list.len() != res.failed {
return;
}
if !run.live_failed.is_empty()
&& (run.live_failed.len() != res.failed
|| !run.current_list.iter().all(|n| run.live_failed.contains(n)))
{
return;
}
run.last_valid_closing = Some((idx, res.failed, run.current_list.clone()));
}
fn record_standalone_libtest(
res: &LibtestResultLine,
list: &[String],
summary: &mut LibtestSummary,
) {
summary.runs += 1;
if res.ok && res.failed == 0 {
return;
}
if res.failed > MAX_TERMINAL_FAILURES || list.len() > MAX_TERMINAL_FAILURES {
summary.overflow = true;
return;
}
if res.failed == 0 || list.len() != res.failed {
summary.inconsistent = true;
return;
}
summary.failed_runs += 1;
summary.expected_failures += res.failed;
for test in list {
summary.failures.push(TerminalFailure {
suite: None,
test: test.clone(),
});
}
}
fn parse_cargo_running_suite(trimmed: &str) -> Option<String> {
if let Some(rest) = trimmed.strip_prefix("Running ")
&& let Some((label, binary)) = rest.split_once(" (")
&& let Some(binary) = binary.strip_suffix(')')
&& let Some(name) = binary.rsplit(['/', '\\']).next()
&& !label.is_empty()
&& !name.is_empty()
{
return Some(format!("{label} ({name})"));
}
if let Some(rest) = trimmed.strip_prefix("Doc-tests ") {
let label = rest.trim();
if !label.is_empty() {
return Some(format!("doc-tests {label}"));
}
}
None
}
fn parse_libtest_running_header(trimmed: &str) -> Option<usize> {
let rest = trimmed.strip_prefix("running ")?;
let num = rest
.strip_suffix(" tests")
.or_else(|| rest.strip_suffix(" test"))?;
num.parse::<usize>().ok()
}
fn parse_libtest_live_failed(trimmed: &str) -> Option<String> {
let rest = trimmed.strip_prefix("test ")?;
let name = rest.strip_suffix(" ... FAILED")?;
let name = name.strip_suffix(" - should panic").unwrap_or(name).trim();
(!name.is_empty()).then(|| name.to_owned())
}
fn parse_libtest_long_running(trimmed: &str) -> Option<String> {
let rest = trimmed.strip_prefix("test ")?;
let (name, _) = rest.split_once(" has been running for over ")?;
let name = name.trim();
(!name.is_empty()).then(|| name.to_owned())
}
fn parse_libtest_result(trimmed: &str) -> Option<LibtestResultLine> {
let (ok, rest) = if let Some(r) = trimmed.strip_prefix("test result: ok.") {
(true, r)
} else {
(false, trimmed.strip_prefix("test result: FAILED.")?)
};
let mut passed = None;
let mut failed = None;
let mut ignored = 0usize;
let mut measured = 0usize;
for part in rest.split(';') {
let p = part.trim();
if let Some(n) = p.strip_suffix(" passed").and_then(|s| s.parse().ok()) {
passed = Some(n);
} else if let Some(n) = p.strip_suffix(" failed").and_then(|s| s.parse().ok()) {
failed = Some(n);
} else if let Some(n) = p.strip_suffix(" ignored").and_then(|s| s.parse().ok()) {
ignored = n;
} else if let Some(n) = p.strip_suffix(" measured").and_then(|s| s.parse().ok()) {
measured = n;
}
}
Some(LibtestResultLine {
ok,
passed: passed?,
failed: failed?,
ignored,
measured,
})
}
pub(crate) fn contradicts_passing_test(output: &str) -> bool {
let mut saw_result = false;
let mut saw_pass = false;
let mut saw_empty_run = false;
for line in output.lines().map(str::trim) {
if let Some(result) = parse_libtest_result(line) {
if !result.ok || result.failed != 0 {
return true;
}
saw_result = true;
saw_pass |= result.passed != 0;
} else if line == "running 0 tests" {
saw_empty_run = true;
}
}
!saw_pass && (saw_result || saw_empty_run)
}
#[derive(Default)]
struct NextestSummary {
failed_runs: usize,
expected_failures: usize,
failures: Vec<TerminalFailure>,
incomplete: bool,
inconsistent: bool,
overflow: bool,
}
impl NextestSummary {
fn merge(&mut self, other: Self) {
self.failed_runs += other.failed_runs;
self.expected_failures += other.expected_failures;
self.failures.extend(other.failures);
self.incomplete |= other.incomplete;
self.inconsistent |= other.inconsistent;
self.overflow |= other.overflow;
}
}
struct NextestHeader {
expected_failures: usize,
flaky_count: usize,
cancelled: bool,
not_run: Option<usize>,
unrecognized_failure_token: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NextestCapturedMode {
Indented,
Unindented,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NextestProgressToken {
Completed,
RetryPlaceholder,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum NextestStatusKind {
Failure,
Pass,
Flaky,
Cancel,
Other,
}
struct NextestStatusLine {
kind: NextestStatusKind,
attempt: Option<usize>,
progress: Option<NextestProgressToken>,
failure: TerminalFailure,
}
#[derive(Default)]
struct RunTestHistory {
max_attempt: usize,
passed: bool,
try_failures: Vec<usize>,
}
#[derive(Default)]
struct SummaryTestEntries {
bare_failures: usize,
try_failures: Vec<(usize, bool)>,
saw_pass_or_flaky: bool,
max_attempt: usize,
}
fn is_top_level(line: &str) -> bool {
!line.starts_with(' ') && !line.starts_with('\t')
}
fn is_rule_chars(s: &str, min_chars: usize) -> bool {
s.chars().count() >= min_chars && (s.chars().all(|c| c == '-') || s.chars().all(|c| c == '─'))
}
fn is_nextest_rule(trimmed: &str) -> bool {
is_rule_chars(trimmed, 12)
}
fn in_ranges(idx: usize, ranges: &[(usize, usize)]) -> bool {
ranges.iter().any(|&(a, b)| idx >= a && idx <= b)
}
fn flush_run_history(
run_history: &mut BTreeMap<TerminalFailure, RunTestHistory>,
intermediate: &mut IntermediateNotes,
) {
for (failure, exec) in std::mem::take(run_history) {
let distinct_attempts: BTreeSet<usize> = exec.try_failures.into_iter().collect();
for _ in distinct_attempts {
intermediate.record_try(failure.display_name());
}
}
}
fn parse_nextest_stream(
lines: &[String],
libtest_captured: &[(usize, usize)],
intermediate: &mut IntermediateNotes,
) -> NextestSummary {
let mut summary = NextestSummary::default();
let mut in_captured: Option<NextestCapturedMode> = None;
let mut started_open = false;
let mut saw_summary_flaky = 0usize;
let mut run_history: BTreeMap<TerminalFailure, RunTestHistory> = BTreeMap::new();
let mut i = 0usize;
while i < lines.len() {
if in_ranges(i, libtest_captured) {
i += 1;
continue;
}
let line = &lines[i];
let trimmed = line.trim();
let top_level = is_top_level(line);
if let Some(mode) = parse_nextest_captured_header(line) {
in_captured = Some(mode);
i += 1;
continue;
}
if top_level && is_nextest_rule(trimmed) {
in_captured = None;
i += 1;
continue;
}
if let Some(mode) = in_captured {
match mode {
NextestCapturedMode::Indented => {
if !trimmed.is_empty() && !line.starts_with(" ") {
in_captured = None;
} else {
i += 1;
continue;
}
}
NextestCapturedMode::Unindented => {
if trimmed.starts_with("Cancelling due to ")
|| trimmed == "test run cancelled"
|| is_nextest_starting_line(trimmed)
{
in_captured = None;
} else {
i += 1;
continue;
}
}
}
}
if is_nextest_starting_line(trimmed) {
if started_open {
summary.incomplete = true;
flush_run_history(&mut run_history, intermediate);
}
started_open = true;
i += 1;
continue;
}
if trimmed.starts_with("Cancelling due to ") || trimmed == "test run cancelled" {
intermediate.cancelled = true;
i += 1;
continue;
}
if let Some(header) = parse_nextest_summary_header(trimmed) {
started_open = false;
if header.cancelled {
intermediate.cancelled = true;
}
if let Some(not_run) = header.not_run {
intermediate.not_run_count =
Some(intermediate.not_run_count.unwrap_or(0) + not_run);
}
saw_summary_flaky += header.flaky_count;
if header.unrecognized_failure_token {
summary.inconsistent = true;
}
let mut summary_tests: BTreeMap<TerminalFailure, SummaryTestEntries> = BTreeMap::new();
let mut block_inconsistent = false;
let mut j = i + 1;
while j < lines.len() && !in_ranges(j, libtest_captured) {
let next_line = &lines[j];
let next_trimmed = next_line.trim();
if parse_nextest_captured_header(next_line) == Some(NextestCapturedMode::Indented) {
j += 1;
while j < lines.len() && !in_ranges(j, libtest_captured) {
let cap_line = &lines[j];
let cap_trimmed = cap_line.trim();
if parse_nextest_captured_header(cap_line)
== Some(NextestCapturedMode::Indented)
|| cap_trimmed.is_empty()
|| cap_line.starts_with(" ")
{
j += 1;
} else {
break;
}
}
continue;
}
if next_trimmed.is_empty()
|| (is_top_level(next_line) && is_nextest_rule(next_trimmed))
|| next_trimmed.starts_with("error:")
|| next_trimmed.starts_with("[cargo-make]")
|| parse_nextest_summary_header(next_trimmed).is_some()
{
break;
}
let Some(parsed) = parse_nextest_status_line(next_trimmed) else {
break;
};
let entry = summary_tests.entry(parsed.failure.clone()).or_default();
if let Some(attempt) = parsed.attempt {
entry.max_attempt = entry.max_attempt.max(attempt);
}
match parsed.kind {
NextestStatusKind::Failure => {
let is_placeholder =
parsed.progress == Some(NextestProgressToken::RetryPlaceholder);
if let Some(attempt) = parsed.attempt {
entry.try_failures.push((attempt, is_placeholder));
} else if is_placeholder {
block_inconsistent = true;
} else {
entry.bare_failures += 1;
}
}
NextestStatusKind::Flaky => {
entry.saw_pass_or_flaky = true;
intermediate.record_flaky(parsed.failure.display_name());
}
NextestStatusKind::Pass => {
entry.saw_pass_or_flaky = true;
}
NextestStatusKind::Cancel => {
intermediate.cancelled = true;
}
NextestStatusKind::Other => {}
}
j += 1;
}
let mut block_failures = Vec::new();
for (failure, entry) in summary_tests {
let exec = run_history.remove(&failure).unwrap_or_default();
let combined_max_attempt = entry.max_attempt.max(exec.max_attempt);
let reached_pass = entry.saw_pass_or_flaky || exec.passed;
let mut resolved_terminal_attempt: Option<usize> = None;
let mut is_terminal_failure = false;
if entry.bare_failures > 0 {
if entry.bare_failures > 1 || reached_pass {
block_inconsistent = true;
} else {
is_terminal_failure = true;
}
} else if !entry.try_failures.is_empty() && !reached_pass {
let eligible: Vec<usize> = entry
.try_failures
.iter()
.filter(|&&(attempt, is_placeholder)| {
!is_placeholder && attempt >= combined_max_attempt
})
.map(|&(attempt, _)| attempt)
.collect();
if let Some(&max_eligible) = eligible.iter().max() {
let count_at_max = eligible.iter().filter(|&&a| a == max_eligible).count();
if count_at_max > 1 {
block_inconsistent = true;
} else {
is_terminal_failure = true;
resolved_terminal_attempt = Some(max_eligible);
}
}
}
if is_terminal_failure {
block_failures.push(failure.clone());
}
let mut intermediate_attempts: BTreeSet<usize> = BTreeSet::new();
for attempt in exec.try_failures {
if Some(attempt) != resolved_terminal_attempt {
intermediate_attempts.insert(attempt);
}
}
for (attempt, _) in entry.try_failures {
if Some(attempt) != resolved_terminal_attempt {
intermediate_attempts.insert(attempt);
}
}
for _ in intermediate_attempts {
intermediate.record_try(failure.display_name());
}
}
flush_run_history(&mut run_history, intermediate);
if header.expected_failures > MAX_TERMINAL_FAILURES
|| block_failures.len() > MAX_TERMINAL_FAILURES
{
summary.overflow = true;
} else if block_inconsistent {
summary.inconsistent = true;
} else if header.expected_failures == 0 {
if !block_failures.is_empty() {
summary.inconsistent = true;
}
} else if block_failures.len() != header.expected_failures {
summary.inconsistent = true;
} else {
summary.failed_runs += 1;
summary.expected_failures += header.expected_failures;
summary.failures.extend(block_failures);
}
i = j;
continue;
}
if let Some(parsed) = parse_nextest_status_line(trimmed) {
let hist = run_history.entry(parsed.failure.clone()).or_default();
if let Some(attempt) = parsed.attempt {
hist.max_attempt = hist.max_attempt.max(attempt);
}
match parsed.kind {
NextestStatusKind::Failure => {
if let Some(attempt) = parsed.attempt {
hist.try_failures.push(attempt);
}
}
NextestStatusKind::Pass => {
hist.passed = true;
}
NextestStatusKind::Flaky => {
hist.passed = true;
intermediate.record_flaky(parsed.failure.display_name());
}
NextestStatusKind::Cancel => intermediate.cancelled = true,
NextestStatusKind::Other => {}
}
}
i += 1;
}
flush_run_history(&mut run_history, intermediate);
if saw_summary_flaky > intermediate.flaky_count {
intermediate.flaky_count = saw_summary_flaky;
}
if started_open {
summary.incomplete = true;
}
summary
}
fn parse_nextest_captured_header(line: &str) -> Option<NextestCapturedMode> {
let trimmed = line.trim();
if line.starts_with(" ") && !line.starts_with(" ") {
for prefix in ["stdout ", "stderr ", "combined "] {
if let Some(rest) = trimmed.strip_prefix(prefix)
&& is_rule_chars(rest.trim(), 2)
{
return Some(NextestCapturedMode::Indented);
}
}
return None;
}
if !is_top_level(line) {
return None;
}
for delim in ["──", "--"] {
if let Some(inner) = trimmed
.strip_prefix(delim)
.and_then(|s| s.strip_suffix(delim))
{
let inner = inner.trim_matches(['─', '-']).trim();
if matches!(inner, "stdout" | "stderr" | "combined") {
return Some(NextestCapturedMode::Unindented);
}
}
}
for delim in ["---", "───"] {
if let Some(inner) = trimmed
.strip_prefix(delim)
.and_then(|s| s.strip_suffix(delim))
{
let inner = inner.trim();
let stream_part = if let Some(after_try) = inner.strip_prefix("TRY ") {
let mut parts = after_try.splitn(2, char::is_whitespace);
let Some(n) = parts.next() else {
continue;
};
if n.is_empty() || !n.bytes().all(|b| b.is_ascii_digit()) {
continue;
}
parts.next().unwrap_or("").trim_start()
} else {
inner
};
if stream_part.starts_with("STDOUT:")
|| stream_part.starts_with("STDERR:")
|| stream_part.starts_with("COMBINED:")
|| stream_part.starts_with("OUTPUT:")
{
return Some(NextestCapturedMode::Unindented);
}
}
}
None
}
fn is_nextest_starting_line(trimmed: &str) -> bool {
let Some(rest) = trimmed.strip_prefix("Starting ") else {
return false;
};
let mut parts = rest.split_whitespace();
let Some(count) = parts.next().and_then(|n| n.parse::<usize>().ok()) else {
return false;
};
count > 0 && matches!(parts.next(), Some("test" | "tests"))
}
fn parse_nextest_summary_header(trimmed: &str) -> Option<NextestHeader> {
let rest = trimmed.strip_prefix("Summary [")?;
let (dur, after) = rest.split_once(']')?;
if !is_duration_token(dur.trim()) {
return None;
}
let (counts_part, details) = after.trim().split_once(':')?;
let run_spec = counts_part
.trim()
.strip_suffix(" tests run")
.or_else(|| counts_part.trim().strip_suffix(" test run"))?;
let mut cancelled = false;
let mut not_run = None;
if let Some((ran, total)) = run_spec.split_once('/') {
let ran: usize = ran.trim().parse().ok()?;
let total: usize = total.trim().parse().ok()?;
if ran < total {
cancelled = true;
not_run = Some(total - ran);
}
} else {
run_spec.trim().parse::<usize>().ok()?;
}
let mut expected_failures = 0usize;
let mut flaky_count = 0usize;
let mut unrecognized_failure_token = false;
for segment in split_top_level_commas(details) {
let seg = segment.trim();
if seg.is_empty() {
continue;
}
let (main, paren) = match seg.split_once('(') {
Some((m, p)) => (m.trim(), Some(p.trim_end_matches(')').trim())),
None => (seg, None),
};
if let Some(p) = paren {
for sub in p.split(',') {
let sub = sub.trim();
if let Some(n) = sub
.strip_suffix(" flaky")
.and_then(|s| s.parse::<usize>().ok())
{
flaky_count += n;
}
if sub.contains("cancel") {
cancelled = true;
}
}
}
let mut words = main.splitn(2, char::is_whitespace);
let Some(n) = words.next().and_then(|s| s.parse::<usize>().ok()) else {
if main.contains("cancel") {
cancelled = true;
}
continue;
};
let label = words.next().unwrap_or("").trim();
match label {
"passed" | "skipped" => {}
"failed" | "timed out" | "exec failed" => expected_failures += n,
"not run" => {
if n > 0 {
cancelled = true;
not_run = Some(not_run.unwrap_or(0).max(n));
}
}
other => {
let lower = other.to_lowercase();
if lower.contains("fail") || lower.contains("abort") || lower.contains("timeout") {
unrecognized_failure_token = true;
}
}
}
}
Some(NextestHeader {
expected_failures,
flaky_count,
cancelled,
not_run,
unrecognized_failure_token,
})
}
fn split_top_level_commas(input: &str) -> Vec<&str> {
let mut parts = Vec::new();
let mut depth = 0usize;
let mut start = 0usize;
for (idx, ch) in input.char_indices() {
match ch {
'(' => depth += 1,
')' => depth = depth.saturating_sub(1),
',' if depth == 0 => {
parts.push(&input[start..idx]);
start = idx + 1;
}
_ => {}
}
}
parts.push(&input[start..]);
parts
}
fn is_duration_token(tok: &str) -> bool {
let Some(num) = tok.strip_suffix('s') else {
return false;
};
!num.is_empty() && num.bytes().all(|b| b.is_ascii_digit() || b == b'.')
}
fn is_nextest_failure_status(status: &str) -> bool {
matches!(
status,
"FAIL" | "TIMEOUT" | "ABORT" | "EXECFAIL" | "LEAK-FAIL" | "FAIL+LEAK"
) || (status.starts_with("SIG")
&& status.len() >= 5
&& status
.bytes()
.all(|b| b.is_ascii_uppercase() || b.is_ascii_digit()))
}
fn parse_flaky_attempt(prefix: &str) -> Option<usize> {
let rest = prefix.strip_prefix("FLAKY ")?.trim();
let (attempt_str, total_str) = rest.split_once('/')?;
let attempt = attempt_str.trim().parse::<usize>().ok()?;
let total_token = total_str.split_whitespace().next()?;
let _total = total_token.parse::<usize>().ok()?;
(attempt > 0).then_some(attempt)
}
fn is_retry_placeholder_chars(s: &str) -> bool {
!s.is_empty() && (s.chars().all(|c| matches!(c, '─' | '-' | '⋯' | '…')) || s == "...")
}
fn strip_nextest_progress_token(rest: &str) -> (Option<NextestProgressToken>, &str) {
let Some(after_open) = rest.strip_prefix('(') else {
return (None, rest);
};
let Some((inner, tail)) = after_open.split_once(')') else {
return (None, rest);
};
let inner_trimmed = inner.trim();
if is_retry_placeholder_chars(inner_trimmed) {
return (
Some(NextestProgressToken::RetryPlaceholder),
tail.trim_start(),
);
}
if let Some((a, b)) = inner.split_once('/') {
let a = a.trim();
let b = b.trim();
if !a.is_empty() && !b.is_empty() && b.bytes().all(|c| c.is_ascii_digit()) {
if a.bytes().all(|c| c.is_ascii_digit()) {
return (Some(NextestProgressToken::Completed), tail.trim_start());
}
if is_retry_placeholder_chars(a) {
return (
Some(NextestProgressToken::RetryPlaceholder),
tail.trim_start(),
);
}
}
}
(None, rest)
}
fn parse_nextest_status_line(trimmed: &str) -> Option<NextestStatusLine> {
let (raw_prefix, after_open) = trimmed.split_once('[')?;
let (dur, rest) = after_open.split_once(']')?;
if !is_duration_token(dur.trim()) {
return None;
}
let prefix = raw_prefix.trim();
let (attempt, kind) = if let Some(after_try) = prefix.strip_prefix("TRY ") {
let mut parts = after_try.split_whitespace();
let attempt_num = parts.next()?.parse::<usize>().ok()?;
let status = parts.next()?;
if attempt_num == 0 || parts.next().is_some() {
return None;
}
let kind = if is_nextest_failure_status(status) {
NextestStatusKind::Failure
} else if matches!(status, "PASS" | "LEAK") {
NextestStatusKind::Pass
} else if matches!(status, "CANCEL" | "CANCELLED" | "TERMINATING") {
NextestStatusKind::Cancel
} else if matches!(status, "SKIP" | "SLOW" | "START") {
NextestStatusKind::Other
} else {
return None;
};
(Some(attempt_num), kind)
} else if prefix == "FLAKY" || prefix.starts_with("FLAKY ") {
(parse_flaky_attempt(prefix), NextestStatusKind::Flaky)
} else if matches!(prefix, "CANCEL" | "CANCELLED" | "TERMINATING") {
(None, NextestStatusKind::Cancel)
} else if matches!(prefix, "PASS" | "LEAK") {
(None, NextestStatusKind::Pass)
} else if matches!(prefix, "SKIP" | "SLOW" | "START")
|| prefix == "RETRY"
|| prefix.starts_with("RETRY ")
{
(None, NextestStatusKind::Other)
} else if is_nextest_failure_status(prefix) {
(None, NextestStatusKind::Failure)
} else {
return None;
};
let (progress, rest) = strip_nextest_progress_token(rest.trim());
let mut parts = rest.split_whitespace();
let suite = parts.next()?;
let test = rest[suite.len()..].trim();
if suite.is_empty() || test.is_empty() {
return None;
}
Some(NextestStatusLine {
kind,
attempt,
progress,
failure: TerminalFailure {
suite: Some(suite.to_owned()),
test: test.to_owned(),
},
})
}
fn push_bounded_unique(list: &mut Vec<String>, item: String, max: usize) {
if list.len() < max && !list.contains(&item) {
list.push(item);
}
}
fn join_bounded(items: &[String], max: usize) -> String {
if items.len() <= max {
return items.join(", ");
}
let shown = items[..max].join(", ");
format!("{shown} (+{} more)", items.len() - max)
}
fn format_failure_list(failures: &[TerminalFailure], max: usize) -> String {
let names: Vec<String> = failures.iter().map(TerminalFailure::display_name).collect();
join_bounded(&names, max)
}
fn format_artifact_pair(c: &RerunComparison) -> Option<String> {
match (&c.first.artifact, &c.second.artifact) {
(Some(a), Some(b)) => Some(format!("attempt 1: {a}, attempt 2: {b}")),
(Some(a), None) => Some(format!("attempt 1: {a}")),
(None, Some(b)) => Some(format!("attempt 2: {b}")),
(None, None) => None,
}
}
fn short_sha(sha: &str) -> &str {
sha.get(..8).unwrap_or(sha)
}
pub fn comparison_headline(c: &RerunComparison) -> String {
let head = short_sha(&c.head);
let artifacts = format_artifact_pair(c)
.map(|a| format!(" ({a})"))
.unwrap_or_default();
match &c.verdict {
ComparisonVerdict::Matching { failures } => format!(
"failed twice on {head} with matching terminal failure(s): {}{artifacts}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT),
),
ComparisonVerdict::Distinct {
common,
first_only,
second_only,
} => {
let mut parts = Vec::new();
if !first_only.is_empty() {
parts.push(format!(
"attempt 1 only: {}",
format_failure_list(first_only, DISPLAY_FAILURE_LIMIT)
));
}
if !second_only.is_empty() {
parts.push(format!(
"attempt 2 only: {}",
format_failure_list(second_only, DISPLAY_FAILURE_LIMIT)
));
}
if !common.is_empty() {
parts.push(format!(
"common: {}",
format_failure_list(common, DISPLAY_FAILURE_LIMIT)
));
}
format!(
"failed twice on {head} with distinct terminal failure(s) ({}){artifacts}",
parts.join("; "),
)
}
ComparisonVerdict::Unknown { reason } => {
let mut known_sides = Vec::new();
if let FailureExtraction::Confirmed { failures } = &c.first.extraction {
known_sides.push(format!(
"attempt 1 terminal failure(s): {}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
));
}
if let FailureExtraction::Confirmed { failures } = &c.second.extraction {
known_sides.push(format!(
"attempt 2 terminal failure(s): {}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
));
}
let detail = if known_sides.is_empty() {
reason.clone()
} else {
format!("{reason}; {}", known_sides.join("; "))
};
format!(
"exited non-zero twice on {head}; terminal failure comparison unknown ({detail}){artifacts}"
)
}
}
}
pub fn outcome_comparison_summary(o: &CommandOutcome) -> Option<String> {
if let Some(c) = &o.rerun_comparison {
return Some(comparison_headline(c));
}
if legacy_failed_twice(&o.output_tail) {
return Some(
"legacy record: command exited non-zero twice without structured attempt comparison (comparison unknown)"
.to_owned(),
);
}
if let Some(ev) = &o.failure_evidence {
match &ev.extraction {
FailureExtraction::Confirmed { failures } if !failures.is_empty() => {
let mut line = format!(
"terminal failure(s): {}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
);
if let Some(inter) = ev.intermediate.summary() {
line.push_str(&format!("; non-terminal: {inter}"));
}
if let Some(art) = &o.artifact {
line.push_str(&format!(" ({art})"));
}
return Some(line);
}
_ => {}
}
}
None
}
pub fn rerun_event_message(context: &str, command: &str, c: &RerunComparison) -> String {
let headline = comparison_headline(c);
let suffix = match &c.verdict {
ComparisonVerdict::Matching { .. } => "the failure reproduced — it stands",
ComparisonVerdict::Distinct { .. } => {
"failures did not match across attempts — verification stays red"
}
ComparisonVerdict::Unknown { .. } => {
"cannot conclude the same failure reproduced — verification stays red"
}
};
format!("{context}: `{command}` {headline}; {suffix}")
}
pub fn format_command_prompt_section(o: &CommandOutcome, max_output: usize) -> String {
if let Some(c) = &o.rerun_comparison {
let mut s = format!("$ {}\n", o.command);
let _ = writeln!(s, "Rerun comparison: {}", comparison_headline(c));
match &c.verdict {
ComparisonVerdict::Matching { .. } => {
s.push_str(
"Both attempts ended with the same confirmed terminal test failure(s).\n",
);
}
ComparisonVerdict::Distinct { .. } => {
s.push_str(
"The two attempts ended with DIFFERENT terminal test failures; do not assume one root cause covers both.\n",
);
}
ComparisonVerdict::Unknown { .. } => {
s.push_str(
"The command exited non-zero twice, but terminal test failures could not be confirmed for both attempts; do not assume the same failure reproduced.\n",
);
}
}
format_attempt_prompt(&mut s, &c.first, ATTEMPT_EXCERPT_MAX);
format_attempt_prompt(&mut s, &c.second, max_output);
return s;
}
if legacy_failed_twice(&o.output_tail) {
let stripped = o
.output_tail
.trim_start()
.strip_prefix(LEGACY_FAILED_TWICE_PREFIX)
.unwrap_or(&o.output_tail)
.trim_start();
return format!(
"$ {}\n[legacy record: command exited non-zero twice without structured attempt comparison; comparison unknown — do not assume the same test failed twice]\n{}\n",
o.command,
summarize_verify(stripped, max_output),
);
}
let mut header = String::new();
if let Some(art) = &o.artifact
&& !o.output_tail.contains(art)
{
let _ = writeln!(header, "[full output: {art}]");
}
if let Some(ev) = &o.failure_evidence {
if let FailureExtraction::Confirmed { failures } = &ev.extraction {
let _ = writeln!(
header,
"[terminal failure(s): {}]",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
);
}
if let Some(inter) = ev.intermediate.summary() {
let _ = writeln!(header, "[non-terminal activity: {inter}]");
}
}
format!(
"$ {}\n{}{}\n",
o.command,
header,
summarize_verify(&o.output_tail, max_output),
)
}
fn format_attempt_prompt(s: &mut String, a: &AttemptEvidence, max_excerpt: usize) {
let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
let art = a
.artifact
.as_deref()
.map(|p| format!(", artifact {p}"))
.unwrap_or_default();
let _ = writeln!(
s,
"\n--- Attempt {} (exit {code}, {}ms{art}) ---",
a.attempt, a.duration_ms
);
match &a.extraction {
FailureExtraction::Confirmed { failures } => {
let _ = writeln!(
s,
"Terminal failure(s): {}",
format_failure_list(failures, MAX_TERMINAL_FAILURES)
);
}
FailureExtraction::Unknown { reason } => {
let _ = writeln!(s, "Terminal failure(s): unknown ({reason})");
}
}
if let Some(inter) = a.intermediate.summary() {
let _ = writeln!(s, "Non-terminal activity (separate from verdict): {inter}");
}
let excerpt = summarize_verify(&a.excerpt, max_excerpt);
if !excerpt.trim().is_empty() {
let _ = writeln!(s, "{excerpt}");
}
}
pub fn format_outcome_cli_lines(o: &CommandOutcome) -> Vec<String> {
let mut lines = Vec::new();
if let Some(c) = &o.rerun_comparison {
lines.push(format!("comparison: {}", comparison_headline(c)));
for a in [&c.first, &c.second] {
let code = a.code.map_or_else(|| "none".to_owned(), |c| c.to_string());
let art = a
.artifact
.as_deref()
.map(|p| format!(" {p}"))
.unwrap_or_default();
let verdict = match &a.extraction {
FailureExtraction::Confirmed { failures } => format!(
"terminal: {}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
),
FailureExtraction::Unknown { reason } => format!("terminal: unknown ({reason})"),
};
let inter = a
.intermediate
.summary()
.map(|m| format!(" [non-terminal: {m}]"))
.unwrap_or_default();
lines.push(format!(
"attempt {} (exit {code}, {}ms{art}): {verdict}{inter}",
a.attempt, a.duration_ms
));
}
} else {
if legacy_failed_twice(&o.output_tail) {
lines.push(
"comparison: unknown (legacy record exited non-zero twice without structured attempt comparison)"
.to_owned(),
);
}
if let Some(art) = &o.artifact {
lines.push(format!("artifact: {art}"));
}
if let Some(ev) = &o.failure_evidence {
match &ev.extraction {
FailureExtraction::Confirmed { failures } => lines.push(format!(
"terminal failure(s): {}",
format_failure_list(failures, DISPLAY_FAILURE_LIMIT)
)),
FailureExtraction::Unknown { reason } => {
lines.push(format!("terminal failure(s): unknown ({reason})"))
}
}
if let Some(inter) = ev.intermediate.summary() {
lines.push(format!("non-terminal: {inter}"));
}
}
}
lines
}
pub fn current_e2e_failure_summary(state: &RunState) -> Option<String> {
if let Some(e) = &state.head_e2e {
if !e.passed {
if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
return Some(format!("current head e2e @ {}: {line}", short_sha(&e.head)));
}
} else {
return None;
}
}
if let Some(e) = &state.gate_repair_e2e {
if !e.passed {
if let Some(line) = summarize_failed_outcomes(&e.outcomes) {
return Some(format!("gate repair e2e @ {}: {line}", short_sha(&e.head)));
}
} else {
return None;
}
}
if let Some(r) = state.reviews.last()
&& r.e2e_status() == E2eStatus::Failed
&& let Some(line) = summarize_failed_outcomes(&r.e2e)
{
let head = r.verified_head.as_deref().unwrap_or(&r.head);
return Some(format!(
"round {} e2e @ {}: {line}",
r.round,
short_sha(head)
));
}
None
}
pub fn summarize_failed_outcomes(outcomes: &[CommandOutcome]) -> Option<String> {
let failing: Vec<&CommandOutcome> = outcomes
.iter()
.filter(|o| !o.ok() && !o.resource_blocked)
.collect();
if failing.is_empty() {
return None;
}
let parts: Vec<String> = failing
.iter()
.take(2)
.map(|o| match outcome_comparison_summary(o) {
Some(detail) => format!("`{}` {detail}", o.command),
None => format!(
"`{}` failed (exit {})",
o.command,
o.code.map_or_else(|| "none".to_owned(), |c| c.to_string())
),
})
.collect();
Some(parts.join("; "))
}
#[cfg(test)]
mod tests {
use super::*;
fn outcome(code: Option<i32>, raw: &str, artifact: Option<&str>) -> CommandOutcome {
let build_failed = code != Some(0) && raw.contains("error: could not compile");
let evidence = extract_combined(code, build_failed, raw);
CommandOutcome {
command: "cargo make test".to_owned(),
code,
output_tail: summarize_verify(raw, crate::run::VERIFY_SUMMARY),
duration_ms: 1200,
resource_blocked: false,
artifact: artifact.map(str::to_owned),
failure_evidence: Some(evidence),
rerun_comparison: None,
}
}
#[test]
fn nextest_separates_terminal_failures_from_try_flaky_and_cancellations() {
let raw = "\
Starting 12 tests across 3 binaries
\x1b[33m TRY 1 FAIL\x1b[0m [ 0.500s] magi-cli::chat_notify test_flaky_one
\x1b[33m FLAKY 2/3\x1b[0m [ 0.400s] magi-cli::chat_notify test_flaky_one
TRY 1 FAIL [ 1.000s] magi-cli::isolated_build_cache test_cache
TRY 2 FAIL [ 1.000s] magi-cli::isolated_build_cache test_cache
\x1b[31m FAIL\x1b[0m [ 1.200s] magi-cli::isolated_build_cache test_cache
Cancelling due to test failure: 2 tests still running
CANCEL [ 0.000s] magi-cli::web_render test_other
------------
Summary [ 10.500s] 5/12 tests run: 4 passed (1 flaky), 1 failed, 0 skipped
FAIL [ 1.200s] magi-cli::isolated_build_cache test_cache
TRY 1 FAIL [ 1.000s] magi-cli::isolated_build_cache test_cache
FLAKY 2/3 [ 0.400s] magi-cli::chat_notify test_flaky_one
error: test run failed
";
let ev = extract_combined(Some(100), false, raw);
assert_eq!(
ev.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("magi-cli::isolated_build_cache".to_owned()),
test: "test_cache".to_owned(),
}]
}
);
assert!(ev.intermediate.try_failure_count >= 2);
assert_eq!(ev.intermediate.flaky_count, 1);
assert!(ev.intermediate.cancelled);
assert_eq!(ev.intermediate.not_run_count, Some(7));
}
#[test]
fn typography_0b11_scenario_distinguishes_unit_failure_from_nextest_failure() {
let attempt1_out = "\
running 2 tests
test ok_test ... ok
test talk::tests::chat_timeout ... FAILED
failures:
---- talk::tests::chat_timeout stdout ----
thread 'talk::tests::chat_timeout' panicked at src/talk.rs:42:9:
timed out waiting for turn
failures:
talk::tests::chat_timeout
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 5.01s
";
let attempt1_err =
"Running unittests src/lib.rs (target/debug/deps/magi-abc)\nerror: test failed\n";
let ev1 = extract_streams(Some(101), false, attempt1_out, attempt1_err);
let attempt2_out = "\
running 2 tests
test ok_test ... ok
test talk::tests::chat_timeout ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.12s
";
let attempt2_err = "\
Running unittests src/lib.rs (target/debug/deps/magi-abc)
Starting 10 tests across 2 binaries
TRY 1 FAIL [ 0.300s] magi-cli::other test_transient
FLAKY 2/3 [ 0.200s] magi-cli::other test_transient
Cancelling due to test failure: 1 test still running
------------
Summary [ 12.000s] 6/10 tests run: 5 passed (1 flaky), 1 failed, 0 skipped
FAIL [ 2.500s] magi-cli::isolated_build_cache test_isolation
error: test run failed
";
let ev2 = extract_streams(Some(100), false, attempt2_out, attempt2_err);
let o1 = CommandOutcome {
command: "cargo make test".to_owned(),
code: Some(101),
output_tail: attempt1_out.to_owned(),
duration_ms: 5000,
resource_blocked: false,
artifact: Some("artifacts/e2e-3.out".to_owned()),
failure_evidence: Some(ev1),
rerun_comparison: None,
};
let o2 = CommandOutcome {
command: "cargo make test".to_owned(),
code: Some(100),
output_tail: attempt2_err.to_owned(),
duration_ms: 12000,
resource_blocked: false,
artifact: Some("artifacts/e2e-4.out".to_owned()),
failure_evidence: Some(ev2),
rerun_comparison: None,
};
let cmp = compare_attempts("0b11aaaa1234", &o1, &o2);
assert_eq!(
cmp.verdict,
ComparisonVerdict::Distinct {
common: vec![],
first_only: vec![TerminalFailure {
suite: Some("unittests src/lib.rs (magi-abc)".to_owned()),
test: "talk::tests::chat_timeout".to_owned(),
}],
second_only: vec![TerminalFailure {
suite: Some("magi-cli::isolated_build_cache".to_owned()),
test: "test_isolation".to_owned(),
}],
}
);
let headline = comparison_headline(&cmp);
assert!(
headline.contains("distinct terminal failure(s)"),
"{headline}"
);
assert!(headline.contains("talk::tests::chat_timeout"), "{headline}");
assert!(headline.contains("isolated_build_cache"), "{headline}");
assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
let event = rerun_event_message("round 1", "cargo make test", &cmp);
assert!(!event.contains("reproduced"), "{event}");
}
#[test]
fn hang_without_final_summary_is_unknown_not_matching() {
let attempt1_out = "\
running 2 tests
test ok_test ... ok
test talk::tests::chat_timeout has been running for over 60 seconds
";
let ev1 = extract_streams(Some(1), false, attempt1_out, "");
assert!(matches!(ev1.extraction, FailureExtraction::Unknown { .. }));
assert_eq!(
ev1.intermediate.long_running,
vec!["talk::tests::chat_timeout"]
);
let attempt2_err = "\
------------
Summary [ 5.000s] 3 tests run: 2 passed, 1 failed, 0 skipped
FAIL [ 1.000s] magi-cli::isolated_build_cache test_isolation
";
let ev2 = extract_streams(Some(100), false, "", attempt2_err);
assert!(matches!(
ev2.extraction,
FailureExtraction::Confirmed { .. }
));
let o1 = CommandOutcome {
command: "cargo make test".to_owned(),
code: Some(1),
output_tail: attempt1_out.to_owned(),
duration_ms: 60_000,
resource_blocked: false,
artifact: Some("artifacts/e2e-3.out".to_owned()),
failure_evidence: Some(ev1),
rerun_comparison: None,
};
let o2 = CommandOutcome {
command: "cargo make test".to_owned(),
code: Some(100),
output_tail: attempt2_err.to_owned(),
duration_ms: 5_000,
resource_blocked: false,
artifact: Some("artifacts/e2e-4.out".to_owned()),
failure_evidence: Some(ev2),
rerun_comparison: None,
};
let cmp = compare_attempts("deadbeef", &o1, &o2);
assert!(matches!(cmp.verdict, ComparisonVerdict::Unknown { .. }));
let headline = comparison_headline(&cmp);
assert!(headline.contains("comparison unknown"), "{headline}");
assert!(headline.contains("isolated_build_cache"), "{headline}");
assert!(headline.contains("artifacts/e2e-3.out"), "{headline}");
assert!(headline.contains("artifacts/e2e-4.out"), "{headline}");
}
#[test]
fn captured_stdout_cannot_spoof_libtest_or_nextest_verdict() {
let raw = "\
running 2 tests
test ok_test ... ok
test real_test ... FAILED
failures:
---- real_test stdout ----
failures:
fake_test
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
------------
Summary [ 0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
FAIL [ 0.100s] fake::bin fake_nextest
failures:
real_test
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
";
let ev = extract_combined(Some(101), false, raw);
assert_eq!(
ev.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: None,
test: "real_test".to_owned(),
}]
}
);
}
#[test]
fn count_mismatch_and_cap_overflow_yield_unknown() {
let mismatch = "\
------------
Summary [ 1.000s] 2 tests run: 0 passed, 2 failed, 0 skipped
FAIL [ 0.500s] pkg::bin only_one
";
assert!(matches!(
extract_combined(Some(100), false, mismatch).extraction,
FailureExtraction::Unknown { .. }
));
let mut many =
"------------\n Summary [ 1.000s] 40 tests run: 0 passed, 40 failed, 0 skipped\n"
.to_owned();
for i in 0..40 {
let _ = writeln!(many, " FAIL [ 0.010s] pkg::bin test_{i}");
}
assert!(matches!(
extract_combined(Some(100), false, &many).extraction,
FailureExtraction::Unknown { .. }
));
}
#[test]
fn matching_a_to_a_and_multi_binary_libtest() {
let raw = "\
Running tests/alpha.rs (target/debug/deps/alpha-1234)
running 2 tests
test a_ok ... ok
test a_fail ... FAILED
failures:
a_fail
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
Running tests/beta.rs (target/debug/deps/beta-5678)
running 1 test
test b_fail ... FAILED
failures:
b_fail
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
";
let o1 = outcome(Some(101), raw, Some("artifacts/e2e-1.out"));
let o2 = outcome(Some(101), raw, Some("artifacts/e2e-2.out"));
let cmp = compare_attempts("abcdef12", &o1, &o2);
assert_eq!(
cmp.verdict,
ComparisonVerdict::Matching {
failures: vec![
TerminalFailure {
suite: Some("tests/alpha.rs (alpha-1234)".to_owned()),
test: "a_fail".to_owned(),
},
TerminalFailure {
suite: Some("tests/beta.rs (beta-5678)".to_owned()),
test: "b_fail".to_owned(),
},
]
}
);
let event = rerun_event_message("round 1", "cargo test", &cmp);
assert!(event.contains("the failure reproduced"), "{event}");
}
#[test]
fn split_cargo_streams_require_unambiguous_binary_identity() {
let raw = "\
running 1 test
test test_layout ... FAILED
failures:
test_layout
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
";
let alpha = "Running tests/alpha.rs (target/debug/deps/alpha-1234)\n";
let beta = "Running tests/beta.rs (target/debug/deps/beta-5678)\n";
let make = |stderr: &str| {
let mut o = outcome(Some(101), raw, None);
o.failure_evidence = Some(extract_streams(Some(101), false, raw, stderr));
o
};
let a = make(alpha);
assert!(matches!(
compare_attempts("head", &a, &make(alpha)).verdict,
ComparisonVerdict::Matching { .. }
));
assert!(matches!(
compare_attempts("head", &a, &make(beta)).verdict,
ComparisonVerdict::Distinct { .. }
));
let same_label = "Running tests/alpha.rs (target/debug/deps/alpha-9999)\n";
assert!(matches!(
compare_attempts("head", &a, &make(same_label)).verdict,
ComparisonVerdict::Distinct { .. }
));
let ambiguous = make(&format!("{alpha}{beta}"));
for unknown in [make(""), ambiguous] {
assert!(matches!(
compare_attempts("head", &unknown, &unknown).verdict,
ComparisonVerdict::Unknown { .. }
));
}
}
#[test]
fn nextest_captured_libtest_failure_is_not_an_independent_run() {
let raw = "\
Starting 1 test across 1 binary
FAIL [ 0.100s] pkg::bin outer
--- STDOUT: pkg::bin outer ---
error: nested command failed
running 1 test
test inner ... FAILED
failures:
inner
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
------------
Summary [ 0.100s] 1 tests run: 0 passed, 1 failed, 0 skipped
FAIL [ 0.100s] pkg::bin outer
error: test run failed
";
assert_eq!(
extract_streams(Some(100), false, "", raw).extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("pkg::bin".to_owned()),
test: "outer".to_owned(),
}],
}
);
}
#[test]
fn legacy_failed_twice_is_treated_as_unknown() {
let o = CommandOutcome {
command: "cargo make test".to_owned(),
code: Some(1),
output_tail: format!("{LEGACY_FAILED_TWICE_PREFIX}\nsome output"),
duration_ms: 100,
resource_blocked: false,
artifact: None,
failure_evidence: None,
rerun_comparison: None,
};
let summary = outcome_comparison_summary(&o).unwrap();
assert!(summary.contains("comparison unknown"), "{summary}");
assert!(!summary.contains("reproduced"), "{summary}");
}
#[test]
fn nextest_retries_all_three_fail_counts_final_try_as_one_terminal_failure() {
let raw = "\
────────────
Nextest run ID 6593990a-423f-41f7-a282-c227e83a40bd with nextest profile: default
Starting 3510 tests across 20 binaries
TRY 1 FAIL [ 0.520s] (─────────) magi-cli::daemon_urgent urgent_task_preempts_queue
stdout ───
running 1 test
test urgent_task_preempts_queue ... FAILED
failures:
failures:
urgent_task_preempts_queue
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.51s
stderr ───
thread 'urgent_task_preempts_queue' panicked at tests/daemon_urgent.rs:120:9:
assertion failed
TRY 2 FAIL [ 0.480s] (─────────) magi-cli::daemon_urgent urgent_task_preempts_queue
stdout ───
running 1 test
test urgent_task_preempts_queue ... FAILED
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.47s
TRY 3 FAIL [ 0.490s] ( 475/3510) magi-cli::daemon_urgent urgent_task_preempts_queue
stdout ───
running 1 test
test urgent_task_preempts_queue ... FAILED
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.48s
────────────
Summary [ 95.120s] 3510 tests run: 3509 passed, 1 failed, 0 skipped
TRY 3 FAIL [ 0.490s] ( 475/3510) magi-cli::daemon_urgent urgent_task_preempts_queue
error: test run failed
";
let ev = extract_streams(Some(100), false, "", raw);
assert_eq!(
ev.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("magi-cli::daemon_urgent".to_owned()),
test: "urgent_task_preempts_queue".to_owned(),
}],
}
);
assert_eq!(ev.intermediate.try_failure_count, 2);
assert_eq!(
ev.intermediate.try_failures,
vec!["magi-cli::daemon_urgent urgent_task_preempts_queue"]
);
assert_eq!(ev.intermediate.flaky_count, 0);
let other_statuses = "\
------------
Starting 3 tests across 1 binary
TRY 1 TIMEOUT [ 60.000s] (---------) pkg::suite test_timeout
TRY 2 TIMEOUT [ 60.000s] ( 1/3) pkg::suite test_timeout
TRY 1 ABORT [ 0.200s] (---------) pkg::suite test_abort
TRY 2 ABORT [ 0.200s] ( 2/3) pkg::suite test_abort
TRY 1 SIGSEGV [ 0.100s] (---------) pkg::suite test_sigsegv
TRY 2 SIGSEGV [ 0.100s] ( 3/3) pkg::suite test_sigsegv
------------
Summary [ 120.700s] 3 tests run: 0 passed, 3 failed (1 timed out), 0 skipped
TRY 2 TIMEOUT [ 60.000s] ( 1/3) pkg::suite test_timeout
TRY 2 ABORT [ 0.200s] ( 2/3) pkg::suite test_abort
TRY 2 SIGSEGV [ 0.100s] ( 3/3) pkg::suite test_sigsegv
error: test run failed
";
let ev_other = extract_combined(Some(100), false, other_statuses);
assert_eq!(
ev_other.extraction,
FailureExtraction::Confirmed {
failures: vec![
TerminalFailure {
suite: Some("pkg::suite".to_owned()),
test: "test_abort".to_owned(),
},
TerminalFailure {
suite: Some("pkg::suite".to_owned()),
test: "test_sigsegv".to_owned(),
},
TerminalFailure {
suite: Some("pkg::suite".to_owned()),
test: "test_timeout".to_owned(),
},
],
}
);
assert_eq!(ev_other.intermediate.try_failure_count, 3);
}
#[test]
fn nextest_try_1_fail_then_try_2_pass_flaky_has_zero_terminal_failures() {
let flaky_only = "\
────────────
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.040s] (───) magi-cli::web test_flaky
stdout ───
running 1 test
test test_flaky ... FAILED
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.03s
TRY 2 PASS [ 0.024s] (1/1) magi-cli::web test_flaky
────────────
Summary [ 0.080s] 1 test run: 1 passed (1 flaky), 0 skipped
FLAKY 2/3 [ 0.024s] (1/1) magi-cli::web test_flaky
";
let ev_flaky_ok = extract_combined(Some(0), false, flaky_only);
assert!(matches!(
ev_flaky_ok.extraction,
FailureExtraction::Unknown { .. }
));
assert_eq!(ev_flaky_ok.intermediate.try_failure_count, 1);
assert_eq!(ev_flaky_ok.intermediate.flaky_count, 1);
assert_eq!(
ev_flaky_ok.intermediate.flaky,
vec!["magi-cli::web test_flaky"]
);
let ev_flaky_nonzero = extract_combined(Some(100), false, flaky_only);
assert!(matches!(
ev_flaky_nonzero.extraction,
FailureExtraction::Unknown { ref reason }
if reason.contains("without a complete failing test summary")
));
assert_eq!(ev_flaky_nonzero.intermediate.try_failure_count, 1);
assert_eq!(ev_flaky_nonzero.intermediate.flaky_count, 1);
let mixed = "\
────────────
Starting 2 tests across 1 binary
TRY 1 FAIL [ 0.040s] (───) magi-cli::web test_flaky
TRY 1 FAIL [ 0.044s] (───) magi-cli::web test_persistent
TRY 2 PASS [ 0.024s] (1/2) magi-cli::web test_flaky
TRY 2 FAIL [ 0.027s] (───) magi-cli::web test_persistent
TRY 3 FAIL [ 0.024s] (2/2) magi-cli::web test_persistent
────────────
Summary [ 0.110s] 2 tests run: 1 passed (1 flaky), 1 failed, 0 skipped
FLAKY 2/3 [ 0.024s] (1/2) magi-cli::web test_flaky
TRY 3 FAIL [ 0.024s] (2/2) magi-cli::web test_persistent
error: test run failed
";
let ev_mixed = extract_combined(Some(100), false, mixed);
assert_eq!(
ev_mixed.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("magi-cli::web".to_owned()),
test: "test_persistent".to_owned(),
}],
}
);
assert_eq!(ev_mixed.intermediate.try_failure_count, 3);
assert_eq!(ev_mixed.intermediate.flaky_count, 1);
}
#[test]
fn nextest_retries_matching_and_distinct_across_attempts_with_changing_progress() {
let make_nextest = |progress: &str, suite: &str, test: &str| {
format!(
"\
────────────
Starting 3510 tests across 20 binaries
TRY 1 FAIL [ 0.400s] (─────────) {suite} {test}
TRY 2 FAIL [ 0.400s] (─────────) {suite} {test}
TRY 3 FAIL [ 0.410s] ({progress}) {suite} {test}
────────────
Summary [ 80.000s] 3510 tests run: 3509 passed, 1 failed, 0 skipped
TRY 3 FAIL [ 0.410s] ({progress}) {suite} {test}
error: test run failed
"
)
};
let a1 = outcome(
Some(100),
&make_nextest(" 475/3510", "magi-cli::daemon_urgent", "test_urgent"),
Some("artifacts/e2e-1.out"),
);
let a2_same = outcome(
Some(100),
&make_nextest(" 612/3510", "magi-cli::daemon_urgent", "test_urgent"),
Some("artifacts/e2e-2.out"),
);
let a2_diff = outcome(
Some(100),
&make_nextest(" 510/3510", "magi-cli::daemon_urgent", "test_other"),
Some("artifacts/e2e-3.out"),
);
let cmp_match = compare_attempts("deadbeef1234", &a1, &a2_same);
assert_eq!(
cmp_match.verdict,
ComparisonVerdict::Matching {
failures: vec![TerminalFailure {
suite: Some("magi-cli::daemon_urgent".to_owned()),
test: "test_urgent".to_owned(),
}],
}
);
let cmp_distinct = compare_attempts("deadbeef1234", &a1, &a2_diff);
assert_eq!(
cmp_distinct.verdict,
ComparisonVerdict::Distinct {
common: vec![],
first_only: vec![TerminalFailure {
suite: Some("magi-cli::daemon_urgent".to_owned()),
test: "test_urgent".to_owned(),
}],
second_only: vec![TerminalFailure {
suite: Some("magi-cli::daemon_urgent".to_owned()),
test: "test_other".to_owned(),
}],
}
);
}
#[test]
fn nextest_summary_resolves_multiple_try_lines_and_same_test_name_across_suites() {
let raw = "\
────────────
Starting 3 tests across 3 binaries
TRY 1 FAIL [ 0.200s] (───) pkg::suite_a shared_name
TRY 2 FAIL [ 0.200s] (───) pkg::suite_a shared_name
TRY 3 FAIL [ 0.200s] (1/3) pkg::suite_a shared_name
TRY 1 FAIL [ 0.200s] (───) pkg::suite_b shared_name
TRY 2 PASS [ 0.150s] (2/3) pkg::suite_b shared_name
TRY 1 FAIL [ 0.200s] (───) pkg::suite_c shared_name
TRY 2 ABORT [ 0.200s] (3/3) pkg::suite_c shared_name
────────────
Summary [ 1.500s] 3 tests run: 1 passed (1 flaky), 2 failed, 0 skipped
TRY 1 FAIL [ 0.200s] (───) pkg::suite_a shared_name
TRY 2 FAIL [ 0.200s] (───) pkg::suite_a shared_name
TRY 3 FAIL [ 0.200s] (1/3) pkg::suite_a shared_name
TRY 1 FAIL [ 0.200s] (───) pkg::suite_b shared_name
FLAKY 2/3 [ 0.150s] (2/3) pkg::suite_b shared_name
TRY 2 ABORT [ 0.200s] (3/3) pkg::suite_c shared_name
error: test run failed
";
let ev = extract_combined(Some(100), false, raw);
assert_eq!(
ev.extraction,
FailureExtraction::Confirmed {
failures: vec![
TerminalFailure {
suite: Some("pkg::suite_a".to_owned()),
test: "shared_name".to_owned(),
},
TerminalFailure {
suite: Some("pkg::suite_c".to_owned()),
test: "shared_name".to_owned(),
},
],
}
);
assert_eq!(ev.intermediate.try_failure_count, 4);
assert_eq!(ev.intermediate.flaky_count, 1);
}
#[test]
fn nextest_incomplete_placeholder_superseded_or_duplicate_try_yields_unknown() {
let unicode_placeholder_in_summary = "\
────────────
Summary [ 1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 1 FAIL [ 0.500s] (───) pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, unicode_placeholder_in_summary).extraction,
FailureExtraction::Unknown { .. }
));
let ascii_placeholder_in_summary = "\
------------
Summary [ 1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 1 FAIL [ 0.500s] (---) pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, ascii_placeholder_in_summary).extraction,
FailureExtraction::Unknown { .. }
));
let superseded_by_later_attempt = "\
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.500s] pkg::bin test_a
TRY 2 FAIL [ 0.500s] pkg::bin test_a
────────────
Summary [ 1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 1 FAIL [ 0.500s] pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, superseded_by_later_attempt).extraction,
FailureExtraction::Unknown { .. }
));
let superseded_by_pass = "\
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.500s] pkg::bin test_a
TRY 2 PASS [ 0.500s] pkg::bin test_a
────────────
Summary [ 1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 1 FAIL [ 0.500s] pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, superseded_by_pass).extraction,
FailureExtraction::Unknown { .. }
));
let duplicate_terminal_try = "\
────────────
Summary [ 1.000s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 3 FAIL [ 0.500s] (1/1) pkg::bin test_a
TRY 3 FAIL [ 0.500s] (1/1) pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, duplicate_terminal_try).extraction,
FailureExtraction::Unknown { .. }
));
let missing_summary = "\
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.500s] (───) pkg::bin test_a
TRY 2 FAIL [ 0.500s] (───) pkg::bin test_a
TRY 3 FAIL [ 0.500s] (1/1) pkg::bin test_a
";
assert!(matches!(
extract_combined(Some(100), false, missing_summary).extraction,
FailureExtraction::Unknown { ref reason } if reason.contains("final summary")
));
}
#[test]
fn nextest_indented_and_unindented_captured_output_cannot_spoof_summary_or_libtest() {
let indented = "\
────────────
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.044s] (───) magi-cli::suite real_fail
stdout ───
running 1 test
test inner_spoof ... FAILED
failures:
inner_spoof
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
------------
Summary [ 0.010s] 1 test run: 0 passed, 1 failed, 0 skipped
FAIL [ 0.010s] fake::bin fake_summary_fail
stderr ───
thread 'real_fail' panicked at src/lib.rs:10:9:
boom
TRY 2 FAIL [ 0.030s] (───) magi-cli::suite real_fail
TRY 3 FAIL [ 0.030s] (1/1) magi-cli::suite real_fail
────────────
Summary [ 0.150s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 3 FAIL [ 0.030s] (1/1) magi-cli::suite real_fail
error: test run failed
";
let ev = extract_streams(Some(100), false, "", indented);
assert_eq!(
ev.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("magi-cli::suite".to_owned()),
test: "real_fail".to_owned(),
}],
}
);
assert_eq!(ev.intermediate.try_failure_count, 2);
let unindented = "\
────────────
Starting 1 test across 1 binary
TRY 1 FAIL [ 0.044s] (───) magi-cli::suite real_fail
── stdout ──
running 1 test
test inner_spoof ... FAILED
failures:
inner_spoof
test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
Summary [ 0.010s] 1 test run: 0 passed, 1 failed, 0 skipped
FAIL [ 0.010s] fake::bin fake_summary_fail
── stderr ──
thread 'real_fail' panicked at src/lib.rs:10:9:
boom
────────────
Summary [ 0.150s] 1 test run: 0 passed, 1 failed, 0 skipped
TRY 3 FAIL [ 0.030s] (1/1) magi-cli::suite real_fail
error: test run failed
";
let ev_unindented = extract_streams(Some(100), false, "", unindented);
assert_eq!(
ev_unindented.extraction,
FailureExtraction::Confirmed {
failures: vec![TerminalFailure {
suite: Some("magi-cli::suite".to_owned()),
test: "real_fail".to_owned(),
}],
}
);
}
}