Skip to main content

supercov_engine/
rust_run.rs

1//! Public, isolated Rust coverage run lifecycle.
2
3use std::{
4    collections::BTreeSet,
5    fs,
6    io::Write,
7    path::{Path, PathBuf},
8    time::Instant,
9};
10
11use serde::{Deserialize, Serialize};
12
13use crate::{
14    evidence_archive::write_archive,
15    integrity::{ExplicitIntegrityInputs, FrontendIntegrityInputs, create_explicit_run_integrity},
16    lifecycle::{
17        ProjectLock, finalize_published_run, publish_run, recover_abandoned_runs,
18        remove_stored_tree_deferred,
19    },
20    run_store::{InstrumentedBuildCache, RawEvidenceMetadata, RunMetadata, RunTimings},
21    rust_build_cache::{
22        read_rust_build_cache, rust_build_cache_key, rust_target_directory, write_rust_build_cache,
23    },
24    rust_project::{PreparedRustProject, prepare_rust_project},
25    rust_test_runner::run_prepared_rust_tests,
26    workspace::{cached_workspace_path, prepare_cached_workspace, recover_cached_workspace},
27};
28
29#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
30#[serde(rename_all = "camelCase", deny_unknown_fields)]
31pub struct DirectRustRunRequest {
32    pub root: PathBuf,
33    pub command: Vec<String>,
34    pub run_id: String,
35    pub started_at: String,
36}
37
38#[derive(Debug, Clone, PartialEq)]
39pub struct DirectRustRunResult {
40    pub run_id: String,
41    pub run_directory: PathBuf,
42    pub exit_code: i32,
43    pub tests: usize,
44    pub artifacts: usize,
45    pub recovered_runs: Vec<String>,
46    pub metadata: RunMetadata,
47}
48
49fn elapsed_ms(started: Instant) -> f64 {
50    (started.elapsed().as_secs_f64() * 10_000.0).round() / 10.0
51}
52
53#[cfg(unix)]
54fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
55    use std::os::unix::ffi::OsStrExt as _;
56    value.as_bytes().to_vec()
57}
58
59#[cfg(windows)]
60fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
61    use std::os::windows::ffi::OsStrExt as _;
62    value
63        .encode_wide()
64        .flat_map(u16::to_le_bytes)
65        .collect::<Vec<_>>()
66}
67
68#[cfg(not(any(unix, windows)))]
69fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
70    value.to_string_lossy().as_bytes().to_vec()
71}
72
73fn append_identity_field(destination: &mut Vec<u8>, value: &[u8]) {
74    destination.extend_from_slice(&(value.len() as u64).to_le_bytes());
75    destination.extend_from_slice(value);
76}
77
78const ROOT_INPUT_EXCLUSIONS: &[&str] = &[
79    ".cache",
80    ".git",
81    ".supercov",
82    ".mcdc-pool",
83    "node_modules",
84    "target",
85    "build",
86    "dist",
87    ".next",
88    ".nuxt",
89    ".output",
90    "coverage",
91    "playwright-report",
92    "test-results",
93];
94
95fn collect_project_inputs(
96    root: &Path,
97    directory: &Path,
98    root_level: bool,
99    regular: &mut Vec<PathBuf>,
100    links: &mut Vec<String>,
101) -> Result<(), String> {
102    let mut entries = fs::read_dir(directory)
103        .map_err(|error| format!("{}: {error}", directory.display()))?
104        .collect::<Result<Vec<_>, _>>()
105        .map_err(|error| error.to_string())?;
106    entries.sort_by_key(fs::DirEntry::file_name);
107    for entry in entries {
108        let path = entry.path();
109        let name = entry
110            .file_name()
111            .into_string()
112            .map_err(|_| format!("Rust project contains a non-UTF-8 path: {}", path.display()))?;
113        if (root_level && ROOT_INPUT_EXCLUSIONS.contains(&name.as_str()))
114            || matches!(name.as_str(), ".supercov" | ".mcdc-pool")
115        {
116            continue;
117        }
118        let file_type = entry.file_type().map_err(|error| error.to_string())?;
119        if file_type.is_dir() {
120            collect_project_inputs(root, &path, false, regular, links)?;
121        } else if file_type.is_file() {
122            let relative = path
123                .strip_prefix(root)
124                .map_err(|_| format!("project input escaped root: {}", path.display()))?;
125            regular.push(relative.to_owned());
126        } else if file_type.is_symlink() {
127            let relative = path
128                .strip_prefix(root)
129                .map_err(|_| format!("project link escaped root: {}", path.display()))?;
130            let target = fs::read_link(&path).map_err(|error| error.to_string())?;
131            links.push(format!(
132                "{}=>{}",
133                relative.to_string_lossy().replace('\\', "/"),
134                target.to_string_lossy().replace('\\', "/")
135            ));
136        } else {
137            return Err(format!(
138                "unsupported Rust project input: {}",
139                path.display()
140            ));
141        }
142    }
143    Ok(())
144}
145
146fn collect_integrity_inputs(
147    root: &Path,
148    command: &[String],
149) -> Result<ExplicitIntegrityInputs, String> {
150    let mut files = Vec::new();
151    let mut links = Vec::new();
152    collect_project_inputs(root, root, true, &mut files, &mut links)?;
153    files.sort();
154    files.dedup();
155    links.sort();
156    links.dedup();
157    let source_files = files
158        .iter()
159        .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("rs"))
160        .cloned()
161        .collect::<Vec<_>>();
162    // Inline `#[cfg(test)]` modules make every Rust source file a possible test
163    // input. Hashing the same file in both domains is intentional and prevents
164    // stale reuse when only an inline test changes.
165    let test_files = source_files.clone();
166    let dependency_files = files
167        .iter()
168        .filter(|path| {
169            path.file_name()
170                .and_then(|value| value.to_str())
171                .is_some_and(|name| matches!(name, "Cargo.toml" | "Cargo.lock"))
172        })
173        .cloned()
174        .collect::<Vec<_>>();
175    let source_set = source_files.iter().cloned().collect::<BTreeSet<_>>();
176    let dependency_set = dependency_files.iter().cloned().collect::<BTreeSet<_>>();
177    let configuration_files = files
178        .into_iter()
179        .filter(|path| !source_set.contains(path) && !dependency_set.contains(path))
180        .collect();
181    let mut execution_configuration = command.join("\0").into_bytes();
182    for link in links {
183        execution_configuration.push(0);
184        execution_configuration.extend_from_slice(link.as_bytes());
185    }
186    let mut environment = std::env::vars_os()
187        .map(|(key, value)| (os_string_bytes(&key), os_string_bytes(&value)))
188        .collect::<Vec<_>>();
189    environment.sort();
190    for (key, value) in environment {
191        append_identity_field(&mut execution_configuration, &key);
192        append_identity_field(&mut execution_configuration, &value);
193    }
194    Ok(ExplicitIntegrityInputs {
195        source_files,
196        test_files,
197        dependency_files,
198        configuration_files,
199        execution_configuration,
200    })
201}
202
203pub fn current_rust_integrity(
204    root: &Path,
205    command: &[String],
206) -> Result<crate::run_store::RunIntegrity, String> {
207    let root = fs::canonicalize(root).map_err(|error| error.to_string())?;
208    create_explicit_run_integrity(
209        &root,
210        &collect_integrity_inputs(&root, command)?,
211        &FrontendIntegrityInputs::embedded_rust(),
212    )
213    .map_err(|error| error.to_string())
214}
215
216pub fn run_direct_rust(
217    request: &DirectRustRunRequest,
218    diagnostics: &mut dyn Write,
219) -> Result<DirectRustRunResult, String> {
220    if request.command.is_empty() {
221        return Err("test command must not be empty".into());
222    }
223    let total_started = Instant::now();
224    let initialization_started = Instant::now();
225    let root = fs::canonicalize(&request.root)
226        .map_err(|error| format!("{}: {error}", request.root.display()))?;
227    let mut lock = ProjectLock::acquire(&root, &request.run_id, &request.started_at)
228        .map_err(|error| error.to_string())?;
229    let initialization_ms = elapsed_ms(initialization_started);
230    let result = (|| {
231        let recovered_runs = recover_abandoned_runs(&root, &request.started_at)
232            .map_err(|error| error.to_string())?;
233        if !recovered_runs.is_empty() {
234            writeln!(
235                diagnostics,
236                "[supercov] recovered abandoned run(s): {}",
237                recovered_runs.join(", ")
238            )
239            .map_err(|error| error.to_string())?;
240        }
241
242        let adapter_started = Instant::now();
243        let integrity_inputs = collect_integrity_inputs(&root, &request.command)?;
244        let integrity = create_explicit_run_integrity(
245            &root,
246            &integrity_inputs,
247            &FrontendIntegrityInputs::embedded_rust(),
248        )
249        .map_err(|error| error.to_string())?;
250        let build_cache_key = rust_build_cache_key(&integrity, &request.command)
251            .map_err(|error| error.to_string())?;
252
253        let workspace_started = Instant::now();
254        recover_cached_workspace(&root, &lock).map_err(|error| error.to_string())?;
255        let workspace = cached_workspace_path(&root).map_err(|error| error.to_string())?;
256        let target_directory = rust_target_directory(&root);
257        let cached = read_rust_build_cache(&workspace, &target_directory, &build_cache_key);
258        let reused_build = cached.is_some();
259        let mut project = if let Some(cached) = cached {
260            writeln!(
261                diagnostics,
262                "[supercov] detected Rust; reusing authenticated instrumented workspace {}",
263                workspace.display()
264            )
265            .map_err(|error| error.to_string())?;
266            PreparedRustProject {
267                workspace_root: workspace.clone(),
268                target_directory: target_directory.clone(),
269                source_files: cached.source_files,
270                crate_roots: Vec::new(),
271                runtime_module: String::new(),
272                manifest: cached.manifest,
273            }
274        } else {
275            let workspace =
276                prepare_cached_workspace(&root, &lock, &[]).map_err(|error| error.to_string())?;
277            writeln!(
278                diagnostics,
279                "[supercov] detected Rust; instrumenting isolated Cargo workspace {}",
280                workspace.display()
281            )
282            .map_err(|error| error.to_string())?;
283            prepare_rust_project(&workspace).map_err(|error| error.to_string())?
284        };
285        project.target_directory = target_directory;
286        fs::create_dir_all(&project.target_directory).map_err(|error| error.to_string())?;
287        let workspace_preparation_ms = elapsed_ms(workspace_started);
288        let adapter_setup_ms = (elapsed_ms(adapter_started) - workspace_preparation_ms).max(0.0);
289
290        writeln!(
291            diagnostics,
292            "[supercov] building once and running each libtest case in its own process"
293        )
294        .map_err(|error| error.to_string())?;
295        let run = run_prepared_rust_tests(
296            &project,
297            &request.command,
298            &request.run_id,
299            &request.started_at,
300            diagnostics,
301        )
302        .map_err(|error| error.to_string())?;
303        write_rust_build_cache(
304            &root,
305            &workspace,
306            &build_cache_key,
307            &request.started_at,
308            &project.source_files,
309            &project.manifest,
310            &run.artifact_files,
311        )?;
312
313        let publication_started = Instant::now();
314        let archive_path = root
315            .join(".supercov/work")
316            .join(&request.run_id)
317            .join("evidence.raw.gz");
318        let raw = write_archive(
319            run.archive_entries().map_err(|error| error.to_string())?,
320            &archive_path,
321        )
322        .map_err(|error| error.to_string())?;
323        remove_stored_tree_deferred(
324            &root,
325            &workspace
326                .join(".supercov/rust-evidence")
327                .join(&request.run_id),
328        )
329        .map_err(|error| error.to_string())?;
330        let evidence_publication_ms = elapsed_ms(publication_started);
331        let timings = RunTimings {
332            initialization_ms,
333            workspace_preparation_ms,
334            adapter_setup_ms,
335            instrumented_build_ms: (run.build_ms * 10.0).round() / 10.0,
336            test_command_ms: (run.execution_ms * 10.0).round() / 10.0,
337            evidence_publication_ms,
338        };
339        let metadata = RunMetadata {
340            id: request.run_id.clone(),
341            started_at: request.started_at.clone(),
342            duration_ms: elapsed_ms(total_started),
343            command: request.command.clone(),
344            test_exit_code: Some(run.exit_code),
345            integrity,
346            raw_evidence: RawEvidenceMetadata {
347                schema_version: raw.schema_version,
348                format: raw.format.into(),
349                file: raw.file.into(),
350                files: raw.files,
351                uncompressed_bytes: raw.uncompressed_bytes,
352                compressed_bytes: raw.compressed_bytes,
353            },
354            isolated_build: Some(true),
355            instrumented_build_cache: Some(InstrumentedBuildCache {
356                key: build_cache_key,
357                reused: reused_build,
358            }),
359            timings: Some(timings),
360            merged: None,
361            parents: None,
362        };
363        let run_directory =
364            publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
365        finalize_published_run(&root, &request.run_id).map_err(|error| error.to_string())?;
366        Ok(DirectRustRunResult {
367            run_id: request.run_id.clone(),
368            run_directory,
369            exit_code: run.exit_code,
370            tests: run.request.raw_results.len(),
371            artifacts: run.artifacts,
372            recovered_runs,
373            metadata,
374        })
375    })();
376    if result.is_err() {
377        let _ =
378            remove_stored_tree_deferred(&root, &root.join(".supercov/work").join(&request.run_id));
379        if let Ok(workspace) = cached_workspace_path(&root) {
380            let _ = remove_stored_tree_deferred(
381                &root,
382                &workspace
383                    .join(".supercov/rust-evidence")
384                    .join(&request.run_id),
385            );
386        }
387    }
388    let release = lock.release().map_err(|error| error.to_string());
389    match (result, release) {
390        (Ok(result), Ok(())) => Ok(result),
391        (Err(error), _) => Err(error),
392        (Ok(_), Err(error)) => Err(error),
393    }
394}