supercov-engine 0.0.45

Rust instrumentation, evidence, attribution, and query engine for Supercov
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Public, isolated Rust coverage run lifecycle.

use std::{
    collections::BTreeSet,
    fs,
    io::Write,
    path::{Path, PathBuf},
    time::Instant,
};

use serde::{Deserialize, Serialize};

use crate::{
    evidence_archive::write_archive,
    integrity::{ExplicitIntegrityInputs, FrontendIntegrityInputs, create_explicit_run_integrity},
    lifecycle::{
        ProjectLock, finalize_published_run, publish_run, recover_abandoned_runs,
        remove_stored_tree_deferred,
    },
    run_store::{InstrumentedBuildCache, RawEvidenceMetadata, RunMetadata, RunTimings},
    rust_build_cache::{
        read_rust_build_cache, rust_build_cache_key, rust_target_directory, write_rust_build_cache,
    },
    rust_project::{PreparedRustProject, prepare_rust_project},
    rust_test_runner::run_prepared_rust_tests,
    workspace::{cached_workspace_path, prepare_cached_workspace, recover_cached_workspace},
};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DirectRustRunRequest {
    pub root: PathBuf,
    pub command: Vec<String>,
    pub run_id: String,
    pub started_at: String,
}

#[derive(Debug, Clone, PartialEq)]
pub struct DirectRustRunResult {
    pub run_id: String,
    pub run_directory: PathBuf,
    pub exit_code: i32,
    pub tests: usize,
    pub artifacts: usize,
    pub recovered_runs: Vec<String>,
    pub metadata: RunMetadata,
}

fn elapsed_ms(started: Instant) -> f64 {
    (started.elapsed().as_secs_f64() * 10_000.0).round() / 10.0
}

#[cfg(unix)]
fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
    use std::os::unix::ffi::OsStrExt as _;
    value.as_bytes().to_vec()
}

#[cfg(windows)]
fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
    use std::os::windows::ffi::OsStrExt as _;
    value
        .encode_wide()
        .flat_map(u16::to_le_bytes)
        .collect::<Vec<_>>()
}

#[cfg(not(any(unix, windows)))]
fn os_string_bytes(value: &std::ffi::OsStr) -> Vec<u8> {
    value.to_string_lossy().as_bytes().to_vec()
}

fn append_identity_field(destination: &mut Vec<u8>, value: &[u8]) {
    destination.extend_from_slice(&(value.len() as u64).to_le_bytes());
    destination.extend_from_slice(value);
}

const ROOT_INPUT_EXCLUSIONS: &[&str] = &[
    ".cache",
    ".git",
    ".supercov",
    ".mcdc-pool",
    "node_modules",
    "target",
    "build",
    "dist",
    ".next",
    ".nuxt",
    ".output",
    "coverage",
    "playwright-report",
    "test-results",
];

fn collect_project_inputs(
    root: &Path,
    directory: &Path,
    root_level: bool,
    regular: &mut Vec<PathBuf>,
    links: &mut Vec<String>,
) -> Result<(), String> {
    let mut entries = fs::read_dir(directory)
        .map_err(|error| format!("{}: {error}", directory.display()))?
        .collect::<Result<Vec<_>, _>>()
        .map_err(|error| error.to_string())?;
    entries.sort_by_key(fs::DirEntry::file_name);
    for entry in entries {
        let path = entry.path();
        let name = entry
            .file_name()
            .into_string()
            .map_err(|_| format!("Rust project contains a non-UTF-8 path: {}", path.display()))?;
        if (root_level && ROOT_INPUT_EXCLUSIONS.contains(&name.as_str()))
            || matches!(name.as_str(), ".supercov" | ".mcdc-pool")
        {
            continue;
        }
        let file_type = entry.file_type().map_err(|error| error.to_string())?;
        if file_type.is_dir() {
            collect_project_inputs(root, &path, false, regular, links)?;
        } else if file_type.is_file() {
            let relative = path
                .strip_prefix(root)
                .map_err(|_| format!("project input escaped root: {}", path.display()))?;
            regular.push(relative.to_owned());
        } else if file_type.is_symlink() {
            let relative = path
                .strip_prefix(root)
                .map_err(|_| format!("project link escaped root: {}", path.display()))?;
            let target = fs::read_link(&path).map_err(|error| error.to_string())?;
            links.push(format!(
                "{}=>{}",
                relative.to_string_lossy().replace('\\', "/"),
                target.to_string_lossy().replace('\\', "/")
            ));
        } else {
            return Err(format!(
                "unsupported Rust project input: {}",
                path.display()
            ));
        }
    }
    Ok(())
}

