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 attribution: crate::coverage_report::ATTRIBUTION_EXACT.into(),
1721 phases: evidence.phases,
1722 runtime: vec![evidence.snapshot],
1723 browser: Vec::new(),
1724 server: Vec::new(),
1725 });
1726 }
1727 let doctest_results =
1728 if selection.run_doctests && invocation.kind == RustCargoCommandKind::CargoTest {
1729 crate::rust_owned_doctests::run_doctests(
1730 project,
1731 &invocation,
1732 &selection,
1733 &evidence_root.join("doctests"),
1734 run_id,
1735 diagnostics,
1736 &mut overall_exit,
1737 )?
1738 } else {
1739 Vec::new()
1740 };
1741 let ran_libtests = !results.is_empty();
1744 let ran_doctests = !doctest_results.is_empty();
1745 results.extend(doctest_results);
1746 let mut runners = Vec::new();
1747 if ran_libtests || !ran_doctests {
1748 runners.push(rust_runner_declaration("rust-libtest"));
1749 }
1750 if ran_doctests {
1751 runners.push(rust_runner_declaration("rustdoc"));
1752 }
1753 let structural_limitations = structural_limitations(&project.manifest);
1754 Ok(RustFrontendRun {
1755 declaration: FrontendRunDeclaration {
1756 protocol_version: LANGUAGE_FRONTEND_PROTOCOL_VERSION,
1757 frontend_id: "rust".into(),
1758 frontend_version: "rust-owned-v1".into(),
1759 language: "rust".into(),
1760 structural_source: StructuralSource::OwnedProbes,
1761 runners,
1762 structural_limitations,
1763 },
1764 request: CoverageReportRequest {
1765 run_id: run_id.into(),
1766 manifest: project.manifest.clone(),
1767 raw_results: results,
1768 generated_at: generated_at.into(),
1769 coverage_model: Some(rust_coverage_model()),
1770 integrity: None,
1771 test_exit_code: ExitCodeInput::Present(Some(overall_exit)),
1772 },
1773 exit_code: overall_exit,
1774 artifacts: artifacts.len(),
1775 artifact_files: artifacts
1776 .iter()
1777 .map(|artifact| artifact.executable.clone())
1778 .collect(),
1779 build_ms,
1780 execution_ms: execution_started.elapsed().as_secs_f64() * 1000.0,
1781 })
1782}
1783
1784#[cfg(test)]
1785mod tests {
1786 use std::time::{SystemTime, UNIX_EPOCH};
1787
1788 use super::*;
1789 use crate::{
1790 coverage_report::{ArchiveReportRequest, analyze_coverage_archive},
1791 evidence_archive::write_archive,
1792 frontend_protocol::validate_frontend_report_request,
1793 rust_project::prepare_rust_project,
1794 };
1795
1796 #[test]
1797 fn cargo_and_libtest_selection_is_preserved_without_presentation_guessing() {
1798 let root = Path::new(".");
1799 let invocation = cargo_invocation(
1800 root,
1801 &[
1802 "cargo".into(),
1803 "test".into(),
1804 "-p".into(),
1805 "fixture".into(),
1806 "authored".into(),
1807 "--".into(),
1808 "generated".into(),
1809 "--skip".into(),
1810 "slow".into(),
1811 "--include-ignored".into(),
1812 ],
1813 )
1814 .unwrap();
1815 assert_eq!(invocation.arguments, ["test", "-p", "fixture", "authored"]);
1816 assert_eq!(
1817 invocation.runner_arguments,
1818 ["generated", "--skip", "slow", "--include-ignored"]
1819 );
1820 let selection = rust_libtest_selection(&invocation).unwrap();
1821 assert_eq!(
1822 selection.list_arguments,
1823 [
1824 "authored",
1825 "generated",
1826 "--skip",
1827 "slow",
1828 "--include-ignored"
1829 ]
1830 );
1831 }
1832
1833 #[test]
1834 fn direct_cargo_argv_preserves_toml_quotes_inside_config_values() {
1835 let config = "target.host.runner=[\"runner with spaces\",\"--fixed\"]";
1836 let invocation = cargo_invocation(
1837 Path::new("."),
1838 &[
1839 "cargo".into(),
1840 "test".into(),
1841 "--config".into(),
1842 config.into(),
1843 ],
1844 )
1845 .unwrap();
1846 assert_eq!(invocation.arguments, ["test", "--config", config]);
1847 }
1848
1849 #[test]
1850 fn nextest_run_is_detected_without_reclassifying_its_filters_or_retries() {
1851 let invocation = cargo_invocation(
1852 Path::new("."),
1853 &[
1854 "cargo".into(),
1855 "+1.95.0".into(),
1856 "nextest".into(),
1857 "run".into(),
1858 "--retries".into(),
1859 "2".into(),
1860 "-E".into(),
1861 "test(/flaky/)".into(),
1862 "--".into(),
1863 "--nocapture".into(),
1864 ],
1865 )
1866 .unwrap();
1867 assert_eq!(invocation.kind, RustCargoCommandKind::NextestRun);
1868 assert_eq!(
1869 invocation.arguments,
1870 [
1871 "+1.95.0",
1872 "nextest",
1873 "run",
1874 "--retries",
1875 "2",
1876 "-E",
1877 "test(/flaky/)",
1878 ]
1879 );
1880 assert_eq!(invocation.runner_arguments, ["--nocapture"]);
1881 let execution = rust_cargo_execution_selection(&invocation).unwrap();
1882 assert!(execution.run_libtests);
1883 assert!(!execution.run_doctests);
1884 assert!(execution.doctest_arguments.is_empty());
1885 assert!(rust_libtest_selection(&invocation).is_err());
1886 assert_eq!(
1887 nextest_list_invocation(&invocation).unwrap(),
1888 NextestListInvocation {
1889 arguments: vec![
1890 "+1.95.0".into(),
1891 "nextest".into(),
1892 "list".into(),
1893 "-E".into(),
1894 "test(/flaky/)".into(),
1895 "--message-format".into(),
1896 "json".into(),
1897 ],
1898 runner_arguments: vec!["--nocapture".into()],
1899 }
1900 );
1901 }
1902
1903 #[test]
1904 fn nextest_list_projection_preserves_selection_and_rejects_external_state() {
1905 let invocation = CargoTestInvocation {
1906 program: "cargo".into(),
1907 kind: RustCargoCommandKind::NextestRun,
1908 arguments: vec![
1909 "nextest".into(),
1910 "run".into(),
1911 "--package=fixture".into(),
1912 "--partition".into(),
1913 "hash:1/2".into(),
1914 "--test-threads=8".into(),
1915 "--failure-output".into(),
1916 "final".into(),
1917 "name".into(),
1918 ],
1919 runner_arguments: vec!["--exact".into(), "full::name".into()],
1920 };
1921 assert_eq!(
1922 nextest_list_invocation(&invocation).unwrap(),
1923 NextestListInvocation {
1924 arguments: vec![
1925 "nextest".into(),
1926 "list".into(),
1927 "--package=fixture".into(),
1928 "--partition".into(),
1929 "hash:1/2".into(),
1930 "name".into(),
1931 "--message-format".into(),
1932 "json".into(),
1933 ],
1934 runner_arguments: vec!["--exact".into(), "full::name".into()],
1935 }
1936 );
1937
1938 let mut rerun = invocation;
1939 rerun.arguments.extend(["--rerun".into(), "latest".into()]);
1940 assert!(
1941 nextest_list_invocation(&rerun)
1942 .unwrap_err()
1943 .to_string()
1944 .contains("cannot yet be assigned exact selected-test identity")
1945 );
1946 }
1947
1948 #[test]
1949 fn nextest_list_projection_preserves_post_separator_libtest_selection() {
1950 let invocation = cargo_invocation(
1951 Path::new("."),
1952 &[
1953 "cargo".into(),
1954 "nextest".into(),
1955 "run".into(),
1956 "--timings".into(),
1957 "-vv".into(),
1958 "--".into(),
1959 "--include-ignored".into(),
1960 "--skip".into(),
1961 "slow".into(),
1962 "--exact".into(),
1963 "tests::selected".into(),
1964 ],
1965 )
1966 .unwrap();
1967 assert_eq!(
1968 nextest_list_invocation(&invocation).unwrap(),
1969 NextestListInvocation {
1970 arguments: vec![
1971 "nextest".to_owned(),
1972 "list".to_owned(),
1973 "--timings".to_owned(),
1974 "-vv".to_owned(),
1975 "--message-format".to_owned(),
1976 "json".to_owned(),
1977 ],
1978 runner_arguments: vec![
1979 "--include-ignored".to_owned(),
1980 "--skip".to_owned(),
1981 "slow".to_owned(),
1982 "--exact".to_owned(),
1983 "tests::selected".to_owned(),
1984 ],
1985 }
1986 );
1987 }
1988
1989 #[test]
1990 fn nextest_version_handshake_preserves_the_cargo_toolchain_selector() {
1991 let invocation = CargoTestInvocation {
1992 program: "cargo".into(),
1993 kind: RustCargoCommandKind::NextestRun,
1994 arguments: vec![
1995 "+1.95.0".into(),
1996 "nextest".into(),
1997 "run".into(),
1998 "-p".into(),
1999 "fixture".into(),
2000 ],
2001 runner_arguments: Vec::new(),
2002 };
2003 assert_eq!(
2004 nextest_version_arguments(&invocation).unwrap(),
2005 ["+1.95.0", "nextest", "--version"]
2006 );
2007 }
2008
2009 #[test]
2010 fn stock_libtest_presentation_and_scheduling_options_do_not_change_discovery() {
2011 let invocation = CargoTestInvocation {
2012 program: "cargo".into(),
2013 kind: RustCargoCommandKind::CargoTest,
2014 arguments: vec!["test".into(), "cargo-filter".into()],
2015 runner_arguments: [
2016 "runner-filter",
2017 "--nocapture",
2018 "--show-output",
2019 "--format=json",
2020 "--color",
2021 "never",
2022 "--test-threads=4",
2023 "--fail-fast",
2024 "--shuffle-seed",
2025 "17",
2026 "-Zunstable-options",
2027 "--exclude-should-panic",
2028 ]
2029 .into_iter()
2030 .map(str::to_owned)
2031 .collect(),
2032 };
2033 let selection = rust_libtest_selection(&invocation).unwrap();
2034 assert_eq!(
2035 selection.list_arguments,
2036 [
2037 "cargo-filter",
2038 "runner-filter",
2039 "-Zunstable-options",
2040 "--exclude-should-panic"
2041 ]
2042 );
2043 }
2044
2045 #[test]
2046 fn cargo_test_options_are_not_mistaken_for_the_test_name_filter() {
2047 let invocation = CargoTestInvocation {
2048 program: "cargo".into(),
2049 kind: RustCargoCommandKind::CargoTest,
2050 arguments: vec![
2051 "test".into(),
2052 "--manifest-path".into(),
2053 "nested/Cargo.toml".into(),
2054 "--features=one,two".into(),
2055 "needle".into(),
2056 ],
2057 runner_arguments: vec!["--ignored".into(), "other".into()],
2058 };
2059 let selection = rust_libtest_selection(&invocation).unwrap();
2060 assert_eq!(selection.list_arguments, ["needle", "--ignored", "other"]);
2061 }
2062
2063 #[test]
2064 fn libtest_thread_count_is_preserved_as_runner_scheduling() {
2065 for arguments in [vec!["--test-threads", "1"], vec!["--test-threads=8"]] {
2066 let invocation = CargoTestInvocation {
2067 program: "cargo".into(),
2068 kind: RustCargoCommandKind::CargoTest,
2069 arguments: vec!["test".into()],
2070 runner_arguments: arguments.into_iter().map(str::to_owned).collect(),
2071 };
2072 let selection = rust_libtest_selection(&invocation).unwrap();
2073 assert!(selection.list_arguments.is_empty());
2074 }
2075 }
2076
2077 #[test]
2078 fn invalid_or_duplicate_libtest_thread_counts_fail_closed() {
2079 for arguments in [
2080 vec!["--test-threads"],
2081 vec!["--test-threads=0"],
2082 vec!["--test-threads=abc"],
2083 vec!["--test-threads", "1", "--test-threads=2"],
2084 ] {
2085 let invocation = CargoTestInvocation {
2086 program: "cargo".into(),
2087 kind: RustCargoCommandKind::CargoTest,
2088 arguments: vec!["test".into()],
2089 runner_arguments: arguments.into_iter().map(str::to_owned).collect(),
2090 };
2091 assert!(rust_libtest_selection(&invocation).is_err());
2092 }
2093 }
2094
2095 #[test]
2096 fn cargo_target_selection_reproduces_when_cargo_runs_doctests() {
2097 let invocation = CargoTestInvocation {
2098 program: "cargo".into(),
2099 kind: RustCargoCommandKind::CargoTest,
2100 arguments: vec![
2101 "test".into(),
2102 "-p".into(),
2103 "fixture".into(),
2104 "needle".into(),
2105 ],
2106 runner_arguments: vec!["--include-ignored".into()],
2107 };
2108 let selection = rust_cargo_execution_selection(&invocation).unwrap();
2109 assert!(selection.run_libtests);
2110 assert!(selection.run_doctests);
2111 assert_eq!(
2112 selection.doctest_arguments,
2113 [
2114 "test",
2115 "--doc",
2116 "-p",
2117 "fixture",
2118 "needle",
2119 "--",
2120 "--include-ignored"
2121 ]
2122 );
2123
2124 let mut explicit_doc = invocation.clone();
2125 explicit_doc.arguments.insert(1, "--doc".into());
2126 let selection = rust_cargo_execution_selection(&explicit_doc).unwrap();
2127 assert!(!selection.run_libtests);
2128 assert!(selection.run_doctests);
2129
2130 for target in ["--lib", "--tests", "--all-targets", "--example=demo"] {
2131 let mut selected = invocation.clone();
2132 selected.arguments.insert(1, target.into());
2133 let selection = rust_cargo_execution_selection(&selected).unwrap();
2134 assert!(selection.run_libtests);
2135 assert!(!selection.run_doctests);
2136 }
2137 }
2138
2139 #[test]
2140 fn a_module_the_build_never_compiles_leaves_the_denominator() {
2141 let nonce = SystemTime::now()
2145 .duration_since(UNIX_EPOCH)
2146 .unwrap()
2147 .as_nanos();
2148 let root = std::env::temp_dir().join(format!(
2149 "supercov-rust-runner-cfg-{}-{nonce}",
2150 std::process::id()
2151 ));
2152 fs::create_dir_all(root.join("src")).unwrap();
2153 fs::write(
2154 root.join("Cargo.toml"),
2155 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n\n[features]\nextra=[]\n",
2156 )
2157 .unwrap();
2158 fs::write(
2159 root.join("src/lib.rs"),
2160 r#"
2161#[cfg(feature = "extra")]
2162mod extra;
2163
2164pub fn kept(value: i32) -> i32 {
2165 if value > 0 { value } else { -value }
2166}
2167#[cfg(test)]
2168mod tests {
2169 #[test] fn positive() { assert_eq!(super::kept(2), 2); }
2170 #[test] fn negative() { assert_eq!(super::kept(-2), 2); }
2171}
2172"#,
2173 )
2174 .unwrap();
2175 fs::write(
2176 root.join("src/extra.rs"),
2177 "pub fn never_built(value: i32) -> i32 {\n if value > 0 { 1 } else { 0 }\n}\n",
2178 )
2179 .unwrap();
2180 let project = prepare_rust_project(&root, None).unwrap();
2181 assert!(
2183 project
2184 .source_files
2185 .iter()
2186 .any(|file| file == "src/extra.rs"),
2187 "{:?}",
2188 project.source_files
2189 );
2190 let run = run_prepared_rust_tests(
2191 &project,
2192 &["cargo".into(), "test".into(), "--lib".into()],
2193 "rust-fixture-cfg",
2194 "2026-08-26T00:00:00.000Z",
2195 &mut Vec::new(),
2196 )
2197 .unwrap();
2198 assert_eq!(run.exit_code, 0);
2199 let manifest = &run.request.manifest;
2202 assert!(
2203 manifest
2204 .points
2205 .iter()
2206 .any(|point| point.file == "src/extra.rs"),
2207 "the obligations must stay in the manifest"
2208 );
2209 let declined = manifest.unmeasured.iter().collect::<BTreeSet<_>>();
2210 for point in &manifest.points {
2211 assert_eq!(
2212 declined.contains(&point.id),
2213 point.file == "src/extra.rs",
2214 "{} in {}",
2215 point.id,
2216 point.file
2217 );
2218 }
2219 for decision in &manifest.decisions {
2220 assert_eq!(
2221 declined.contains(&decision.id),
2222 decision.file == "src/extra.rs"
2223 );
2224 }
2225 let report =
2227 crate::frontend_protocol::analyze_frontend_results(&run.declaration, &run.request)
2228 .unwrap();
2229 assert_eq!(
2230 report.view.summary.lines.percentage, 100.0,
2231 "declined obligations must not read as uncovered"
2232 );
2233 fs::remove_dir_all(&root).ok();
2234 }
2235
2236 #[test]
2237 fn assertion_occurrences_are_retained_without_automatic_asserted_credit() {
2238 let nonce = SystemTime::now()
2243 .duration_since(UNIX_EPOCH)
2244 .unwrap()
2245 .as_nanos();
2246 let root = std::env::temp_dir().join(format!(
2247 "supercov-rust-runner-assert-{}-{nonce}",
2248 std::process::id()
2249 ));
2250 fs::create_dir_all(root.join("src")).unwrap();
2251 fs::write(
2252 root.join("Cargo.toml"),
2253 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2254 )
2255 .unwrap();
2256 fs::write(
2257 root.join("src/lib.rs"),
2258 r#"
2259pub fn checked(value: i32) -> i32 {
2260 value * 2
2261}
2262pub fn unchecked(value: i32) -> i32 {
2263 value + 1
2264}
2265#[cfg(test)]
2266mod tests {
2267 #[test]
2268 fn asserts() {
2269 let doubled = super::checked(2);
2270 assert_eq!(doubled, 4);
2271 }
2272 #[test]
2273 fn asserts_nothing() {
2274 let _ = super::unchecked(1);
2275 }
2276}
2277"#,
2278 )
2279 .unwrap();
2280 let project = prepare_rust_project(&root, None).unwrap();
2281 let run = run_prepared_rust_tests(
2282 &project,
2283 &["cargo".into(), "test".into(), "--lib".into()],
2284 "rust-fixture-assert",
2285 "2026-08-26T00:00:00.000Z",
2286 &mut Vec::new(),
2287 )
2288 .unwrap();
2289 assert_eq!(run.exit_code, 0);
2290
2291 let phases = |test: &str| {
2294 run.request
2295 .raw_results
2296 .iter()
2297 .find(|result| result.test.ends_with(test))
2298 .unwrap_or_else(|| panic!("no test {test}"))
2299 .phases
2300 .clone()
2301 };
2302 let asserting = phases("asserts");
2303 assert!(
2304 !asserting.is_empty(),
2305 "the asserting test recorded no phase"
2306 );
2307 assert!(
2308 asserting
2309 .iter()
2310 .all(|phase| phase.kind == "assertion" && phase.status.as_deref() == Some("passed"))
2311 );
2312 assert!(
2313 phases("asserts_nothing").is_empty(),
2314 "a test that checks nothing witnesses nothing"
2315 );
2316
2317 let report =
2318 crate::frontend_protocol::analyze_frontend_results(&run.declaration, &run.request)
2319 .unwrap();
2320 let level = |line: usize| {
2321 report
2322 .view
2323 .lines
2324 .iter()
2325 .find(|entry| entry.file == "src/lib.rs" && entry.line == line)
2326 .map(|entry| entry.confidence.level.clone())
2327 .unwrap_or_else(|| panic!("no line {line}"))
2328 };
2329 assert_eq!(level(3), "executed");
2331 assert_eq!(level(6), "executed");
2332 fs::remove_dir_all(&root).ok();
2333 }
2334
2335 #[test]
2336 fn libtest_filters_select_the_tests_plain_cargo_would_run() {
2337 let nonce = SystemTime::now()
2341 .duration_since(UNIX_EPOCH)
2342 .unwrap()
2343 .as_nanos();
2344 let root = std::env::temp_dir().join(format!(
2345 "supercov-rust-runner-filters-{}-{nonce}",
2346 std::process::id()
2347 ));
2348 fs::create_dir_all(root.join("src")).unwrap();
2349 fs::write(
2350 root.join("Cargo.toml"),
2351 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2352 )
2353 .unwrap();
2354 fs::write(
2355 root.join("src/lib.rs"),
2356 r#"
2357pub fn value(flag: bool) -> i32 { if flag { 1 } else { 0 } }
2358#[cfg(test)]
2359mod tests {
2360 #[test] fn alpha() { assert_eq!(super::value(true), 1); }
2361 #[test] fn beta() { assert_eq!(super::value(false), 0); }
2362 #[test] #[ignore] fn gamma_slow() { assert_eq!(super::value(true), 1); }
2363}
2364"#,
2365 )
2366 .unwrap();
2367 let project = prepare_rust_project(&root, None).unwrap();
2368 let names = |run: &str, command: &[&str]| {
2369 let run = run_prepared_rust_tests(
2370 &project,
2371 &command
2372 .iter()
2373 .map(|word| (*word).into())
2374 .collect::<Vec<String>>(),
2375 run,
2376 "2026-08-26T00:00:00.000Z",
2377 &mut Vec::new(),
2378 )
2379 .unwrap();
2380 assert_eq!(run.exit_code, 0, "{:?}", run.request.raw_results);
2381 let mut names = run
2382 .request
2383 .raw_results
2384 .iter()
2385 .map(|result| {
2386 (
2387 result.test.rsplit("::").next().unwrap().to_owned(),
2388 result.status.clone().unwrap(),
2389 )
2390 })
2391 .collect::<Vec<_>>();
2392 names.sort();
2393 names
2394 };
2395 assert_eq!(
2397 names("rust-fixture-filters-1", &["cargo", "test", "--lib"]),
2398 [
2399 ("alpha".to_owned(), "passed".to_owned()),
2400 ("beta".to_owned(), "passed".to_owned()),
2401 ("gamma_slow".to_owned(), "skipped".to_owned()),
2402 ]
2403 );
2404 assert_eq!(
2406 names(
2407 "rust-fixture-filters-2",
2408 &["cargo", "test", "--lib", "alpha"]
2409 ),
2410 [("alpha".to_owned(), "passed".to_owned())]
2411 );
2412 assert_eq!(
2413 names(
2414 "rust-fixture-filters-3",
2415 &["cargo", "test", "--lib", "--", "--skip", "beta"]
2416 ),
2417 [
2418 ("alpha".to_owned(), "passed".to_owned()),
2419 ("gamma_slow".to_owned(), "skipped".to_owned()),
2420 ]
2421 );
2422 assert_eq!(
2424 names(
2425 "rust-fixture-filters-4",
2426 &["cargo", "test", "--lib", "--", "--ignored"]
2427 ),
2428 [("gamma_slow".to_owned(), "passed".to_owned())]
2429 );
2430 fs::remove_dir_all(&root).ok();
2431 }
2432
2433 #[test]
2434 fn libtest_processes_run_in_their_package_directory() {
2435 let nonce = SystemTime::now()
2439 .duration_since(UNIX_EPOCH)
2440 .unwrap()
2441 .as_nanos();
2442 let root = std::env::temp_dir().join(format!(
2443 "supercov-rust-runner-cwd-{}-{nonce}",
2444 std::process::id()
2445 ));
2446 fs::create_dir_all(root.join("member/src")).unwrap();
2447 fs::write(
2448 root.join("Cargo.toml"),
2449 "[workspace]\nmembers = ['member']\nresolver = '2'\n",
2450 )
2451 .unwrap();
2452 fs::write(
2453 root.join("member/Cargo.toml"),
2454 "[package]\nname='member'\nversion='0.0.0'\nedition='2024'\n",
2455 )
2456 .unwrap();
2457 fs::write(
2458 root.join("member/src/lib.rs"),
2459 r#"
2460pub fn manifest() -> String {
2461 std::fs::read_to_string("Cargo.toml").unwrap()
2462}
2463#[cfg(test)]
2464mod tests {
2465 #[test] fn reads_own_manifest() { assert!(super::manifest().contains("name='member'")); }
2466}
2467"#,
2468 )
2469 .unwrap();
2470 let project = prepare_rust_project(&root, None).unwrap();
2471 let run = run_prepared_rust_tests(
2472 &project,
2473 &["cargo".into(), "test".into(), "--lib".into()],
2474 "rust-fixture-cwd",
2475 "2026-08-26T00:00:00.000Z",
2476 &mut Vec::new(),
2477 )
2478 .unwrap();
2479 assert_eq!(run.exit_code, 0, "{:?}", run.request.raw_results);
2480 assert_eq!(run.request.raw_results.len(), 1);
2481 assert_eq!(run.request.raw_results[0].status.as_deref(), Some("passed"));
2482 fs::remove_dir_all(&root).ok();
2483 }
2484
2485 #[test]
2486 fn cargo_libtest_runs_produce_queryable_owned_evidence() {
2487 let nonce = SystemTime::now()
2488 .duration_since(UNIX_EPOCH)
2489 .unwrap()
2490 .as_nanos();
2491 let root = std::env::temp_dir().join(format!(
2492 "supercov-rust-runner-{}-{nonce}",
2493 std::process::id()
2494 ));
2495 fs::create_dir_all(root.join("src")).unwrap();
2496 fs::write(
2497 root.join("Cargo.toml"),
2498 "[package]\nname='fixture'\nversion='0.0.0'\nedition='2024'\n",
2499 )
2500 .unwrap();
2501 fs::write(
2502 root.join("src/lib.rs"),
2503 r#"
2504pub fn choose(left: bool, right: bool) -> i32 {
2505 if left && right { 1 } else { 0 }
2506}
2507pub fn pick(value: i32) -> &'static str {
2508 match value {
2509 0 => "zero",
2510 1 => "one",
2511 _ => "many",
2512 }
2513}
2514pub fn total(values: &[i32]) -> i32 {
2515 let mut sum = 0;
2516 for value in values {
2517 sum += value;
2518 }
2519 sum
2520}
2521pub fn first_even(values: &[i32]) -> Option<i32> {
2522 let mut index = 0;
2523 while index < values.len() {
2524 if values[index] % 2 == 0 {
2525 return Some(values[index]);
2526 }
2527 index += 1;
2528 }
2529 None
2530}
2531pub fn parse_twice(text: &str) -> Option<i32> {
2532 let value: i32 = text.parse().ok()?;
2533 Some(value * 2)
2534}
2535pub fn describe(value: Option<i32>, flag: bool) -> &'static str {
2536 if let Some(inner) = value && inner > 0 && flag {
2537 "positive"
2538 } else {
2539 "other"
2540 }
2541}
2542pub fn depth(n: u32) -> Result<u32, String> {
2543 if n == 0 {
2544 Ok(0)
2545 } else {
2546 let below = depth(n - 1)?;
2547 Ok(below + 1)
2548 }
2549}
2550#[cfg(test)]
2551mod tests {
2552 #[test] fn false_path() { assert_eq!(super::choose(false, true), 0); }
2553 #[test] fn true_path() { assert_eq!(super::choose(true, true), 1); }
2554 #[test] #[ignore] fn ignored_path() { unreachable!(); }
2555 #[test] fn pick_zero() { assert_eq!(super::pick(0), "zero"); }
2556 #[test] fn pick_many() { assert_eq!(super::pick(7), "many"); }
2557 #[test] fn total_empty() { assert_eq!(super::total(&[]), 0); }
2558 #[test] fn total_some() { assert_eq!(super::total(&[1, 2]), 3); }
2559 #[test] fn first_even_empty() { assert_eq!(super::first_even(&[]), None); }
2560 #[test] fn first_even_found() { assert_eq!(super::first_even(&[1, 4]), Some(4)); }
2561 #[test] fn parse_ok() { assert_eq!(super::parse_twice("4"), Some(8)); }
2562 #[test] fn parse_bad() { assert_eq!(super::parse_twice("x"), None); }
2563 #[test] fn chain_taken() { assert_eq!(super::describe(Some(1), true), "positive"); }
2564 #[test] fn chain_pattern_fails() { assert_eq!(super::describe(None, true), "other"); }
2565 #[test] fn chain_negative() { assert_eq!(super::describe(Some(-1), true), "other"); }
2566 #[test] fn chain_flag_fails() { assert_eq!(super::describe(Some(1), false), "other"); }
2567 #[test] fn deep_recursion() { assert_eq!(super::depth(5_000), Ok(5_000)); }
2568}
2569"#,
2570 )
2571 .unwrap();
2572 let project = prepare_rust_project(&root, None).unwrap();
2573 let run = run_prepared_rust_tests(
2577 &project,
2578 &["cargo".into(), "test".into(), "--lib".into()],
2579 "rust-fixture",
2580 "2026-08-26T00:00:00.000Z",
2581 &mut Vec::new(),
2582 )
2583 .unwrap();
2584 assert_eq!(run.exit_code, 0);
2585 assert_eq!(run.request.raw_results.len(), 16);
2586 let statuses = run
2587 .request
2588 .raw_results
2589 .iter()
2590 .filter_map(|result| result.status.as_deref())
2591 .collect::<Vec<_>>();
2592 assert_eq!(
2593 statuses
2594 .iter()
2595 .filter(|status| **status == "skipped")
2596 .count(),
2597 1
2598 );
2599 assert_eq!(
2600 statuses
2601 .iter()
2602 .filter(|status| **status == "passed")
2603 .count(),
2604 15
2605 );
2606
2607 let chain_vectors = |test: &str| {
2610 let result = run
2611 .request
2612 .raw_results
2613 .iter()
2614 .find(|result| result.test.ends_with(test))
2615 .unwrap_or_else(|| panic!("no test {test}"));
2616 let snapshot = result
2617 .runtime
2618 .iter()
2619 .flat_map(|snapshot| &snapshot.decisions)
2620 .find(|decision| decision.meta.source.starts_with("let Some(inner) = value"))
2621 .unwrap_or_else(|| panic!("{test} recorded no chain decision"));
2622 snapshot
2623 .vectors
2624 .iter()
2625 .map(|vector| (vector.values.clone(), vector.outcome))
2626 .collect::<Vec<_>>()
2627 };
2628 assert_eq!(
2629 chain_vectors("chain_taken"),
2630 [(vec![Some(true), Some(true), Some(true)], true)]
2631 );
2632 assert_eq!(
2633 chain_vectors("chain_pattern_fails"),
2634 [(vec![Some(false), None, None], false)]
2635 );
2636 assert_eq!(
2637 chain_vectors("chain_negative"),
2638 [(vec![Some(true), Some(false), None], false)]
2639 );
2640 assert_eq!(
2641 chain_vectors("chain_flag_fails"),
2642 [(vec![Some(true), Some(true), Some(false)], false)]
2643 );
2644 validate_frontend_report_request(&run.declaration, &run.request).unwrap();
2645 let archive = root.join("evidence.raw.gz");
2646 write_archive(run.archive_entries().unwrap(), &archive).unwrap();
2647 let report = analyze_coverage_archive(&ArchiveReportRequest {
2648 archive_path: archive,
2649 run_id: "rust-fixture".into(),
2650 generated_at: "2026-08-26T00:00:00.000Z".into(),
2651 integrity: None,
2652 test_exit_code: ExitCodeInput::Present(Some(0)),
2653 })
2654 .unwrap();
2655 assert_eq!(report.view.tests.len(), 16);
2656 assert!(report.view.summary.lines.covered > 0);
2657 assert!(report.view.summary.decisions > 0);
2658
2659 let single = |kind: &str| {
2662 let mut found = report
2663 .view
2664 .branches
2665 .iter()
2666 .filter(|branch| branch.meta.kind == kind);
2667 let branch = found.next().unwrap_or_else(|| panic!("no {kind} branch"));
2668 assert!(found.next().is_none(), "more than one {kind} branch");
2669 branch
2670 };
2671 let tests_of = |branch: &crate::coverage_report::BranchResult, label: &str| {
2672 branch
2673 .alternatives
2674 .iter()
2675 .find(|alternative| alternative.label == label)
2676 .unwrap_or_else(|| panic!("{} has no alternative {label}", branch.meta.kind))
2677 .tests
2678 .clone()
2679 };
2680 let for_loop = single("for-loop");
2681 assert_eq!(
2682 tests_of(for_loop, "zero iterations"),
2683 ["src/lib.rs::tests::total_empty"]
2684 );
2685 assert_eq!(
2686 tests_of(for_loop, "entered"),
2687 ["src/lib.rs::tests::total_some"]
2688 );
2689 let while_loop = single("while-loop");
2690 assert_eq!(
2691 tests_of(while_loop, "zero iterations"),
2692 ["src/lib.rs::tests::first_even_empty"]
2693 );
2694 assert_eq!(
2695 tests_of(while_loop, "entered"),
2696 ["src/lib.rs::tests::first_even_found"]
2697 );
2698 let try_operator = report
2701 .view
2702 .branches
2703 .iter()
2704 .find(|branch| {
2705 branch.meta.kind == "try-operator" && branch.meta.source.contains("parse().ok()")
2706 })
2707 .expect("parse_twice's try operator");
2708 assert_eq!(
2709 tests_of(try_operator, "continued"),
2710 ["src/lib.rs::tests::parse_ok"]
2711 );
2712 assert_eq!(
2713 tests_of(try_operator, "early return"),
2714 ["src/lib.rs::tests::parse_bad"]
2715 );
2716 let mut logical = report
2717 .view
2718 .branches
2719 .iter()
2720 .filter(|branch| branch.meta.kind == "logical-and")
2721 .collect::<Vec<_>>();
2722 logical.sort_by_key(|branch| (branch.meta.line, branch.meta.column));
2723 assert_eq!(logical.len(), 3);
2725 assert_eq!(
2726 tests_of(logical[0], "short-circuited"),
2727 ["src/lib.rs::tests::false_path"]
2728 );
2729 assert_eq!(
2730 tests_of(logical[0], "right operand evaluated"),
2731 ["src/lib.rs::tests::true_path"]
2732 );
2733 assert_eq!(
2734 tests_of(logical[1], "short-circuited"),
2735 ["src/lib.rs::tests::chain_pattern_fails"]
2736 );
2737 assert_eq!(
2738 tests_of(logical[1], "right operand evaluated"),
2739 [
2740 "src/lib.rs::tests::chain_flag_fails",
2741 "src/lib.rs::tests::chain_negative",
2742 "src/lib.rs::tests::chain_taken",
2743 ]
2744 );
2745 assert_eq!(
2746 tests_of(logical[2], "short-circuited"),
2747 [
2748 "src/lib.rs::tests::chain_negative",
2749 "src/lib.rs::tests::chain_pattern_fails",
2750 ]
2751 );
2752 assert_eq!(
2753 tests_of(logical[2], "right operand evaluated"),
2754 [
2755 "src/lib.rs::tests::chain_flag_fails",
2756 "src/lib.rs::tests::chain_taken",
2757 ]
2758 );
2759 assert!(for_loop.covered && while_loop.covered && try_operator.covered);
2760 assert!(logical.iter().all(|branch| branch.covered));
2761
2762 let mut arms = report
2765 .view
2766 .branches
2767 .iter()
2768 .filter(|branch| branch.meta.kind == "match-arm")
2769 .collect::<Vec<_>>();
2770 arms.sort_by_key(|branch| branch.meta.line);
2771 assert_eq!(arms.len(), 3);
2772 let alternative = |arm: usize, label: &str| {
2773 arms[arm]
2774 .alternatives
2775 .iter()
2776 .find(|alternative| alternative.label == label)
2777 .unwrap_or_else(|| panic!("arm {arm} has no alternative {label}"))
2778 };
2779 assert_eq!(
2780 alternative(0, "selected").tests,
2781 ["src/lib.rs::tests::pick_zero"]
2782 );
2783 assert_eq!(
2784 alternative(0, "not selected").tests,
2785 ["src/lib.rs::tests::pick_many"]
2786 );
2787 assert!(!alternative(1, "selected").covered);
2788 assert_eq!(
2789 alternative(1, "not selected").tests,
2790 ["src/lib.rs::tests::pick_many"]
2791 );
2792 assert_eq!(arms[2].alternatives.len(), 1);
2793 assert_eq!(
2794 alternative(2, "selected").tests,
2795 ["src/lib.rs::tests::pick_many"]
2796 );
2797 assert!(arms[0].covered && !arms[1].covered && arms[2].covered);
2798
2799 fs::remove_dir_all(root).unwrap();
2800 }
2801}