1use std::{
12 collections::{BTreeMap, BTreeSet},
13 ffi::OsString,
14 fs,
15 io::Write,
16 path::{Component, Path, PathBuf},
17 process::{Command, Output},
18 sync::{
19 Mutex,
20 atomic::{AtomicUsize, Ordering},
21 },
22 time::Instant,
23};
24
25use serde::Deserialize;
26use supercov_contracts::{
27 AttributionPrecision, ExecutionModel, FrontendAttribution, FrontendLimitation,
28 FrontendLimitationScope, FrontendRunDeclaration, FrontendRunnerDeclaration,
29 LANGUAGE_FRONTEND_PROTOCOL_VERSION, StructuralSource,
30};
31
32use crate::{
33 coverage_analysis::McdcVector,
34 coverage_report::{
35 CoverageManifest, CoverageModelDeclaration, CoveragePhase, CoverageReportRequest,
36 DecisionMeta, DecisionSnapshot, ExecutionScope, ExitCodeInput, PersistedCoverageModel,
37 RawTestResult, RuntimeEvent, RuntimeSnapshot, TestProvenance,
38 },
39 evidence_archive::EvidenceArchiveEntry,
40 rust_project::PreparedRustProject,
41 rust_runtime::{RustProbeObservation, read_rust_probe_directory},
42 rust_test_context::preflight_rust_test_contexts,
43};
44
45#[derive(Debug, Clone, PartialEq)]
46pub struct RustFrontendRun {
47 pub declaration: FrontendRunDeclaration,
48 pub request: CoverageReportRequest,
49 pub exit_code: i32,
50 pub artifacts: usize,
51 pub artifact_files: Vec<PathBuf>,
52 pub build_ms: f64,
53 pub execution_ms: f64,
54}
55
56impl RustFrontendRun {
57 pub fn archive_entries(&self) -> Result<Vec<EvidenceArchiveEntry>, serde_json::Error> {
58 let model = PersistedCoverageModel::from_declaration(
59 self.request
60 .coverage_model
61 .as_ref()
62 .expect("Rust frontend always declares a coverage model"),
63 )
64 .expect("Rust coverage model is contract-valid");
65 let mut entries = vec![
66 EvidenceArchiveEntry {
67 path: "coverage-model.json".into(),
68 contents: serde_json::to_vec(&model)?,
69 },
70 EvidenceArchiveEntry {
71 path: "frontend.json".into(),
72 contents: serde_json::to_vec(&self.declaration)?,
73 },
74 EvidenceArchiveEntry {
75 path: "manifest.json".into(),
76 contents: serde_json::to_vec(&self.request.manifest)?,
77 },
78 ];
79 for (index, result) in self.request.raw_results.iter().enumerate() {
80 entries.push(EvidenceArchiveEntry {
81 path: format!("results/{index:08}/mcdc.json"),
82 contents: serde_json::to_vec(result)?,
83 });
84 }
85 Ok(entries)
86 }
87}
88
89#[derive(Debug)]
90pub enum RustTestRunnerError {
91 UnsupportedCommand(String),
92 Launch(String),
93 CargoFailed(String),
94 CargoJson(String),
95 UnsafeArtifact(String),
96 ListFailed(String),
97 Probe(String),
98 Context(String),
99 UnknownProbe(String),
100 InvalidVector {
101 id: String,
102 expected: usize,
103 actual: usize,
104 },
105 Json(serde_json::Error),
106 Io(String),
107}
108
109impl std::fmt::Display for RustTestRunnerError {
110 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
111 match self {
112 Self::UnsupportedCommand(reason) => formatter.write_str(reason),
113 Self::Launch(reason) => {
114 write!(formatter, "could not launch Rust test process: {reason}")
115 }
116 Self::CargoFailed(reason) => write!(formatter, "Cargo test build failed: {reason}"),
117 Self::CargoJson(reason) => write!(formatter, "invalid Cargo JSON output: {reason}"),
118 Self::UnsafeArtifact(path) => {
119 write!(formatter, "Cargo emitted an unsafe test artifact: {path}")
120 }
121 Self::ListFailed(reason) => {
122 write!(formatter, "could not enumerate Rust tests: {reason}")
123 }
124 Self::Probe(reason) => write!(formatter, "invalid Rust probe evidence: {reason}"),
125 Self::Context(reason) => write!(formatter, "invalid Rust test context: {reason}"),
126 Self::UnknownProbe(id) => write!(
127 formatter,
128 "Rust runtime emitted an unknown obligation: {id}"
129 ),
130 Self::InvalidVector {
131 id,
132 expected,
133 actual,
134 } => write!(
135 formatter,
136 "Rust decision {id} emitted vector width {actual}; expected {expected}"
137 ),
138 Self::Json(error) => write!(formatter, "could not encode Rust evidence: {error}"),
139 Self::Io(reason) => formatter.write_str(reason),
140 }
141 }
142}
143
144impl std::error::Error for RustTestRunnerError {}
145
146impl From<serde_json::Error> for RustTestRunnerError {
147 fn from(value: serde_json::Error) -> Self {
148 Self::Json(value)
149 }
150}
151
152#[derive(Debug, Deserialize)]
153struct CargoMessage {
154 reason: String,
155 #[serde(default)]
156 target: Option<CargoArtifactTarget>,
157 #[serde(default)]
158 profile: Option<CargoArtifactProfile>,
159 executable: Option<PathBuf>,
160 manifest_path: Option<PathBuf>,
161}
162
163#[derive(Debug, Deserialize)]
164struct CargoArtifactTarget {
165 name: String,
166 kind: Vec<String>,
167 src_path: PathBuf,
168}
169
170#[derive(Debug, Deserialize)]
171struct CargoArtifactProfile {
172 test: bool,
173}
174
175#[derive(Debug, Clone)]
176struct TestArtifact {
177 executable: PathBuf,
178 name: String,
179 kind: String,
180 source: String,
181 package_directory: PathBuf,
184}
185
186#[derive(Debug)]
187struct ProcessTask {
188 ordinal: usize,
189 artifact_index: usize,
190 test_index: usize,
191 artifact: TestArtifact,
192 test: String,
193 context_id: u64,
194 directory: PathBuf,
195}
196
197#[derive(Debug)]
198struct ProcessOutcome {
199 task: ProcessTask,
200 output: Output,
201}
202
203fn shell_words(value: &str) -> Result<Vec<String>, RustTestRunnerError> {
204 let mut words = Vec::new();
205 let mut current = String::new();
206 let mut quote = None;
207 let mut escaped = false;
208 for character in value.chars() {
209 if escaped {
210 current.push(character);
211 escaped = false;
212 } else if character == '\\' && quote != Some('\'') {
213 escaped = true;
214 } else if matches!(character, '\'' | '"') {
215 if quote == Some(character) {
216 quote = None;
217 } else if quote.is_none() {
218 quote = Some(character);
219 } else {
220 current.push(character);
221 }
222 } else if character.is_whitespace() && quote.is_none() {
223 if !current.is_empty() {
224 words.push(std::mem::take(&mut current));
225 }
226 } else {
227 current.push(character);
228 }
229 }
230 if escaped || quote.is_some() {
231 return Err(RustTestRunnerError::UnsupportedCommand(
232 "the expanded Cargo command contains an incomplete quote or escape".into(),
233 ));
234 }
235 if !current.is_empty() {
236 words.push(current);
237 }
238 Ok(words)
239}
240
241fn executable_name(value: &str) -> &str {
242 Path::new(value)
243 .file_name()
244 .and_then(|name| name.to_str())
245 .unwrap_or(value)
246 .trim_end_matches(".exe")
247 .trim_end_matches(".cmd")
248}
249
250#[derive(Debug, Clone, PartialEq, Eq)]
251pub(crate) struct CargoTestInvocation {
252 pub program: String,
253 pub kind: RustCargoCommandKind,
254 pub arguments: Vec<String>,
255 pub runner_arguments: Vec<String>,
256}
257
258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
259pub(crate) enum RustCargoCommandKind {
260 CargoTest,
261 NextestRun,
262}
263
264impl CargoTestInvocation {
265 pub(crate) fn command_position(&self) -> Option<usize> {
266 match self.kind {
267 RustCargoCommandKind::CargoTest => self
268 .arguments
269 .iter()
270 .position(|argument| argument == "test"),
271 RustCargoCommandKind::NextestRun => self
272 .arguments
273 .windows(2)
274 .position(|pair| pair == ["nextest", "run"]),
275 }
276 }
277}
278
279#[derive(Debug, Clone, PartialEq, Eq)]
280pub(crate) struct RustLibtestSelection {
281 pub list_arguments: Vec<String>,
282}
283
284#[derive(Debug, Clone, PartialEq, Eq)]
285pub(crate) struct RustCargoExecutionSelection {
286 pub run_libtests: bool,
287 pub run_doctests: bool,
288 pub doctest_arguments: Vec<String>,
289}
290
291#[derive(Debug, Clone, PartialEq, Eq)]
292pub(crate) struct NextestListInvocation {
293 pub arguments: Vec<String>,
294 pub runner_arguments: Vec<String>,
295}
296
297pub(crate) fn nextest_version_arguments(
298 invocation: &CargoTestInvocation,
299) -> Result<Vec<String>, RustTestRunnerError> {
300 if invocation.kind != RustCargoCommandKind::NextestRun {
301 return Err(RustTestRunnerError::UnsupportedCommand(
302 "a nextest version handshake requires `cargo nextest run`".into(),
303 ));
304 }
305 let command = invocation.command_position().ok_or_else(|| {
306 RustTestRunnerError::UnsupportedCommand(
307 "the expanded Cargo invocation lost its nextest run subcommand".into(),
308 )
309 })?;
310 let mut arguments = invocation.arguments[..command].to_vec();
311 arguments.extend(["nextest".into(), "--version".into()]);
312 Ok(arguments)
313}
314
315fn nextest_run_only_option(argument: &str) -> Option<bool> {
316 let name = argument.split_once('=').map_or(argument, |(name, _)| name);
317 match name {
318 "-j"
319 | "--jobs"
320 | "--test-threads"
321 | "--retries"
322 | "--flaky-result"
323 | "--max-fail"
324 | "--no-tests"
325 | "--failure-output"
326 | "--success-output"
327 | "--status-level"
328 | "--final-status-level"
329 | "--show-progress"
330 | "--max-progress-running"
331 | "--message-format"
332 | "--message-format-version" => Some(!argument.contains('=')),
333 "--fail-fast"
334 | "--ff"
335 | "--no-fail-fast"
336 | "--nff"
337 | "--no-capture"
338 | "--nocapture"
339 | "--no-output-indent"
340 | "--hide-progress-bar"
341 | "--no-input-handler" => Some(false),
342 _ if argument.starts_with("-j") && argument.len() > 2 => Some(false),
343 _ => None,
344 }
345}
346
347fn nextest_unsupported_run_option(argument: &str) -> Option<bool> {
348 let name = argument.split_once('=').map_or(argument, |(name, _)| name);
349 match name {
350 "-R"
351 | "--rerun"
352 | "--debugger"
353 | "--tracer"
354 | "--stress-count"
355 | "--stress-duration"
356 | "--archive-file"
357 | "--archive-format"
358 | "--extract-to"
359 | "--cargo-metadata"
360 | "--workspace-remap"
361 | "--binaries-metadata"
362 | "--target-dir-remap"
363 | "--build-dir-remap" => Some(!argument.contains('=')),
364 "--no-run" | "--extract-overwrite" | "--persist-extract-tempdir" => Some(false),
365 _ => None,
366 }
367}
368
369fn nextest_shared_option(argument: &str) -> Option<bool> {
370 let name = argument.split_once('=').map_or(argument, |(name, _)| name);
371 match name {
372 "--color"
373 | "-p"
374 | "--package"
375 | "--exclude"
376 | "--bin"
377 | "--example"
378 | "--test"
379 | "--bench"
380 | "-F"
381 | "--features"
382 | "--build-jobs"
383 | "--cargo-profile"
384 | "--target"
385 | "--target-dir"
386 | "--cargo-message-format"
387 | "--config"
388 | "--timings"
389 | "-Z"
390 | "--run-ignored"
391 | "--partition"
392 | "--platform-filter"
393 | "-E"
394 | "--filterset"
395 | "--filter-expr"
396 | "--manifest-path"
397 | "--config-file"
398 | "--user-config-file"
399 | "--tool-config-file"
400 | "-P"
401 | "--profile" => Some(!argument.contains('=')),
402 "--no-pager"
403 | "-v"
404 | "--verbose"
405 | "--workspace"
406 | "--all"
407 | "--lib"
408 | "--bins"
409 | "--examples"
410 | "--tests"
411 | "--benches"
412 | "--all-targets"
413 | "--all-features"
414 | "--no-default-features"
415 | "-r"
416 | "--release"
417 | "--unit-graph"
418 | "--frozen"
419 | "--locked"
420 | "--offline"
421 | "--cargo-quiet"
422 | "--cargo-verbose"
423 | "--ignore-rust-version"
424 | "--future-incompat-report"
425 | "--ignore-default-filter"
426 | "--override-version-check" => Some(false),
427 _ if argument.starts_with("-p") && argument.len() > 2 => Some(false),
428 _ if argument.starts_with("-F") && argument.len() > 2 => Some(false),
429 _ if argument.starts_with("-E") && argument.len() > 2 => Some(false),
430 _ if argument.starts_with("-P") && argument.len() > 2 => Some(false),
431 _ if argument.starts_with("-Z") && argument.len() > 2 => Some(false),
432 _ if argument.len() > 2
433 && argument.starts_with('-')
434 && argument[1..].bytes().all(|byte| byte == b'v') =>
435 {
436 Some(false)
437 }
438 _ if argument.starts_with("--timings=") => Some(false),
439 _ => None,
440 }
441}
442
443pub(crate) fn nextest_list_invocation(
449 invocation: &CargoTestInvocation,
450) -> Result<NextestListInvocation, RustTestRunnerError> {
451 if invocation.kind != RustCargoCommandKind::NextestRun {
452 return Err(RustTestRunnerError::UnsupportedCommand(
453 "a nextest list projection requires `cargo nextest run`".into(),
454 ));
455 }
456 let command = invocation.command_position().ok_or_else(|| {
457 RustTestRunnerError::UnsupportedCommand(
458 "the expanded Cargo invocation lost its nextest run subcommand".into(),
459 )
460 })?;
461 let mut arguments = invocation.arguments[..command].to_vec();
462 arguments.extend(["nextest".into(), "list".into()]);
463 let mut index = command + 2;
464 while index < invocation.arguments.len() {
465 let argument = &invocation.arguments[index];
466 if argument == "--" {
467 arguments.extend(invocation.arguments[index..].iter().cloned());
468 break;
469 }
470 if let Some(takes_value) = nextest_unsupported_run_option(argument) {
471 if takes_value && invocation.arguments.get(index + 1).is_none() {
472 return Err(RustTestRunnerError::UnsupportedCommand(format!(
473 "nextest option {argument} has no value"
474 )));
475 }
476 return Err(RustTestRunnerError::UnsupportedCommand(format!(
477 "nextest option {argument} cannot yet be assigned exact selected-test identity"
478 )));
479 }
480 if let Some(takes_value) = nextest_run_only_option(argument) {
481 if takes_value {
482 index += 1;
483 if index == invocation.arguments.len() {
484 return Err(RustTestRunnerError::UnsupportedCommand(format!(
485 "nextest option {argument} has no value"
486 )));
487 }
488 }
489 } else if let Some(takes_value) = nextest_shared_option(argument) {
490 arguments.push(argument.clone());
491 if takes_value {
492 index += 1;
493 let value = invocation.arguments.get(index).ok_or_else(|| {
494 RustTestRunnerError::UnsupportedCommand(format!(
495 "nextest option {argument} has no value"
496 ))
497 })?;
498 arguments.push(value.clone());
499 }
500 } else if argument.starts_with('-') {
501 return Err(RustTestRunnerError::UnsupportedCommand(format!(
502 "the pinned nextest run contract does not recognize option {argument}"
503 )));
504 } else {
505 arguments.push(argument.clone());
506 }
507 index += 1;
508 }
509 arguments.extend(["--message-format".into(), "json".into()]);
510 Ok(NextestListInvocation {
511 arguments,
512 runner_arguments: invocation.runner_arguments.clone(),
513 })
514}
515
516pub(crate) fn cargo_invocation(
517 root: &Path,
518 command: &[String],
519) -> Result<CargoTestInvocation, RustTestRunnerError> {
520 let words = if command.iter().any(|word| executable_name(word) == "cargo") {
525 command.to_vec()
526 } else {
527 let expanded = crate::project_discovery::expanded_command(root, command);
528 shell_words(&expanded)?
529 };
530 let cargo = words
531 .iter()
532 .position(|word| executable_name(word) == "cargo")
533 .ok_or_else(|| RustTestRunnerError::UnsupportedCommand(
534 "Rust was detected, but the expanded command does not expose a stable Cargo invocation".into(),
535 ))?;
536 let cargo_test = words[cargo + 1..]
537 .iter()
538 .position(|word| word == "test")
539 .map(|position| cargo + 1 + position);
540 let nextest = words[cargo + 1..]
541 .windows(2)
542 .position(|pair| pair == ["nextest", "run"])
543 .map(|position| cargo + 1 + position);
544 let (kind, command) = match (cargo_test, nextest) {
545 (Some(test), None) => (RustCargoCommandKind::CargoTest, test),
546 (None, Some(nextest)) => (RustCargoCommandKind::NextestRun, nextest),
547 (Some(_), Some(_)) => {
548 return Err(RustTestRunnerError::UnsupportedCommand(
549 "the Cargo invocation ambiguously contains both test and nextest run".into(),
550 ));
551 }
552 (None, None) => {
553 return Err(RustTestRunnerError::UnsupportedCommand(
554 "the owned Rust runner currently requires `cargo test` or `cargo nextest run`; cross remains explicitly unsupported"
555 .into(),
556 ));
557 }
558 };
559 if words[cargo + 1..command]
560 .iter()
561 .any(|word| matches!(word.as_str(), "&&" | "||" | ";" | "|"))
562 {
563 return Err(RustTestRunnerError::UnsupportedCommand(
564 "the Cargo invocation contains a shell boundary before `test`".into(),
565 ));
566 }
567 let command_end = command
568 + if kind == RustCargoCommandKind::NextestRun {
569 1
570 } else {
571 0
572 };
573 let mut arguments = words[cargo + 1..=command_end].to_vec();
574 let mut runner_arguments = Vec::new();
575 let mut after_separator = false;
576 for argument in &words[command_end + 1..] {
577 if argument == "--" && !after_separator {
578 after_separator = true;
579 continue;
580 }
581 if matches!(argument.as_str(), "&&" | "||" | ";" | "|") {
582 return Err(RustTestRunnerError::UnsupportedCommand(
583 "the Cargo test command contains an unsupported shell boundary".into(),
584 ));
585 }
586 if after_separator {
587 runner_arguments.push(argument.clone());
588 } else {
589 arguments.push(argument.clone());
590 }
591 }
592 Ok(CargoTestInvocation {
593 program: words[cargo].clone(),
594 kind,
595 arguments,
596 runner_arguments,
597 })
598}
599
600fn cargo_option_takes_value(argument: &str) -> Option<bool> {
601 let name = argument.split_once('=').map_or(argument, |(name, _)| name);
602 match name {
603 "-p" | "--package" | "--exclude" | "--bin" | "--example" | "--test" | "--bench" | "-F"
604 | "--features" | "-j" | "--jobs" | "--profile" | "--target" | "--target-dir"
605 | "--message-format" | "--color" | "--config" | "-Z" | "--manifest-path" => {
606 Some(!argument.contains('='))
607 }
608 "--no-run"
609 | "--no-fail-fast"
610 | "--future-incompat-report"
611 | "-q"
612 | "--quiet"
613 | "-v"
614 | "--verbose"
615 | "--workspace"
616 | "--all"
617 | "--lib"
618 | "--bins"
619 | "--examples"
620 | "--tests"
621 | "--benches"
622 | "--all-targets"
623 | "--doc"
624 | "--all-features"
625 | "--no-default-features"
626 | "-r"
627 | "--release"
628 | "--timings"
629 | "--ignore-rust-version"
630 | "--locked"
631 | "--offline"
632 | "--frozen" => Some(false),
633 _ if argument.starts_with("-vv") => Some(false),
634 _ if argument.starts_with("-p") && argument.len() > 2 => Some(false),
635 _ if argument.starts_with("-F") && argument.len() > 2 => Some(false),
636 _ if argument.starts_with("-j") && argument.len() > 2 => Some(false),
637 _ => None,
638 }
639}
640
641pub(crate) fn rust_libtest_selection(
642 invocation: &CargoTestInvocation,
643) -> Result<RustLibtestSelection, RustTestRunnerError> {
644 if invocation.kind != RustCargoCommandKind::CargoTest {
645 return Err(RustTestRunnerError::UnsupportedCommand(
646 "libtest selection cannot be reconstructed from a nextest command".into(),
647 ));
648 }
649 let test = invocation
650 .arguments
651 .iter()
652 .position(|argument| argument == "test")
653 .ok_or_else(|| {
654 RustTestRunnerError::UnsupportedCommand(
655 "the expanded Cargo invocation lost its test subcommand".into(),
656 )
657 })?;
658 let mut cargo_filter = None;
659 let mut index = test + 1;
660 while index < invocation.arguments.len() {
661 let argument = &invocation.arguments[index];
662 if argument.starts_with('-') {
663 let takes_value = cargo_option_takes_value(argument).ok_or_else(|| {
664 RustTestRunnerError::UnsupportedCommand(format!(
665 "the pinned Cargo test contract does not recognize option {argument}"
666 ))
667 })?;
668 if takes_value {
669 index += 1;
670 if index == invocation.arguments.len() {
671 return Err(RustTestRunnerError::UnsupportedCommand(format!(
672 "Cargo option {argument} has no value"
673 )));
674 }
675 }
676 } else if cargo_filter.replace(argument.clone()).is_some() {
677 return Err(RustTestRunnerError::UnsupportedCommand(
678 "Cargo test has more than one pre-separator TESTNAME".into(),
679 ));
680 }
681 index += 1;
682 }
683
684 let mut list_arguments = cargo_filter.into_iter().collect::<Vec<_>>();
685 let mut test_threads = None;
686 let mut index = 0;
687 while index < invocation.runner_arguments.len() {
688 let argument = &invocation.runner_arguments[index];
689 match argument.as_str() {
690 "--ignored" | "--include-ignored" | "--exclude-should-panic" | "--test" | "--bench" => {
691 list_arguments.push(argument.clone());
692 }
693 "--exact" => list_arguments.push(argument.clone()),
694 "--skip" => {
695 let value = invocation.runner_arguments.get(index + 1).ok_or_else(|| {
696 RustTestRunnerError::UnsupportedCommand(
697 "libtest --skip has no filter value".into(),
698 )
699 })?;
700 list_arguments.extend([argument.clone(), value.clone()]);
701 index += 1;
702 }
703 _ if argument.starts_with("--skip=") && argument.len() > "--skip=".len() => {
704 list_arguments.push(argument.clone());
705 }
706 "--test-threads" => {
707 let value = invocation.runner_arguments.get(index + 1).ok_or_else(|| {
708 RustTestRunnerError::UnsupportedCommand(
709 "libtest --test-threads has no value".into(),
710 )
711 })?;
712 let parsed = parse_libtest_threads(value)?;
713 if test_threads.replace(parsed).is_some() {
714 return Err(RustTestRunnerError::UnsupportedCommand(
715 "libtest --test-threads was provided more than once".into(),
716 ));
717 }
718 index += 1;
719 }
720 _ if argument.starts_with("--test-threads=") => {
721 let value = &argument["--test-threads=".len()..];
722 let parsed = parse_libtest_threads(value)?;
723 if test_threads.replace(parsed).is_some() {
724 return Err(RustTestRunnerError::UnsupportedCommand(
725 "libtest --test-threads was provided more than once".into(),
726 ));
727 }
728 }
729 "-Z" => {
730 let value = invocation.runner_arguments.get(index + 1).ok_or_else(|| {
731 RustTestRunnerError::UnsupportedCommand(
732 "libtest -Z has no feature value".into(),
733 )
734 })?;
735 list_arguments.extend([argument.clone(), value.clone()]);
740 index += 1;
741 }
742 _ if argument.starts_with("-Z") && argument.len() > 2 => {
743 list_arguments.push(argument.clone());
744 }
745 "--logfile" | "--color" | "--format" | "--shuffle-seed" => {
746 if invocation.runner_arguments.get(index + 1).is_none() {
747 return Err(RustTestRunnerError::UnsupportedCommand(format!(
748 "libtest {argument} has no value"
749 )));
750 }
751 index += 1;
755 }
756 _ if ["--logfile=", "--color=", "--format=", "--shuffle-seed="]
757 .iter()
758 .any(|prefix| argument.starts_with(prefix) && argument.len() > prefix.len()) => {}
759 "--force-run-in-process"
760 | "--fail-fast"
761 | "--no-capture"
762 | "--nocapture"
763 | "-q"
764 | "--quiet"
765 | "--show-output"
766 | "--report-time"
767 | "--ensure-time"
768 | "--shuffle" => {
769 }
773 "--list" | "-h" | "--help" => {
774 return Err(RustTestRunnerError::UnsupportedCommand(format!(
775 "libtest {argument} does not execute a test suite; exact non-execution mode support is not implemented"
776 )));
777 }
778 _ if !argument.starts_with('-') => list_arguments.push(argument.clone()),
779 _ => {
780 return Err(RustTestRunnerError::UnsupportedCommand(format!(
781 "the pinned Rust 1.95 libtest discovery contract does not recognize option {argument}"
782 )));
783 }
784 }
785 index += 1;
786 }
787 Ok(RustLibtestSelection { list_arguments })
788}
789
790fn parse_libtest_threads(value: &str) -> Result<usize, RustTestRunnerError> {
791 match value.parse::<usize>() {
792 Ok(0) => Err(RustTestRunnerError::UnsupportedCommand(
793 "argument for --test-threads must not be 0".into(),
794 )),
795 Ok(value) => Ok(value),
796 Err(error) => Err(RustTestRunnerError::UnsupportedCommand(format!(
797 "argument for --test-threads must be a number > 0 (error: {error})"
798 ))),
799 }
800}
801
802pub(crate) fn rust_cargo_execution_selection(
803 invocation: &CargoTestInvocation,
804) -> Result<RustCargoExecutionSelection, RustTestRunnerError> {
805 if invocation.kind == RustCargoCommandKind::NextestRun {
806 return Ok(RustCargoExecutionSelection {
807 run_libtests: true,
808 run_doctests: false,
809 doctest_arguments: Vec::new(),
810 });
811 }
812 let test = invocation
813 .arguments
814 .iter()
815 .position(|argument| argument == "test")
816 .ok_or_else(|| {
817 RustTestRunnerError::UnsupportedCommand(
818 "the expanded Cargo invocation lost its test subcommand".into(),
819 )
820 })?;
821 let mut doc = false;
822 let mut other_target = false;
823 let mut index = test + 1;
824 while index < invocation.arguments.len() {
825 let argument = &invocation.arguments[index];
826 let name = argument
827 .split_once('=')
828 .map_or(argument.as_str(), |(name, _)| name);
829 match name {
830 "--doc" => doc = true,
831 "--lib" | "--bins" | "--bin" | "--examples" | "--example" | "--tests" | "--test"
832 | "--benches" | "--bench" | "--all-targets" => other_target = true,
833 _ => {}
834 }
835 if argument.starts_with('-') {
836 let takes_value = cargo_option_takes_value(argument).ok_or_else(|| {
837 RustTestRunnerError::UnsupportedCommand(format!(
838 "the pinned Cargo test contract does not recognize option {argument}"
839 ))
840 })?;
841 if takes_value {
842 index += 1;
843 if index == invocation.arguments.len() {
844 return Err(RustTestRunnerError::UnsupportedCommand(format!(
845 "Cargo option {argument} has no value"
846 )));
847 }
848 }
849 }
850 index += 1;
851 }
852 if doc && other_target {
853 return Err(RustTestRunnerError::UnsupportedCommand(
854 "Cargo --doc cannot be combined with another explicit target selection".into(),
855 ));
856 }
857 let run_doctests = doc || !other_target;
858 let run_libtests = !doc;
859 let mut doctest_arguments = invocation.arguments.clone();
860 if run_doctests && !doc {
861 doctest_arguments.insert(test + 1, "--doc".into());
862 }
863 if !invocation.runner_arguments.is_empty() {
864 doctest_arguments.push("--".into());
865 doctest_arguments.extend(invocation.runner_arguments.iter().cloned());
866 }
867 Ok(RustCargoExecutionSelection {
868 run_libtests,
869 run_doctests,
870 doctest_arguments,
871 })
872}
873
874pub(crate) fn relative_source(root: &Path, path: &Path) -> Result<String, RustTestRunnerError> {
875 let relative = path
876 .strip_prefix(root)
877 .map_err(|_| RustTestRunnerError::UnsafeArtifact(path.display().to_string()))?;
878 if relative.as_os_str().is_empty()
879 || relative
880 .components()
881 .any(|part| !matches!(part, Component::Normal(_)))
882 {
883 return Err(RustTestRunnerError::UnsafeArtifact(
884 path.display().to_string(),
885 ));
886 }
887 Ok(relative.to_string_lossy().replace('\\', "/"))
888}
889
890fn build_test_artifacts(
891 project: &PreparedRustProject,
892 command: &[String],
893) -> Result<Vec<TestArtifact>, RustTestRunnerError> {
894 let mut invocation = cargo_invocation(&project.workspace_root, command)?;
895 invocation
896 .arguments
897 .extend(["--no-run".into(), "--message-format=json".into()]);
898 let output = Command::new(&invocation.program)
905 .args(invocation.arguments)
906 .current_dir(&project.workspace_root)
907 .env("CARGO_TARGET_DIR", &project.target_directory)
908 .env("RUSTFLAGS", capped_rustflags())
909 .output()
910 .map_err(|error| RustTestRunnerError::Launch(error.to_string()))?;
911 if !output.status.success() {
912 let rendered = output
916 .stdout
917 .split(|byte| *byte == b'\n')
918 .filter_map(|line| serde_json::from_slice::<serde_json::Value>(line).ok())
919 .filter(|message| {
920 message["reason"] == "compiler-message" && message["message"]["level"] == "error"
921 })
922 .filter_map(|message| message["message"]["rendered"].as_str().map(str::to_owned))
923 .collect::<String>();
924 return Err(RustTestRunnerError::CargoFailed(format!(
925 "{rendered}{}",
926 String::from_utf8_lossy(&output.stderr).trim()
927 )));
928 }
929 let canonical_target = fs::canonicalize(&project.target_directory)
930 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
931 let mut artifacts = Vec::new();
932 for line in output
933 .stdout
934 .split(|byte| *byte == b'\n')
935 .filter(|line| !line.is_empty())
936 {
937 let message: CargoMessage = serde_json::from_slice(line)
938 .map_err(|error| RustTestRunnerError::CargoJson(error.to_string()))?;
939 if message.reason != "compiler-artifact"
940 || !message.profile.as_ref().is_some_and(|profile| profile.test)
941 {
942 continue;
943 }
944 let (Some(executable), Some(target)) = (message.executable, message.target) else {
945 continue;
946 };
947 let executable = fs::canonicalize(&executable)
948 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
949 if !executable.starts_with(&canonical_target)
950 || !fs::metadata(&executable).is_ok_and(|metadata| metadata.is_file())
951 {
952 return Err(RustTestRunnerError::UnsafeArtifact(
953 executable.display().to_string(),
954 ));
955 }
956 let source = fs::canonicalize(target.src_path)
957 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
958 let package_directory = message
959 .manifest_path
960 .as_deref()
961 .and_then(Path::parent)
962 .map_or_else(|| project.workspace_root.clone(), Path::to_path_buf);
963 artifacts.push(TestArtifact {
964 executable,
965 package_directory,
966 name: target.name,
967 kind: if target.kind.iter().any(|kind| kind == "test") {
968 "integration".into()
969 } else {
970 "unit".into()
971 },
972 source: relative_source(&project.workspace_root, &source)?,
973 });
974 }
975 artifacts.sort_by(|left, right| left.executable.cmp(&right.executable));
976 artifacts.dedup_by(|left, right| left.executable == right.executable);
977 if artifacts.is_empty() {
978 return Err(RustTestRunnerError::CargoJson(
979 "Cargo emitted no libtest artifacts".into(),
980 ));
981 }
982 Ok(artifacts)
983}
984
985fn list_tests(
990 executable: &Path,
991 filters: &[String],
992 environment: &[(&'static str, OsString)],
993) -> Result<Vec<String>, RustTestRunnerError> {
994 let output = Command::new(executable)
995 .args(["--list", "--format", "terse"])
996 .args(filters)
997 .envs(environment.iter().map(|(key, value)| (key, value)))
998 .output()
999 .map_err(|error| RustTestRunnerError::Launch(error.to_string()))?;
1000 if !output.status.success() {
1001 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_owned();
1005 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_owned();
1006 let detail = if !stderr.is_empty() {
1007 stderr
1008 } else if !stdout.is_empty() {
1009 format!("no stderr; stdout was {stdout}")
1010 } else {
1011 "no output on either stream".to_owned()
1012 };
1013 return Err(RustTestRunnerError::ListFailed(format!(
1014 "{} exited with {} when asked to --list: {detail}",
1015 executable.display(),
1016 output.status
1017 )));
1018 }
1019 let mut tests = String::from_utf8_lossy(&output.stdout)
1020 .lines()
1021 .filter_map(|line| line.strip_suffix(": test"))
1022 .map(str::to_owned)
1023 .collect::<Vec<_>>();
1024 tests.sort();
1025 tests.dedup();
1026 Ok(tests)
1027}
1028
1029pub(crate) struct RustEvidence {
1032 pub(crate) snapshot: RuntimeSnapshot,
1033 pub(crate) phases: Vec<CoveragePhase>,
1034}
1035
1036struct PendingRecord {
1038 event_type: &'static str,
1039 id: String,
1040 vector: Option<McdcVector>,
1041 sequence: i64,
1042}
1043
1044pub(crate) fn snapshot(
1048 manifest: &CoverageManifest,
1049 directory: &Path,
1050 attempt: &str,
1051) -> Result<RustEvidence, RustTestRunnerError> {
1052 let points = manifest
1053 .points
1054 .iter()
1055 .map(|point| (point.id.as_str(), point))
1056 .collect::<BTreeMap<_, _>>();
1057 let alternatives = manifest
1058 .branches
1059 .iter()
1060 .flat_map(|branch| {
1061 branch
1062 .alternatives
1063 .iter()
1064 .map(|alternative| alternative.id.as_str())
1065 })
1066 .collect::<BTreeSet<_>>();
1067 let decisions = manifest
1068 .decisions
1069 .iter()
1070 .map(|decision| (decision.id.as_str(), decision))
1071 .collect::<BTreeMap<_, _>>();
1072 let mut hits = BTreeSet::new();
1073 let mut vectors = BTreeMap::<String, BTreeSet<(Vec<Option<bool>>, bool)>>::new();
1074 let mut pending = BTreeMap::<u64, Vec<PendingRecord>>::new();
1078 let mut events = Vec::new();
1079 let mut phases = Vec::new();
1080 let mut sequence = 0_i64;
1083 let token = crate::rust_project::manifest_token(manifest);
1088 for (name, observations) in read_rust_probe_directory(directory)
1089 .map_err(|error| RustTestRunnerError::Probe(error.to_string()))?
1090 {
1091 if !name.starts_with(&token) {
1092 continue;
1093 }
1094 for entry in observations {
1095 sequence += 1;
1096 let thread = entry.thread;
1097 match entry.observation {
1098 RustProbeObservation::Hit { id } => {
1099 if !points.contains_key(id.as_str()) && !alternatives.contains(id.as_str()) {
1100 return Err(RustTestRunnerError::UnknownProbe(id));
1101 }
1102 hits.insert(id.clone());
1103 pending.entry(thread).or_default().push(PendingRecord {
1104 event_type: "hit",
1105 id,
1106 vector: None,
1107 sequence,
1108 });
1109 }
1110 RustProbeObservation::Decision {
1111 id,
1112 values,
1113 outcome,
1114 } => {
1115 let Some(meta) = decisions.get(id.as_str()) else {
1116 return Err(RustTestRunnerError::UnknownProbe(id));
1117 };
1118 if values.len() != meta.conditions.len() {
1119 return Err(RustTestRunnerError::InvalidVector {
1120 id,
1121 expected: meta.conditions.len(),
1122 actual: values.len(),
1123 });
1124 }
1125 hits.insert(format!(
1126 "{}:outcome:{}",
1127 meta.id,
1128 if outcome { "true" } else { "false" }
1129 ));
1130 vectors
1131 .entry(meta.id.clone())
1132 .or_default()
1133 .insert((values.clone(), outcome));
1134 pending.entry(thread).or_default().push(PendingRecord {
1135 event_type: "decision",
1136 id,
1137 vector: Some(McdcVector { values, outcome }),
1138 sequence,
1139 });
1140 }
1141 RustProbeObservation::Assertion { id } => {
1142 let Some(point) = points.get(id.as_str()) else {
1145 return Err(RustTestRunnerError::UnknownProbe(id));
1146 };
1147 let witnessed = pending.remove(&thread).unwrap_or_default();
1148 let phase_id = format!("{attempt}:assertion:{sequence}");
1149 phases.push(CoveragePhase {
1150 id: phase_id.clone(),
1151 kind: "assertion".into(),
1152 operation: format!(
1153 "Rust assertion at {}:{}:{}",
1154 point.file, point.line, point.column
1155 ),
1156 source: Some(point.source.clone()),
1157 caused_by_phase_id: None,
1158 started_at_ms: witnessed.first().map_or(sequence, |record| record.sequence),
1159 ended_at_ms: Some(sequence),
1160 status: Some("passed".into()),
1163 error: None,
1164 });
1165 for record in witnessed {
1166 events.push(RuntimeEvent {
1167 event_type: record.event_type.into(),
1168 id: record.id,
1169 vector: record.vector,
1170 timestamp_ms: record.sequence,
1171 phase_id: Some(phase_id.clone()),
1172 statement_id: None,
1173 environment: "server".into(),
1174 });
1175 }
1176 }
1177 }
1178 }
1179 }
1180 let mut decision_snapshots = Vec::new();
1181 for (id, observed) in vectors {
1182 let meta: DecisionMeta = (*decisions[id.as_str()]).clone();
1183 decision_snapshots.push(DecisionSnapshot {
1184 meta,
1185 vectors: observed
1186 .into_iter()
1187 .map(|(values, outcome)| McdcVector { values, outcome })
1188 .collect(),
1189 });
1190 }
1191 Ok(RustEvidence {
1192 snapshot: RuntimeSnapshot {
1193 decisions: decision_snapshots,
1194 hits: hits.into_iter().collect(),
1195 events,
1196 logicals: Vec::new(),
1197 },
1198 phases,
1199 })
1200}
1201
1202fn rust_coverage_model() -> CoverageModelDeclaration {
1203 CoverageModelDeclaration {
1204 language: "rust".into(),
1205 variant: "rust-owned-probes-v1".into(),
1206 name: "supercov-rust-owned-v1".into(),
1207 completeness_meaning: "Every semantics-proven Rust obligation in the owned source denominator was observed; explicit manifest limitations identify unmeasured Rust surfaces.".into(),
1208 measured: vec![
1209 "owned Rust statements and function entries".into(),
1210 "owned atomic condition vectors and decision outcomes".into(),
1211 "exact process-per-libtest attribution".into(),
1212 "exact process-per-doctest attribution".into(),
1213 "evidence a passing assertion of the same thread witnessed".into(),
1214 ],
1215 not_measured: vec![
1216 "macro-expanded and generated Rust code".into(),
1217 "const-evaluated code and unsupported structural branch probes".into(),
1218 "causal linkage to individual actions".into(),
1219 "all input values, semantic partitions, paths, or concurrency interleavings".into(),
1220 "mutation score or assertion fault-detection strength".into(),
1221 ],
1222 }
1223}
1224
1225pub(crate) fn instrumented_stack_environment() -> Vec<(&'static str, &'static str)> {
1237 if std::env::var_os("RUST_MIN_STACK").is_some() {
1238 Vec::new()
1239 } else {
1240 vec![("RUST_MIN_STACK", "16777216")]
1241 }
1242}
1243
1244fn rustc_print_path(request: &str) -> Result<PathBuf, RustTestRunnerError> {
1246 let output = Command::new("rustc")
1247 .args(["--print", request])
1248 .output()
1249 .map_err(|error| {
1250 RustTestRunnerError::Launch(format!("rustc --print {request}: {error}"))
1251 })?;
1252 if !output.status.success() {
1253 return Err(RustTestRunnerError::Launch(format!(
1254 "rustc --print {request} exited with {}",
1255 output.status
1256 )));
1257 }
1258 Ok(PathBuf::from(
1259 String::from_utf8_lossy(&output.stdout).trim(),
1260 ))
1261}
1262
1263pub(crate) fn rustc_sysroot() -> Result<PathBuf, RustTestRunnerError> {
1265 rustc_print_path("sysroot")
1266}
1267
1268pub(crate) fn rustc_target_libdir() -> Result<PathBuf, RustTestRunnerError> {
1272 rustc_print_path("target-libdir")
1273}
1274
1275pub(crate) fn dynamic_library_environment(
1281 target_libdir: &Path,
1282 executable: &Path,
1283) -> Vec<(&'static str, OsString)> {
1284 let variable = if cfg!(target_os = "macos") {
1285 "DYLD_FALLBACK_LIBRARY_PATH"
1286 } else if cfg!(windows) {
1287 "PATH"
1288 } else {
1289 "LD_LIBRARY_PATH"
1290 };
1291 let mut entries = Vec::new();
1292 if let Some(deps) = executable.parent() {
1293 entries.push(deps.to_path_buf());
1294 if let Some(profile) = deps.parent() {
1295 entries.push(profile.to_path_buf());
1296 }
1297 }
1298 entries.push(target_libdir.to_path_buf());
1299 if let Some(existing) = std::env::var_os(variable) {
1300 entries.extend(std::env::split_paths(&existing));
1301 }
1302 match std::env::join_paths(entries) {
1303 Ok(value) => vec![(variable, value)],
1304 Err(_) => Vec::new(),
1305 }
1306}
1307
1308pub(crate) fn capped_rustflags() -> String {
1309 let mut rustflags = std::env::var("RUSTFLAGS").unwrap_or_default();
1310 if !rustflags.is_empty() {
1311 rustflags.push(' ');
1312 }
1313 rustflags.push_str("--cap-lints=warn");
1314 rustflags
1315}
1316
1317pub(crate) fn io_error(error: impl std::fmt::Display) -> RustTestRunnerError {
1318 RustTestRunnerError::Io(error.to_string())
1319}
1320
1321pub(crate) fn libtest_skipped(exit: i32, stdout: &str) -> bool {
1324 exit == 0 && (stdout.contains("running 0 tests") || stdout.contains("; 1 ignored;"))
1325}
1326
1327fn rust_runner_limitations(runner: &str) -> Vec<FrontendLimitation> {
1330 let prefix = if runner == "rust-libtest" {
1331 "rust".to_owned()
1332 } else {
1333 runner.to_owned()
1334 };
1335 vec![
1336 FrontendLimitation {
1337 id: format!("{prefix}-action-linkage-unavailable"),
1338 scopes: vec![FrontendLimitationScope::Action],
1339 reason: "Rust test frameworks expose no general action lifecycle".into(),
1340 },
1341 FrontendLimitation {
1342 id: format!("{prefix}-assertion-linkage-unavailable"),
1343 scopes: vec![FrontendLimitationScope::Assertion],
1344 reason: "assertion macros do not expose a stable per-assertion success lifecycle"
1345 .into(),
1346 },
1347 ]
1348}
1349
1350fn rust_runner_declaration(runner: &str) -> FrontendRunnerDeclaration {
1351 FrontendRunnerDeclaration {
1352 runner: runner.into(),
1353 execution_model: ExecutionModel::ProcessPerTest,
1354 attribution: FrontendAttribution {
1355 run: AttributionPrecision::Exact,
1356 worker: AttributionPrecision::Exact,
1357 test: AttributionPrecision::Exact,
1358 retry: AttributionPrecision::Exact,
1359 phase: AttributionPrecision::Exact,
1360 action: AttributionPrecision::Unavailable,
1361 assertion: AttributionPrecision::Unavailable,
1362 },
1363 limitations: rust_runner_limitations(runner),
1364 }
1365}
1366
1367fn decline_uncompiled_sources(
1376 project: &PreparedRustProject,
1377) -> (CoverageManifest, BTreeSet<String>) {
1378 let mut manifest = project.manifest.clone();
1379 let Some(compiled) = crate::rust_project::compiled_source_files(
1380 &project.workspace_root,
1381 &project.target_directory,
1382 ) else {
1383 return (manifest, BTreeSet::new());
1384 };
1385 let declined = project
1386 .source_files
1387 .iter()
1388 .filter(|file| !compiled.contains(*file))
1389 .cloned()
1390 .collect::<BTreeSet<_>>();
1391 if declined.is_empty()
1394 || project
1395 .crate_roots
1396 .iter()
1397 .all(|root| !compiled.contains(root))
1398 {
1399 return (manifest, BTreeSet::new());
1400 }
1401 let mut unmeasured = manifest.unmeasured.iter().cloned().collect::<BTreeSet<_>>();
1402 unmeasured.extend(
1403 manifest
1404 .points
1405 .iter()
1406 .filter(|point| declined.contains(&point.file))
1407 .map(|point| point.id.clone()),
1408 );
1409 unmeasured.extend(
1410 manifest
1411 .decisions
1412 .iter()
1413 .filter(|decision| declined.contains(&decision.file))
1414 .map(|decision| decision.id.clone()),
1415 );
1416 unmeasured.extend(
1417 manifest
1418 .branches
1419 .iter()
1420 .filter(|branch| declined.contains(&branch.file))
1421 .map(|branch| branch.id.clone()),
1422 );
1423 manifest.unmeasured = unmeasured.into_iter().collect();
1424 manifest.limitations.retain(|limitation| {
1426 limitation
1427 .get("file")
1428 .and_then(|file| file.as_str())
1429 .is_none_or(|file| !declined.contains(file))
1430 });
1431 (manifest, declined)
1432}
1433
1434fn structural_limitations(manifest: &CoverageManifest) -> Vec<String> {
1436 manifest
1437 .limitations
1438 .iter()
1439 .filter_map(|item| {
1440 item.get("id")
1441 .and_then(|value| value.as_str())
1442 .map(str::to_owned)
1443 })
1444 .collect()
1445}
1446
1447pub fn run_prepared_rust_tests(
1448 project: &PreparedRustProject,
1449 command: &[String],
1450 run_id: &str,
1451 generated_at: &str,
1452 diagnostics: &mut dyn Write,
1453) -> Result<RustFrontendRun, RustTestRunnerError> {
1454 let invocation = cargo_invocation(&project.workspace_root, command)?;
1455 let selection = rust_cargo_execution_selection(&invocation)?;
1456 let build_started = Instant::now();
1457 let artifacts = if selection.run_libtests && invocation.kind == RustCargoCommandKind::CargoTest
1461 {
1462 build_test_artifacts(project, command)?
1463 } else {
1464 Vec::new()
1465 };
1466 let build_ms = build_started.elapsed().as_secs_f64() * 1000.0;
1467 let (manifest, declined) = decline_uncompiled_sources(project);
1471 if !declined.is_empty() {
1472 writeln!(
1473 diagnostics,
1474 "[supercov] {} source file(s) this build did not compile are outside the denominator: {}{}",
1475 declined.len(),
1476 declined
1477 .iter()
1478 .take(3)
1479 .cloned()
1480 .collect::<Vec<_>>()
1481 .join(", "),
1482 if declined.len() > 3 { ", ..." } else { "" }
1483 )
1484 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
1485 }
1486 let project = &PreparedRustProject {
1487 manifest,
1488 ..project.clone()
1489 };
1490 let _signal_guard = crate::child_signal_guard::ChildSignalGuard::install()
1494 .map_err(|error| RustTestRunnerError::Launch(error.to_string()))?;
1495 let evidence_root = project
1496 .workspace_root
1497 .join(".supercov/rust-evidence")
1498 .join(run_id);
1499 fs::create_dir_all(&evidence_root)
1500 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
1501 let mut results = Vec::new();
1502 let mut overall_exit = 0;
1503 let execution_started = Instant::now();
1504 if invocation.kind == RustCargoCommandKind::NextestRun {
1505 let outcome = crate::rust_owned_nextest::run_nextest(
1508 project,
1509 &invocation,
1510 &evidence_root.join("nextest"),
1511 run_id,
1512 diagnostics,
1513 )?;
1514 let artifact_count = outcome.artifact_files.len();
1515 return Ok(RustFrontendRun {
1516 declaration: FrontendRunDeclaration {
1517 protocol_version: LANGUAGE_FRONTEND_PROTOCOL_VERSION,
1518 frontend_id: "rust".into(),
1519 frontend_version: "rust-owned-v1".into(),
1520 language: "rust".into(),
1521 structural_source: StructuralSource::OwnedProbes,
1522 runners: vec![rust_runner_declaration("nextest")],
1523 structural_limitations: structural_limitations(&project.manifest),
1524 },
1525 request: CoverageReportRequest {
1526 run_id: run_id.into(),
1527 manifest: project.manifest.clone(),
1528 raw_results: outcome.results,
1529 generated_at: generated_at.into(),
1530 coverage_model: Some(rust_coverage_model()),
1531 integrity: None,
1532 test_exit_code: ExitCodeInput::Present(Some(outcome.exit_code)),
1533 },
1534 exit_code: outcome.exit_code,
1535 artifacts: artifact_count,
1536 artifact_files: outcome.artifact_files,
1537 build_ms,
1538 execution_ms: execution_started.elapsed().as_secs_f64() * 1000.0,
1539 });
1540 }
1541 let libtest_selection = rust_libtest_selection(&invocation)?;
1547 let ignored_mode = libtest_selection
1550 .list_arguments
1551 .iter()
1552 .filter(|argument| {
1553 matches!(
1554 argument.as_str(),
1555 "--ignored" | "--include-ignored" | "--exclude-should-panic"
1556 )
1557 })
1558 .cloned()
1559 .collect::<Vec<_>>();
1560 let mut tasks = Vec::new();
1561 let target_libdir = if artifacts.is_empty() {
1562 PathBuf::new()
1563 } else {
1564 rustc_target_libdir()?
1565 };
1566 for (artifact_index, artifact) in artifacts.iter().enumerate() {
1567 let tests = list_tests(
1568 &artifact.executable,
1569 &libtest_selection.list_arguments,
1570 &dynamic_library_environment(&target_libdir, &artifact.executable),
1571 )?;
1572 let contexts = preflight_rust_test_contexts(tests.clone())
1573 .map_err(|error| RustTestRunnerError::Context(error.to_string()))?;
1574 for (test_index, test) in tests.into_iter().enumerate() {
1575 let directory = evidence_root.join(format!("{artifact_index:04}-{test_index:08}"));
1576 fs::create_dir(&directory)
1577 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
1578 tasks.push(ProcessTask {
1579 ordinal: tasks.len(),
1580 artifact_index,
1581 test_index,
1582 artifact: artifact.clone(),
1583 context_id: contexts[&test],
1584 test,
1585 directory,
1586 });
1587 }
1588 }
1589 let workers = std::thread::available_parallelism()
1590 .map(usize::from)
1591 .unwrap_or(1)
1592 .min(tasks.len().max(1));
1593 let next = AtomicUsize::new(0);
1594 let outcomes = Mutex::new(Vec::<Result<ProcessOutcome, String>>::with_capacity(
1595 tasks.len(),
1596 ));
1597 std::thread::scope(|scope| {
1598 for _ in 0..workers {
1599 scope.spawn(|| {
1600 loop {
1601 let index = next.fetch_add(1, Ordering::Relaxed);
1602 let Some(task) = tasks.get(index) else { break };
1603 let result = crate::child_signal_guard::output(
1604 Command::new(&task.artifact.executable)
1605 .args(["--exact", &task.test])
1614 .args(&ignored_mode)
1615 .current_dir(&task.artifact.package_directory)
1616 .envs(instrumented_stack_environment())
1617 .envs(dynamic_library_environment(
1618 &target_libdir,
1619 &task.artifact.executable,
1620 ))
1621 .env("SUPERCOV_RUST_EVIDENCE_DIR", &task.directory)
1622 .env(
1623 crate::rust_probe_transport::RUST_CONTEXT_ENV,
1624 format!("{:016x}", task.context_id),
1625 ),
1626 )
1627 .map(|output| ProcessOutcome {
1628 task: ProcessTask {
1629 ordinal: task.ordinal,
1630 artifact_index: task.artifact_index,
1631 test_index: task.test_index,
1632 artifact: task.artifact.clone(),
1633 test: task.test.clone(),
1634 context_id: task.context_id,
1635 directory: task.directory.clone(),
1636 },
1637 output,
1638 })
1639 .map_err(|error| error.to_string());
1640 outcomes
1641 .lock()
1642 .expect("Rust test result lock poisoned")
1643 .push(result);
1644 }
1645 });
1646 }
1647 });
1648 let mut outcomes = outcomes
1649 .into_inner()
1650 .map_err(|_| RustTestRunnerError::Io("Rust test result lock poisoned".into()))?
1651 .into_iter()
1652 .map(|result| result.map_err(RustTestRunnerError::Launch))
1653 .collect::<Result<Vec<_>, _>>()?;
1654 outcomes.sort_by_key(|outcome| outcome.task.ordinal);
1655 for outcome in outcomes {
1656 let ProcessTask {
1657 artifact_index,
1658 test_index,
1659 artifact,
1660 test,
1661 directory,
1662 ..
1663 } = outcome.task;
1664 let test_id = format!("{}::{test}", artifact.source);
1668 let worker_id = format!("artifact-{artifact_index:04}");
1669 let attempt_id = format!("{run_id}:{artifact_index:04}:{test_index:08}");
1670 let output = outcome.output;
1671 let exit = output.status.code().unwrap_or(1);
1672 let stdout = String::from_utf8_lossy(&output.stdout);
1673 let skipped = libtest_skipped(exit, &stdout);
1674 if exit != 0 {
1675 writeln!(diagnostics, "[supercov] Rust test failed: {test_id}")
1676 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
1677 diagnostics
1678 .write_all(&output.stdout)
1679 .and_then(|_| diagnostics.write_all(&output.stderr))
1680 .map_err(|error| RustTestRunnerError::Io(error.to_string()))?;
1681 }
1682 if exit != 0 {
1683 overall_exit = exit;
1684 }
1685 let evidence = snapshot(&project.manifest, &directory, &attempt_id)?;
1686 results.push(RawTestResult {
1687 test_id: Some(test_id.clone()),
1688 scope: Some(ExecutionScope {
1689 version: 1,
1690 run_id: run_id.into(),
1691 worker_id,
1692 test_id: test_id.clone(),
1693 test_key: format!("{}::{test}", artifact.source),
1694 retry: 0,
1695 attempt_id,
1696 }),
1697 test: test_id,
1698 test_file: Some(artifact.source.clone()),
1699 title: Some(test),
1700 retry: Some(0),
1701 status: Some(
1702 if exit != 0 {
1703 "failed"
1704 } else if skipped {
1705 "skipped"
1706 } else {
1707 "passed"
1708 }
1709 .into(),
1710 ),
1711 expected_status: Some("passed".into()),
1712 flaky: false,
1713 provenance: TestProvenance {
1714 runner: "rust-libtest".into(),
1715 kind: artifact.kind,
1716 project: Some(artifact.name),
1717 source: "supercov-owned-process-per-test".into(),
1718 },
1719 role: "test".into(),
1720 phases: evidence.phases,
1721 runtime: vec![evidence.snapshot],
1722 browser: Vec::new(),
1723 server: Vec::new(),
1724 });
1725 }
1726 let doctest_results =
1727 if selection.run_doctests && invocation.kind == RustCargoCommandKind::CargoTest {
1728 crate::rust_owned_doctests::run_doctests(
1729 project,
1730 &invocation,
1731 &selection,
1732 &evidence_root.join("doctests"),
1733 run_id,
1734 diagnostics,
1735 &mut overall_exit,
1736 )?
1737 } else {
1738 Vec::new()
1739 };
1740 let ran_libtests = !results.is_empty();
1743 let ran_doctests = !doctest_results.is_empty();
1744 results.extend(doctest_results);
1745 let mut runners = Vec::new();
1746 if ran_libtests || !ran_doctests {
1747 runners.push(rust_runner_declaration("rust-libtest"));
1748 }
1749 if ran_doctests {
1750 runners.push(rust_runner_declaration("rustdoc"));
1751 }
1752 let structural_limitations = structural_limitations(&project.manifest);
1753 Ok(RustFrontendRun {
1754 declaration: FrontendRunDeclaration {
1755 protocol_version: LANGUAGE_FRONTEND_PROTOCOL_VERSION,
1756 frontend_id: "rust".into(),
1757 frontend_version: "rust-owned-v1".into(),
1758 language: "rust".into(),
1759 structural_source: StructuralSource::OwnedProbes,
1760 runners,
1761 structural_limitations,
1762 },
1763 request: CoverageReportRequest {
1764 run_id: run_id.into(),
1765 manifest: project.manifest.clone(),
1766 raw_results: results,
1767 generated_at: generated_at.into(),
1768 coverage_model: Some(rust_coverage_model()),
1769 integrity: None,
1770 test_exit_code: ExitCodeInput::Present(Some(overall_exit)),
1771 },
1772 exit_code: overall_exit,
1773 artifacts: artifacts.len(),
1774 artifact_files: artifacts
1775 .iter()
1776 .map(|artifact| artifact.executable.clone())
1777 .collect(),
1778 build_ms,
1779 execution_ms: execution_started.elapsed().as_secs_f64() * 1000.0,
1780 })
1781}
1782
1783#[cfg(test)]
1784mod tests {
1785 use std::time::{SystemTime, UNIX_EPOCH};
1786
1787 use super::*;
1788 use crate::{
1789 coverage_report::{ArchiveReportRequest, analyze_coverage_archive},
1790 evidence_archive::write_archive,
1791 frontend_protocol::validate_frontend_report_request,
1792 rust_project::prepare_rust_project,
1793 };
1794
1795 #[test]
1796 fn cargo_and_libtest_selection_is_preserved_without_presentation_guessing() {
1797 let root = Path::new(".");
1798 let invocation = cargo_invocation(
1799 root,
1800 &[
1801 "cargo".into(),
1802 "test".into(),
1803 "-p".into(),
1804 "fixture".into(),
1805 "authored".into(),
1806 "--".into(),
1807 "generated".into(),
1808 "--skip".into(),
1809 "slow".into(),
1810 "--include-ignored".into(),
1811 ],
1812 )
1813 .unwrap();
1814 assert_eq!(invocation.arguments, ["test", "-p", "fixture", "authored"]);
1815 assert_eq!(
1816 invocation.runner_arguments,
1817 ["generated", "--skip", "slow", "--include-ignored"]
1818 );
1819 let selection = rust_libtest_selection(&invocation).unwrap();
1820 assert_eq!(
1821 selection.list_arguments,
1822 [
1823 "authored",
1824 "generated",
1825 "--skip",
1826 "slow",
1827 "--include-ignored"
1828 ]
1829 );
1830 }
1831
1832 #[test]
1833 fn direct_cargo_argv_preserves_toml_quotes_inside_config_values() {
1834 let config = "target.host.runner=[\"runner with spaces\",\"--fixed\"]";
1835 let invocation = cargo_invocation(
1836 Path::new("."),
1837 &[
1838 "cargo".into(),
1839 "test".into(),
1840 "--config".into(),
1841 config.into(),
1842 ],
1843 )
1844 .unwrap();
1845 assert_eq!(invocation.arguments, ["test", "--config", config]);
1846 }
1847
1848 #[test]
1849 fn nextest_run_is_detected_without_reclassifying_its_filters_or_retries() {
1850 let invocation = cargo_invocation(
1851 Path::new("."),
1852 &[
1853 "cargo".into(),
1854 "+1.95.0".into(),
1855 "nextest".into(),
1856 "run".into(),
1857 "--retries".into(),
1858 "2".into(),
1859 "-E".into(),
1860 "test(/flaky/)".into(),
1861 "--".into(),
1862 "--nocapture".into(),
1863 ],
1864 )
1865 .unwrap();
1866 assert_eq!(invocation.kind, RustCargoCommandKind::NextestRun);
1867 assert_eq!(
1868 invocation.arguments,
1869 [
1870 "+1.95.0",
1871 "nextest",
1872 "run",
1873 "--retries",
1874 "2",
1875 "-E",
1876 "test(/flaky/)",
1877 ]
1878 );
1879 assert_eq!(invocation.runner_arguments, ["--nocapture"]);
1880 let execution = rust_cargo_execution_selection(&invocation).unwrap();
1881 assert!(execution.run_libtests);
1882 assert!(!execution.run_doctests);
1883 assert!(execution.doctest_arguments.is_empty());
1884 assert!(rust_libtest_selection(&invocation).is_err());
1885 assert_eq!(
1886 nextest_list_invocation(&invocation).unwrap(),
1887 NextestListInvocation {
1888 arguments: vec![
1889 "+1.95.0".into(),
1890 "nextest".into(),
1891 "list".into(),
1892 "-E".into(),
1893 "test(/flaky/)".into(),
1894 "--message-format".into(),
1895 "json".into(),
1896 ],
1897 runner_arguments: vec!["--nocapture".into()],
1898 }
1899 );
1900 }
1901
1902 #[test]
1903 fn nextest_list_projection_preserves_selection_and_rejects_external_state() {
1904 let invocation = CargoTestInvocation {
1905 program: "cargo".into(),
1906 kind: RustCargoCommandKind::NextestRun,
1907 arguments: vec![
1908 "nextest".into(),
1909 "run".into(),
1910 "--package=fixture".into(),
1911 "--partition".into(),
1912 "hash:1/2".into(),
1913 "--test-threads=8".into(),
1914 "--failure-output".into(),
1915 "final".into(),
1916 "name".into(),
1917 ],
1918 runner_arguments: vec!["--exact".into(), "full::name".into()],
1919 };
1920 assert_eq!(
1921 nextest_list_invocation(&invocation).unwrap(),
1922 NextestListInvocation {
1923 arguments: vec![
1924 "nextest".into(),
1925 "list".into(),
1926 "--package=fixture".into(),
1927 "--partition".into(),
1928 "hash:1/2".into(),
1929 "name".into(),
1930 "--message-format".into(),
1931 "json".into(),
1932 ],
1933 runner_arguments: vec!["--exact".into(), "full::name".into()],
1934 }
1935 );
1936
1937 let mut rerun = invocation;
1938 rerun.arguments.extend(["--rerun".into(), "latest".into()]);
1939 assert!(
1940 nextest_list_invocation(&rerun)
1941 .unwrap_err()
1942 .to_string()
1943 .contains("cannot yet be assigned exact selected-test identity")
1944 );
1945 }
1946
1947 #[test]
1948 fn nextest_list_projection_preserves_post_separator_libtest_selection() {
1949 let invocation = cargo_invocation(
1950 Path::new("."),
1951 &[
1952 "cargo".into(),
1953 "nextest".into(),
1954 "run".into(),
1955 "--timings".into(),
1956 "-vv".into(),
1957 "--".into(),
1958 "--include-ignored".into(),
1959 "--skip".into(),
1960 "slow".into(),
1961 "--exact".into(),
1962 "tests::selected".into(),
1963 ],
1964 )
1965 .unwrap();
1966 assert_eq!(
1967 nextest_list_invocation(&invocation).unwrap(),
1968 NextestListInvocation {
1969 arguments: vec![
1970 "nextest".to_owned(),
1971 "list".to_owned(),
1972 "--timings".to_owned(),
1973 "-vv".to_owned(),
1974 "--message-format".to_owned(),
1975 "json".to_owned(),
1976 ],
1977 runner_arguments: vec![
1978 "--include-ignored".to_owned(),
1979 "--skip".to_owned(),
1980 "slow".to_owned(),
1981 "--exact".to_owned(),
1982 "tests::selected".to_owned(),
1983 ],
1984 }
1985 );
1986 }
1987
1988 #[test]
1989 fn nextest_version_handshake_preserves_the_cargo_toolchain_selector() {
1990 let invocation = CargoTestInvocation {
1991 program: "cargo".into(),
1992 kind: RustCargoCommandKind::NextestRun,
1993 arguments: vec![
1994 "+1.95.0".into(),
1995 "nextest".into(),
1996 "run".into(),
1997 "-p".into(),
1998 "fixture".into(),
1999 ],
2000 runner_arguments: Vec::new(),
2001 };
2002 assert_eq!(
2003 nextest_version_arguments(&invocation).unwrap(),
2004 ["+1.95.0", "nextest", "--version"]
2005 );
2006 }
2007
2008 #[test]
2009 fn stock_libtest_presentation_and_scheduling_options_do_not_change_discovery() {
2010 let invocation = CargoTestInvocation {
2011 program: "cargo".into(),
2012 kind: RustCargoCommandKind::CargoTest,
2013 arguments: vec!["test".into(), "cargo-filter".into()],
2014 runner_arguments: [
2015 "runner-filter",
2016 "--nocapture",
2017 "--show-output",
2018 "--format=json",
2019 "--color",
2020 "never",
2021 "--test-threads=4",
2022 "--fail-fast",
2023 "--shuffle-seed",
2024 "17",
2025 "-Zunstable-options",
2026 "--exclude-should-panic",
2027 ]
2028 .into_iter()
2029 .map(str::to_owned)
2030 .collect(),
2031 };
2032 let selection = rust_libtest_selection(&invocation).unwrap();
2033 assert_eq!(
2034 selection.list_arguments,
2035 [
2036 "cargo-filter",
2037 "runner-filter",
2038 "-Zunstable-options",
2039 "--exclude-should-panic"
2040 ]
2041 );
2042 }
2043
2044 #[test]
2045 fn cargo_test_options_are_not_mistaken_for_the_test_name_filter() {
2046 let invocation = CargoTestInvocation {
2047 program: "cargo".into(),
2048 kind: RustCargoCommandKind::CargoTest,
2049 arguments: vec![
2050 "test".into(),
2051 "--manifest-path".into(),
2052 "nested/Cargo.toml".into(),
2053 "--features=one,two".into(),
2054 "needle".into(),
2055 ],
2056 runner_arguments: vec!["--ignored".into(), "other".into()],
2057 };
2058 let selection = rust_libtest_selection(&invocation).unwrap();
2059 assert_eq!(selection.list_arguments, ["needle", "--ignored", "other"]);
2060 }
2061
2062 #[test]
2063 fn libtest_thread_count_is_preserved_as_runner_scheduling() {
2064 for arguments in [vec!["--test-threads", "1"], vec!["--test-threads=8"]] {
2065 let invocation = CargoTestInvocation {
2066 program: "cargo".into(),
2067 kind: RustCargoCommandKind::CargoTest,
2068 arguments: vec!["test".into()],
2069 runner_arguments: arguments.into_iter().map(str::to_owned).collect(),
2070 };
2071 let selection = rust_libtest_selection(&invocation).unwrap();
2072 assert!(selection.list_arguments.is_empty());
2073 }
2074 }
2075
2076 #[test]
2077 fn invalid_or_duplicate_libtest_thread_counts_fail_closed() {
2078 for arguments in [
2079 vec!["--test-threads"],
2080 vec!["--test-threads=0"],
2081 vec!["--test-threads=abc"],
2082 vec!["--test-threads", "1", "--test-threads=2"],
2083 ] {
2084 let invocation = CargoTestInvocation {
2085 program: "cargo".into(),
2086 kind: RustCargoCommandKind::CargoTest,
2087 arguments: vec!["test".into()],
2088 runner_arguments: arguments.into_iter().map(str::to_owned).collect(),
2089 };
2090 assert!(rust_libtest_selection(&invocation).is_err());
2091 }
2092 }
2093
2094 #[test]
2095 fn cargo_target_selection_reproduces_when_cargo_runs_doctests() {
2096 let invocation = CargoTestInvocation {
2097 program: "cargo".into(),
2098 kind: RustCargoCommandKind::CargoTest,
2099 arguments: vec![
2100 "test".into(),
2101 "-p".into(),
2102 "fixture".into(),
2103 "needle".into(),
2104 ],
2105 runner_arguments: vec!["--include-ignored".into()],
2106 };
2107 let selection = rust_cargo_execution_selection(&invocation).unwrap();
2108 assert!(selection.run_libtests);
2109 assert!(selection.run_doctests);
2110 assert_eq!(
2111 selection.doctest_arguments,
2112 [
2113 "test",
2114 "--doc",
2115 "-p",
2116 "fixture",
2117 "needle",
2118 "--",
2119 "--include-ignored"
2120 ]
2121 );
2122
2123 let mut explicit_doc = invocation.clone();
2124 explicit_doc.arguments.insert(1, "--doc".into());
2125 let selection = rust_cargo_execution_selection(&explicit_doc).unwrap();
2126 assert!(!selection.run_libtests);
2127 assert!(selection.run_doctests);
2128
2129 for target in ["--lib", "--tests", "--all-targets", "--example=demo"] {
2130 let mut selected = invocation.clone();
2131 selected.arguments.insert(1, target.into());
2132 let selection = rust_cargo_execution_selection(&selected).unwrap();
2133 assert!(selection.run_libtests);
2134 assert!(!selection.run_doctests);
2135 }
2136 }
2137
2138 #[test]
2139 fn a_module_the_build_never_compiles_leaves_the_denominator() {
2140 let nonce = SystemTime::now()
2144 .duration_since(UNIX_EPOCH)
2145 .unwrap()
2146 .as_nanos();
2147 let root = std::env::temp_dir().join(format!(
2148 "supercov-rust-runner-cfg-{}-{nonce}",
2149 std::process::id()
2150 ));
2151 fs::create_dir_all(root.join("src")).unwrap();
2152 fs::write(
2153 root.join("Cargo.toml"),
2154 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n\n[features]\nextra=[]\n",
2155 )
2156 .unwrap();
2157 fs::write(
2158 root.join("src/lib.rs"),
2159 r#"
2160#[cfg(feature = "extra")]
2161mod extra;
2162
2163pub fn kept(value: i32) -> i32 {
2164 if value > 0 { value } else { -value }
2165}
2166#[cfg(test)]
2167mod tests {
2168 #[test] fn positive() { assert_eq!(super::kept(2), 2); }
2169 #[test] fn negative() { assert_eq!(super::kept(-2), 2); }
2170}
2171"#,
2172 )
2173 .unwrap();
2174 fs::write(
2175 root.join("src/extra.rs"),
2176 "pub fn never_built(value: i32) -> i32 {\n if value > 0 { 1 } else { 0 }\n}\n",
2177 )
2178 .unwrap();
2179 let project = prepare_rust_project(&root).unwrap();
2180 assert!(
2182 project
2183 .source_files
2184 .iter()
2185 .any(|file| file == "src/extra.rs"),
2186 "{:?}",
2187 project.source_files
2188 );
2189 let run = run_prepared_rust_tests(
2190 &project,
2191 &["cargo".into(), "test".into(), "--lib".into()],
2192 "rust-fixture-cfg",
2193 "2026-08-26T00:00:00.000Z",
2194 &mut Vec::new(),
2195 )
2196 .unwrap();
2197 assert_eq!(run.exit_code, 0);
2198 let manifest = &run.request.manifest;
2201 assert!(
2202 manifest
2203 .points
2204 .iter()
2205 .any(|point| point.file == "src/extra.rs"),
2206 "the obligations must stay in the manifest"
2207 );
2208 let declined = manifest.unmeasured.iter().collect::<BTreeSet<_>>();
2209 for point in &manifest.points {
2210 assert_eq!(
2211 declined.contains(&point.id),
2212 point.file == "src/extra.rs",
2213 "{} in {}",
2214 point.id,
2215 point.file
2216 );
2217 }
2218 for decision in &manifest.decisions {
2219 assert_eq!(
2220 declined.contains(&decision.id),
2221 decision.file == "src/extra.rs"
2222 );
2223 }
2224 let report =
2226 crate::frontend_protocol::analyze_frontend_results(&run.declaration, &run.request)
2227 .unwrap();
2228 assert_eq!(
2229 report.view.summary.lines.percentage, 100.0,
2230 "declined obligations must not read as uncovered"
2231 );
2232 fs::remove_dir_all(&root).ok();
2233 }
2234
2235 #[test]
2236 fn assertion_occurrences_are_retained_without_automatic_asserted_credit() {
2237 let nonce = SystemTime::now()
2242 .duration_since(UNIX_EPOCH)
2243 .unwrap()
2244 .as_nanos();
2245 let root = std::env::temp_dir().join(format!(
2246 "supercov-rust-runner-assert-{}-{nonce}",
2247 std::process::id()
2248 ));
2249 fs::create_dir_all(root.join("src")).unwrap();
2250 fs::write(
2251 root.join("Cargo.toml"),
2252 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2253 )
2254 .unwrap();
2255 fs::write(
2256 root.join("src/lib.rs"),
2257 r#"
2258pub fn checked(value: i32) -> i32 {
2259 value * 2
2260}
2261pub fn unchecked(value: i32) -> i32 {
2262 value + 1
2263}
2264#[cfg(test)]
2265mod tests {
2266 #[test]
2267 fn asserts() {
2268 let doubled = super::checked(2);
2269 assert_eq!(doubled, 4);
2270 }
2271 #[test]
2272 fn asserts_nothing() {
2273 let _ = super::unchecked(1);
2274 }
2275}
2276"#,
2277 )
2278 .unwrap();
2279 let project = prepare_rust_project(&root).unwrap();
2280 let run = run_prepared_rust_tests(
2281 &project,
2282 &["cargo".into(), "test".into(), "--lib".into()],
2283 "rust-fixture-assert",
2284 "2026-08-26T00:00:00.000Z",
2285 &mut Vec::new(),
2286 )
2287 .unwrap();
2288 assert_eq!(run.exit_code, 0);
2289
2290 let phases = |test: &str| {
2293 run.request
2294 .raw_results
2295 .iter()
2296 .find(|result| result.test.ends_with(test))
2297 .unwrap_or_else(|| panic!("no test {test}"))
2298 .phases
2299 .clone()
2300 };
2301 let asserting = phases("asserts");
2302 assert!(
2303 !asserting.is_empty(),
2304 "the asserting test recorded no phase"
2305 );
2306 assert!(
2307 asserting
2308 .iter()
2309 .all(|phase| phase.kind == "assertion" && phase.status.as_deref() == Some("passed"))
2310 );
2311 assert!(
2312 phases("asserts_nothing").is_empty(),
2313 "a test that checks nothing witnesses nothing"
2314 );
2315
2316 let report =
2317 crate::frontend_protocol::analyze_frontend_results(&run.declaration, &run.request)
2318 .unwrap();
2319 let level = |line: usize| {
2320 report
2321 .view
2322 .lines
2323 .iter()
2324 .find(|entry| entry.file == "src/lib.rs" && entry.line == line)
2325 .map(|entry| entry.confidence.level.clone())
2326 .unwrap_or_else(|| panic!("no line {line}"))
2327 };
2328 assert_eq!(level(3), "executed");
2330 assert_eq!(level(6), "executed");
2331 fs::remove_dir_all(&root).ok();
2332 }
2333
2334 #[test]
2335 fn libtest_filters_select_the_tests_plain_cargo_would_run() {
2336 let nonce = SystemTime::now()
2340 .duration_since(UNIX_EPOCH)
2341 .unwrap()
2342 .as_nanos();
2343 let root = std::env::temp_dir().join(format!(
2344 "supercov-rust-runner-filters-{}-{nonce}",
2345 std::process::id()
2346 ));
2347 fs::create_dir_all(root.join("src")).unwrap();
2348 fs::write(
2349 root.join("Cargo.toml"),
2350 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2351 )
2352 .unwrap();
2353 fs::write(
2354 root.join("src/lib.rs"),
2355 r#"
2356pub fn value(flag: bool) -> i32 { if flag { 1 } else { 0 } }
2357#[cfg(test)]
2358mod tests {
2359 #[test] fn alpha() { assert_eq!(super::value(true), 1); }
2360 #[test] fn beta() { assert_eq!(super::value(false), 0); }
2361 #[test] #[ignore] fn gamma_slow() { assert_eq!(super::value(true), 1); }
2362}
2363"#,
2364 )
2365 .unwrap();
2366 let project = prepare_rust_project(&root).unwrap();
2367 let names = |run: &str, command: &[&str]| {
2368 let run = run_prepared_rust_tests(
2369 &project,
2370 &command
2371 .iter()
2372 .map(|word| (*word).into())
2373 .collect::<Vec<String>>(),
2374 run,
2375 "2026-08-26T00:00:00.000Z",
2376 &mut Vec::new(),
2377 )
2378 .unwrap();
2379 assert_eq!(run.exit_code, 0, "{:?}", run.request.raw_results);
2380 let mut names = run
2381 .request
2382 .raw_results
2383 .iter()
2384 .map(|result| {
2385 (
2386 result.test.rsplit("::").next().unwrap().to_owned(),
2387 result.status.clone().unwrap(),
2388 )
2389 })
2390 .collect::<Vec<_>>();
2391 names.sort();
2392 names
2393 };
2394 assert_eq!(
2396 names("rust-fixture-filters-1", &["cargo", "test", "--lib"]),
2397 [
2398 ("alpha".to_owned(), "passed".to_owned()),
2399 ("beta".to_owned(), "passed".to_owned()),
2400 ("gamma_slow".to_owned(), "skipped".to_owned()),
2401 ]
2402 );
2403 assert_eq!(
2405 names(
2406 "rust-fixture-filters-2",
2407 &["cargo", "test", "--lib", "alpha"]
2408 ),
2409 [("alpha".to_owned(), "passed".to_owned())]
2410 );
2411 assert_eq!(
2412 names(
2413 "rust-fixture-filters-3",
2414 &["cargo", "test", "--lib", "--", "--skip", "beta"]
2415 ),
2416 [
2417 ("alpha".to_owned(), "passed".to_owned()),
2418 ("gamma_slow".to_owned(), "skipped".to_owned()),
2419 ]
2420 );
2421 assert_eq!(
2423 names(
2424 "rust-fixture-filters-4",
2425 &["cargo", "test", "--lib", "--", "--ignored"]
2426 ),
2427 [("gamma_slow".to_owned(), "passed".to_owned())]
2428 );
2429 fs::remove_dir_all(&root).ok();
2430 }
2431
2432 #[test]
2433 fn libtest_processes_run_in_their_package_directory() {
2434 let nonce = SystemTime::now()
2438 .duration_since(UNIX_EPOCH)
2439 .unwrap()
2440 .as_nanos();
2441 let root = std::env::temp_dir().join(format!(
2442 "supercov-rust-runner-cwd-{}-{nonce}",
2443 std::process::id()
2444 ));
2445 fs::create_dir_all(root.join("member/src")).unwrap();
2446 fs::write(
2447 root.join("Cargo.toml"),
2448 "[workspace]\nmembers = ['member']\nresolver = '2'\n",
2449 )
2450 .unwrap();
2451 fs::write(
2452 root.join("member/Cargo.toml"),
2453 "[package]\nname='member'\nversion='0.0.0'\nedition='2024'\n",
2454 )
2455 .unwrap();
2456 fs::write(
2457 root.join("member/src/lib.rs"),
2458 r#"
2459pub fn manifest() -> String {
2460 std::fs::read_to_string("Cargo.toml").unwrap()
2461}
2462#[cfg(test)]
2463mod tests {
2464 #[test] fn reads_own_manifest() { assert!(super::manifest().contains("name='member'")); }
2465}
2466"#,
2467 )
2468 .unwrap();
2469 let project = prepare_rust_project(&root).unwrap();
2470 let run = run_prepared_rust_tests(
2471 &project,
2472 &["cargo".into(), "test".into(), "--lib".into()],
2473 "rust-fixture-cwd",
2474 "2026-08-26T00:00:00.000Z",
2475 &mut Vec::new(),
2476 )
2477 .unwrap();
2478 assert_eq!(run.exit_code, 0, "{:?}", run.request.raw_results);
2479 assert_eq!(run.request.raw_results.len(), 1);
2480 assert_eq!(run.request.raw_results[0].status.as_deref(), Some("passed"));
2481 fs::remove_dir_all(&root).ok();
2482 }
2483
2484 #[test]
2485 fn cargo_libtest_runs_produce_queryable_owned_evidence() {
2486 let nonce = SystemTime::now()
2487 .duration_since(UNIX_EPOCH)
2488 .unwrap()
2489 .as_nanos();
2490 let root = std::env::temp_dir().join(format!(
2491 "supercov-rust-runner-{}-{nonce}",
2492 std::process::id()
2493 ));
2494 fs::create_dir_all(root.join("src")).unwrap();
2495 fs::write(
2496 root.join("Cargo.toml"),
2497 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2498 )
2499 .unwrap();
2500 fs::write(
2501 root.join("src/lib.rs"),
2502 r#"
2503pub fn choose(left: bool, right: bool) -> i32 {
2504 if left && right { 1 } else { 0 }
2505}
2506pub fn pick(value: i32) -> &'static str {
2507 match value {
2508 0 => "zero",
2509 1 => "one",
2510 _ => "many",
2511 }
2512}
2513pub fn total(values: &[i32]) -> i32 {
2514 let mut sum = 0;
2515 for value in values {
2516 sum += value;
2517 }
2518 sum
2519}
2520pub fn first_even(values: &[i32]) -> Option<i32> {
2521 let mut index = 0;
2522 while index < values.len() {
2523 if values[index] % 2 == 0 {
2524 return Some(values[index]);
2525 }
2526 index += 1;
2527 }
2528 None
2529}
2530pub fn parse_twice(text: &str) -> Option<i32> {
2531 let value: i32 = text.parse().ok()?;
2532 Some(value * 2)
2533}
2534pub fn describe(value: Option<i32>, flag: bool) -> &'static str {
2535 if let Some(inner) = value && inner > 0 && flag {
2536 "positive"
2537 } else {
2538 "other"
2539 }
2540}
2541pub fn depth(n: u32) -> Result<u32, String> {
2542 if n == 0 {
2543 Ok(0)
2544 } else {
2545 let below = depth(n - 1)?;
2546 Ok(below + 1)
2547 }
2548}
2549#[cfg(test)]
2550mod tests {
2551 #[test] fn false_path() { assert_eq!(super::choose(false, true), 0); }
2552 #[test] fn true_path() { assert_eq!(super::choose(true, true), 1); }
2553 #[test] #[ignore] fn ignored_path() { unreachable!(); }
2554 #[test] fn pick_zero() { assert_eq!(super::pick(0), "zero"); }
2555 #[test] fn pick_many() { assert_eq!(super::pick(7), "many"); }
2556 #[test] fn total_empty() { assert_eq!(super::total(&[]), 0); }
2557 #[test] fn total_some() { assert_eq!(super::total(&[1, 2]), 3); }
2558 #[test] fn first_even_empty() { assert_eq!(super::first_even(&[]), None); }
2559 #[test] fn first_even_found() { assert_eq!(super::first_even(&[1, 4]), Some(4)); }
2560 #[test] fn parse_ok() { assert_eq!(super::parse_twice("4"), Some(8)); }
2561 #[test] fn parse_bad() { assert_eq!(super::parse_twice("x"), None); }
2562 #[test] fn chain_taken() { assert_eq!(super::describe(Some(1), true), "positive"); }
2563 #[test] fn chain_pattern_fails() { assert_eq!(super::describe(None, true), "other"); }
2564 #[test] fn chain_negative() { assert_eq!(super::describe(Some(-1), true), "other"); }
2565 #[test] fn chain_flag_fails() { assert_eq!(super::describe(Some(1), false), "other"); }
2566 #[test] fn deep_recursion() { assert_eq!(super::depth(5_000), Ok(5_000)); }
2567}
2568"#,
2569 )
2570 .unwrap();
2571 let project = prepare_rust_project(&root).unwrap();
2572 let run = run_prepared_rust_tests(
2576 &project,
2577 &["cargo".into(), "test".into(), "--lib".into()],
2578 "rust-fixture",
2579 "2026-08-26T00:00:00.000Z",
2580 &mut Vec::new(),
2581 )
2582 .unwrap();
2583 assert_eq!(run.exit_code, 0);
2584 assert_eq!(run.request.raw_results.len(), 16);
2585 let statuses = run
2586 .request
2587 .raw_results
2588 .iter()
2589 .filter_map(|result| result.status.as_deref())
2590 .collect::<Vec<_>>();
2591 assert_eq!(
2592 statuses
2593 .iter()
2594 .filter(|status| **status == "skipped")
2595 .count(),
2596 1
2597 );
2598 assert_eq!(
2599 statuses
2600 .iter()
2601 .filter(|status| **status == "passed")
2602 .count(),
2603 15
2604 );
2605
2606 let chain_vectors = |test: &str| {
2609 let result = run
2610 .request
2611 .raw_results
2612 .iter()
2613 .find(|result| result.test.ends_with(test))
2614 .unwrap_or_else(|| panic!("no test {test}"));
2615 let snapshot = result
2616 .runtime
2617 .iter()
2618 .flat_map(|snapshot| &snapshot.decisions)
2619 .find(|decision| decision.meta.source.starts_with("let Some(inner) = value"))
2620 .unwrap_or_else(|| panic!("{test} recorded no chain decision"));
2621 snapshot
2622 .vectors
2623 .iter()
2624 .map(|vector| (vector.values.clone(), vector.outcome))
2625 .collect::<Vec<_>>()
2626 };
2627 assert_eq!(
2628 chain_vectors("chain_taken"),
2629 [(vec![Some(true), Some(true), Some(true)], true)]
2630 );
2631 assert_eq!(
2632 chain_vectors("chain_pattern_fails"),
2633 [(vec![Some(false), None, None], false)]
2634 );
2635 assert_eq!(
2636 chain_vectors("chain_negative"),
2637 [(vec![Some(true), Some(false), None], false)]
2638 );
2639 assert_eq!(
2640 chain_vectors("chain_flag_fails"),
2641 [(vec![Some(true), Some(true), Some(false)], false)]
2642 );
2643 validate_frontend_report_request(&run.declaration, &run.request).unwrap();
2644 let archive = root.join("evidence.raw.gz");
2645 write_archive(run.archive_entries().unwrap(), &archive).unwrap();
2646 let report = analyze_coverage_archive(&ArchiveReportRequest {
2647 archive_path: archive,
2648 run_id: "rust-fixture".into(),
2649 generated_at: "2026-08-26T00:00:00.000Z".into(),
2650 integrity: None,
2651 test_exit_code: ExitCodeInput::Present(Some(0)),
2652 })
2653 .unwrap();
2654 assert_eq!(report.view.tests.len(), 16);
2655 assert!(report.view.summary.lines.covered > 0);
2656 assert!(report.view.summary.decisions > 0);
2657
2658 let single = |kind: &str| {
2661 let mut found = report
2662 .view
2663 .branches
2664 .iter()
2665 .filter(|branch| branch.meta.kind == kind);
2666 let branch = found.next().unwrap_or_else(|| panic!("no {kind} branch"));
2667 assert!(found.next().is_none(), "more than one {kind} branch");
2668 branch
2669 };
2670 let tests_of = |branch: &crate::coverage_report::BranchResult, label: &str| {
2671 branch
2672 .alternatives
2673 .iter()
2674 .find(|alternative| alternative.label == label)
2675 .unwrap_or_else(|| panic!("{} has no alternative {label}", branch.meta.kind))
2676 .tests
2677 .clone()
2678 };
2679 let for_loop = single("for-loop");
2680 assert_eq!(
2681 tests_of(for_loop, "zero iterations"),
2682 ["src/lib.rs::tests::total_empty"]
2683 );
2684 assert_eq!(
2685 tests_of(for_loop, "entered"),
2686 ["src/lib.rs::tests::total_some"]
2687 );
2688 let while_loop = single("while-loop");
2689 assert_eq!(
2690 tests_of(while_loop, "zero iterations"),
2691 ["src/lib.rs::tests::first_even_empty"]
2692 );
2693 assert_eq!(
2694 tests_of(while_loop, "entered"),
2695 ["src/lib.rs::tests::first_even_found"]
2696 );
2697 let try_operator = report
2700 .view
2701 .branches
2702 .iter()
2703 .find(|branch| {
2704 branch.meta.kind == "try-operator" && branch.meta.source.contains("parse().ok()")
2705 })
2706 .expect("parse_twice's try operator");
2707 assert_eq!(
2708 tests_of(try_operator, "continued"),
2709 ["src/lib.rs::tests::parse_ok"]
2710 );
2711 assert_eq!(
2712 tests_of(try_operator, "early return"),
2713 ["src/lib.rs::tests::parse_bad"]
2714 );
2715 let mut logical = report
2716 .view
2717 .branches
2718 .iter()
2719 .filter(|branch| branch.meta.kind == "logical-and")
2720 .collect::<Vec<_>>();
2721 logical.sort_by_key(|branch| (branch.meta.line, branch.meta.column));
2722 assert_eq!(logical.len(), 3);
2724 assert_eq!(
2725 tests_of(logical[0], "short-circuited"),
2726 ["src/lib.rs::tests::false_path"]
2727 );
2728 assert_eq!(
2729 tests_of(logical[0], "right operand evaluated"),
2730 ["src/lib.rs::tests::true_path"]
2731 );
2732 assert_eq!(
2733 tests_of(logical[1], "short-circuited"),
2734 ["src/lib.rs::tests::chain_pattern_fails"]
2735 );
2736 assert_eq!(
2737 tests_of(logical[1], "right operand evaluated"),
2738 [
2739 "src/lib.rs::tests::chain_flag_fails",
2740 "src/lib.rs::tests::chain_negative",
2741 "src/lib.rs::tests::chain_taken",
2742 ]
2743 );
2744 assert_eq!(
2745 tests_of(logical[2], "short-circuited"),
2746 [
2747 "src/lib.rs::tests::chain_negative",
2748 "src/lib.rs::tests::chain_pattern_fails",
2749 ]
2750 );
2751 assert_eq!(
2752 tests_of(logical[2], "right operand evaluated"),
2753 [
2754 "src/lib.rs::tests::chain_flag_fails",
2755 "src/lib.rs::tests::chain_taken",
2756 ]
2757 );
2758 assert!(for_loop.covered && while_loop.covered && try_operator.covered);
2759 assert!(logical.iter().all(|branch| branch.covered));
2760
2761 let mut arms = report
2764 .view
2765 .branches
2766 .iter()
2767 .filter(|branch| branch.meta.kind == "match-arm")
2768 .collect::<Vec<_>>();
2769 arms.sort_by_key(|branch| branch.meta.line);
2770 assert_eq!(arms.len(), 3);
2771 let alternative = |arm: usize, label: &str| {
2772 arms[arm]
2773 .alternatives
2774 .iter()
2775 .find(|alternative| alternative.label == label)
2776 .unwrap_or_else(|| panic!("arm {arm} has no alternative {label}"))
2777 };
2778 assert_eq!(
2779 alternative(0, "selected").tests,
2780 ["src/lib.rs::tests::pick_zero"]
2781 );
2782 assert_eq!(
2783 alternative(0, "not selected").tests,
2784 ["src/lib.rs::tests::pick_many"]
2785 );
2786 assert!(!alternative(1, "selected").covered);
2787 assert_eq!(
2788 alternative(1, "not selected").tests,
2789 ["src/lib.rs::tests::pick_many"]
2790 );
2791 assert_eq!(arms[2].alternatives.len(), 1);
2792 assert_eq!(
2793 alternative(2, "selected").tests,
2794 ["src/lib.rs::tests::pick_many"]
2795 );
2796 assert!(arms[0].covered && !arms[1].covered && arms[2].covered);
2797
2798 fs::remove_dir_all(root).unwrap();
2799 }
2800}