pub(crate) fn collect_integrity_inputs(
    root: &Path,
    command: &[String],
) -> Result<ExplicitIntegrityInputs, String> {
    let mut files = Vec::new();
    let mut links = Vec::new();
    collect_project_inputs(root, root, true, &mut files, &mut links)?;
    files.sort();
    files.dedup();
    links.sort();
    links.dedup();
    let source_files = files
        .iter()
        .filter(|path| path.extension().and_then(|value| value.to_str()) == Some("rs"))
        .cloned()
        .collect::<Vec<_>>();
    // Inline `#[cfg(test)]` modules make every Rust source file a possible test
    // input. Hashing the same file in both domains is intentional and prevents
    // stale reuse when only an inline test changes.
    let test_files = source_files.clone();
    let dependency_files = files
        .iter()
        .filter(|path| {
            path.file_name()
                .and_then(|value| value.to_str())
                .is_some_and(|name| matches!(name, "Cargo.toml" | "Cargo.lock"))
        })
        .cloned()
        .collect::<Vec<_>>();
    let source_set = source_files.iter().cloned().collect::<BTreeSet<_>>();
    let dependency_set = dependency_files.iter().cloned().collect::<BTreeSet<_>>();
    let configuration_files = files
        .into_iter()
        .filter(|path| !source_set.contains(path) && !dependency_set.contains(path))
        .collect();
    let mut execution_configuration = command.join("\0").into_bytes();
    for link in links {
        execution_configuration.push(0);
        execution_configuration.extend_from_slice(link.as_bytes());
    }
    let mut environment = std::env::vars_os()
        .map(|(key, value)| (os_string_bytes(&key), os_string_bytes(&value)))
        .collect::<Vec<_>>();
    environment.sort();
    for (key, value) in environment {
        append_identity_field(&mut execution_configuration, &key);
        append_identity_field(&mut execution_configuration, &value);
    }
    Ok(ExplicitIntegrityInputs {
        source_files,
        test_files,
        dependency_files,
        configuration_files,
        execution_configuration,
    })
}

pub fn current_rust_integrity(
    root: &Path,
    command: &[String],
) -> Result<crate::run_store::RunIntegrity, String> {
    let root = fs::canonicalize(root).map_err(|error| error.to_string())?;
    create_explicit_run_integrity(
        &root,
        &collect_integrity_inputs(&root, command)?,
        &FrontendIntegrityInputs::embedded_rust(),
    )
    .map_err(|error| error.to_string())
}

pub fn run_direct_rust(
    request: &DirectRustRunRequest,
    diagnostics: &mut dyn Write,
) -> Result<DirectRustRunResult, String> {
    if request.command.is_empty() {
        return Err("test command must not be empty".into());
    }
    // The shared probe runtime maps its evidence file and hooks thread and
    // process creation on macOS, Linux and Windows; on any other host every
    // probe is a no-op, so a run there would report zero coverage without a
    // word of explanation. Refuse plainly instead.
    if !cfg!(any(
        target_os = "macos",
        target_os = "linux",
        target_os = "windows"
    )) {
        return Err(
            "Rust suites are not supported on this platform: the probe transport has no implementation here, so a run would measure nothing"
                .into(),
        );
    }
    let total_started = Instant::now();
    let initialization_started = Instant::now();
    let root = fs::canonicalize(&request.root)
        .map_err(|error| format!("{}: {error}", request.root.display()))?;
    let mut lock = ProjectLock::acquire(&root, &request.run_id, &request.started_at)
        .map_err(|error| error.to_string())?;
    let initialization_ms = elapsed_ms(initialization_started);
    let result = (|| {
        let recovered_runs = recover_abandoned_runs(&root, &request.started_at)
            .map_err(|error| error.to_string())?;
        if !recovered_runs.is_empty() {
            writeln!(
                diagnostics,
                "[supercov] recovered abandoned run(s): {}",
                recovered_runs.join(", ")
            )
            .map_err(|error| error.to_string())?;
        }

        let adapter_started = Instant::now();
        let integrity_inputs = collect_integrity_inputs(&root, &request.command)?;
        let assertion_inputs =
            crate::assertion_inputs::capture(&root, "rust", integrity_inputs.assertion_paths())?;
        let integrity = create_explicit_run_integrity(
            &root,
            &integrity_inputs,
            &FrontendIntegrityInputs::embedded_rust(),
        )
        .map_err(|error| error.to_string())?;
        let build_cache_key = rust_build_cache_key(&integrity, &request.command)
            .map_err(|error| error.to_string())?;

        let workspace_started = Instant::now();
        recover_cached_workspace(&root, &lock).map_err(|error| error.to_string())?;
        let workspace = cached_workspace_path(&root).map_err(|error| error.to_string())?;
        let target_directory = rust_target_directory(&root);
        let cache_started = Instant::now();
        let cached = read_rust_build_cache(&workspace, &target_directory, &build_cache_key);
        let cache_read_ms = elapsed_ms(cache_started);
        let mut copy_ms = 0.0;
        let reused_build = cached.is_some();
        let mut project = if let Some(cached) = cached {
            writeln!(
                diagnostics,
                "[supercov] detected Rust; reusing authenticated instrumented workspace {}",
                workspace.display()
            )
            .map_err(|error| error.to_string())?;
            PreparedRustProject {
                workspace_root: workspace.clone(),
                target_directory: target_directory.clone(),
                source_files: cached.source_files,
                crate_roots: Vec::new(),
                runtime_module: String::new(),
                manifest: cached.manifest,
                preparation: Default::default(),
            }
        } else {
            let copy_started = Instant::now();
            let workspace =
                prepare_cached_workspace(&root, &lock, &[]).map_err(|error| error.to_string())?;
            copy_ms = elapsed_ms(copy_started);
            writeln!(
                diagnostics,
                "[supercov] detected Rust; instrumenting isolated Cargo workspace {}",
                workspace.display()
            )
            .map_err(|error| error.to_string())?;
            prepare_rust_project(&workspace).map_err(|error| error.to_string())?
        };
        project.target_directory = target_directory;
        fs::create_dir_all(&project.target_directory).map_err(|error| error.to_string())?;
        let workspace_preparation_ms = elapsed_ms(workspace_started);
        let adapter_setup_ms = (elapsed_ms(adapter_started) - workspace_preparation_ms).max(0.0);
        if std::env::var("SUPERCOV_PHASE_TIMING").as_deref() == Ok("1") {
            let preparation = &project.preparation;
            writeln!(
                diagnostics,
                "[supercov] workspace timings cache-check={cache_read_ms:.1}ms copy={copy_ms:.1}ms metadata={:.1}ms discovery={:.1}ms instrument={:.1}ms runtime={:.1}ms",
                preparation.metadata_ms,
                preparation.discovery_ms,
                preparation.instrument_ms,
                preparation.runtime_ms,
            )
            .map_err(|error| error.to_string())?;
        }

        let nextest = request
            .command
            .windows(2)
            .any(|pair| pair == ["nextest", "run"]);
        writeln!(
            diagnostics,
            "{}",
            if nextest {
                "[supercov] running cargo nextest with Supercov as its target runner, each attempt in its own process"
            } else {
                "[supercov] building once and running each libtest case and doctest in its own process"
            }
        )
        .map_err(|error| error.to_string())?;
        let run = run_prepared_rust_tests(
            &project,
            &request.command,
            &request.run_id,
            &request.started_at,
            diagnostics,
        )
        .map_err(|error| error.to_string())?;
        write_rust_build_cache(
            &root,
            &workspace,
            &build_cache_key,
            &request.started_at,
            &project.source_files,
            // The manifest the run reported: pruned to what the build
            // compiled, so a reused build reuses the same denominator.
            &run.request.manifest,
            &run.artifact_files,
        )?;

        let publication_started = Instant::now();
        let archive_path = root
            .join(".supercov/work")
            .join(&request.run_id)
            .join("evidence.raw.gz");
        let raw = write_archive(
            crate::assertion_inputs::append(
                run.archive_entries().map_err(|error| error.to_string())?,
                &assertion_inputs,
            )?,
            &archive_path,
        )
        .map_err(|error| error.to_string())?;
        remove_stored_tree_deferred(
            &root,
            &workspace
                .join(".supercov/rust-evidence")
                .join(&request.run_id),
        )
        .map_err(|error| error.to_string())?;
        let evidence_publication_ms = elapsed_ms(publication_started);
        let timings = RunTimings {
            initialization_ms,
            workspace_preparation_ms,
            adapter_setup_ms,
            instrumented_build_ms: (run.build_ms * 10.0).round() / 10.0,
            test_command_ms: (run.execution_ms * 10.0).round() / 10.0,
            evidence_publication_ms,
        };
        let metadata = RunMetadata {
            id: request.run_id.clone(),
            started_at: request.started_at.clone(),
            duration_ms: elapsed_ms(total_started),
            command: request.command.clone(),
            test_exit_code: Some(run.exit_code),
            integrity,
            raw_evidence: RawEvidenceMetadata {
                schema_version: raw.schema_version,
                format: raw.format.into(),
                file: raw.file.into(),
                files: raw.files,
                uncompressed_bytes: raw.uncompressed_bytes,
                compressed_bytes: raw.compressed_bytes,
            },
            isolated_build: Some(true),
            instrumented_build_cache: Some(InstrumentedBuildCache {
                key: build_cache_key,
                reused: reused_build,
            }),
            timings: Some(timings),
            merged: None,
            parents: None,
        };
        let run_directory =
            publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
        finalize_published_run(&root, &request.run_id).map_err(|error| error.to_string())?;
        Ok(DirectRustRunResult {
            run_id: request.run_id.clone(),
            run_directory,
            exit_code: run.exit_code,
            // Tests, not attempts: a retried test is still one test.
            tests: run
                .request
                .raw_results
                .iter()
                .map(|result| result.test.as_str())
                .collect::<std::collections::BTreeSet<_>>()
                .len(),
            artifacts: run.artifacts,
            recovered_runs,
            metadata,
        })
    })();
    if result.is_err() {
        let _ =
            remove_stored_tree_deferred(&root, &root.join(".supercov/work").join(&request.run_id));
        if let Ok(workspace) = cached_workspace_path(&root) {
            let _ = remove_stored_tree_deferred(
                &root,
                &workspace
                    .join(".supercov/rust-evidence")
                    .join(&request.run_id),
            );
        }
    }
    let release = lock.release().map_err(|error| error.to_string());
    match (result, release) {
        (Ok(result), Ok(())) => Ok(result),
        (Err(error), _) => Err(error),
        (Ok(_), Err(error)) => Err(error),
    }
}