Skip to main content

supercov_engine/
python_run.rs

1//! Public Python coverage run lifecycle.
2//!
3//! The project runs in place with its own interpreter, environment and test
4//! command. Supercov prepares the complete obligation manifest and probe plan
5//! from source, materialises its stdlib-only runtime under `.supercov/`,
6//! points the interpreter at it through environment variables, supervises the
7//! user's command unchanged, and publishes the joined evidence.
8
9use std::{
10    ffi::OsString,
11    fs,
12    io::Write,
13    path::{Path, PathBuf},
14    time::Instant,
15};
16
17use serde::{Deserialize, Serialize};
18
19use crate::workspace::canonicalize_simplified;
20use crate::{
21    evidence_archive::write_archive,
22    frontend_protocol::validate_frontend_report_request,
23    integrity::{FrontendIntegrityInputs, create_explicit_run_integrity},
24    lifecycle::{
25        ProjectLock, finalize_published_run, publish_run, recover_abandoned_runs,
26        remove_stored_tree_deferred,
27    },
28    orchestration::{ExecutionPhase, ExecutionPlan, PhaseKind, execute_plan},
29    process_supervision::{CommandSpec, SupervisionOptions},
30    python_evidence::{PythonAssertionInventory, PythonFrontendRun, build_python_frontend_run},
31    python_project::{PreparedPythonProject, prepare_python_project, python_integrity_inputs},
32    run_store::{RawEvidenceMetadata, RunMetadata, RunTimings},
33};
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
36#[serde(rename_all = "camelCase", deny_unknown_fields)]
37pub struct DirectPythonRunRequest {
38    pub root: PathBuf,
39    pub command: Vec<String>,
40    pub run_id: String,
41    pub started_at: String,
42}
43
44#[derive(Debug, Clone, PartialEq)]
45pub struct DirectPythonRunResult {
46    pub run_id: String,
47    pub run_directory: PathBuf,
48    pub exit_code: i32,
49    pub tests: usize,
50    pub source_files: usize,
51    pub interpreters: usize,
52    pub python_versions: Vec<String>,
53    pub recovered_runs: Vec<String>,
54    pub metadata: RunMetadata,
55}
56
57fn elapsed_ms(started: Instant) -> f64 {
58    (started.elapsed().as_secs_f64() * 10_000.0).round() / 10.0
59}
60
61fn embedded_runtime_files() -> [(&'static str, &'static [u8]); 4] {
62    [
63        (
64            "sitecustomize.py",
65            include_bytes!("../runtime-assets/python/sitecustomize.py"),
66        ),
67        (
68            "supercov_runtime.py",
69            include_bytes!("../runtime-assets/python/supercov_runtime.py"),
70        ),
71        (
72            "supercov_pytest.py",
73            include_bytes!("../runtime-assets/python/supercov_pytest.py"),
74        ),
75        (
76            "supercov_unittest.py",
77            include_bytes!("../runtime-assets/python/supercov_unittest.py"),
78        ),
79    ]
80}
81
82fn write_runtime(directory: &Path) -> Result<(), String> {
83    fs::create_dir_all(directory).map_err(|error| format!("{}: {error}", directory.display()))?;
84    for (name, contents) in embedded_runtime_files() {
85        let path = directory.join(name);
86        fs::write(&path, contents).map_err(|error| format!("{}: {error}", path.display()))?;
87    }
88    Ok(())
89}
90
91fn copy_tree(source: &Path, destination: &Path) -> Result<(), String> {
92    for entry in fs::read_dir(source).map_err(|error| format!("{}: {error}", source.display()))? {
93        let entry = entry.map_err(|error| error.to_string())?;
94        let target = destination.join(entry.file_name());
95        if entry
96            .file_type()
97            .map_err(|error| error.to_string())?
98            .is_dir()
99        {
100            fs::create_dir_all(&target).map_err(|error| error.to_string())?;
101            copy_tree(&entry.path(), &target)?;
102        } else {
103            fs::copy(entry.path(), &target).map_err(|error| error.to_string())?;
104        }
105    }
106    Ok(())
107}
108
109fn prepend_path_list(existing: Option<OsString>, entry: &Path) -> OsString {
110    let mut value = entry.as_os_str().to_owned();
111    if let Some(existing) = existing.filter(|existing| !existing.is_empty()) {
112        value.push(if cfg!(windows) { ";" } else { ":" });
113        value.push(existing);
114    }
115    value
116}
117
118fn append_list(existing: Option<OsString>, entry: &str, separator: &str) -> OsString {
119    match existing.filter(|existing| !existing.is_empty()) {
120        Some(existing) => {
121            let mut value = existing;
122            value.push(separator);
123            value.push(entry);
124            value
125        }
126        None => entry.into(),
127    }
128}
129
130fn environment(
131    root: &Path,
132    run_id: &str,
133    runtime_directory: &Path,
134    plan_path: &Path,
135    evidence_directory: &Path,
136) -> Vec<(OsString, OsString)> {
137    let mut variables = std::env::vars_os().collect::<Vec<_>>();
138    let mut take = |key: &str| {
139        let position = variables.iter().position(|(name, _)| name == key);
140        position.map(|index| variables.remove(index).1)
141    };
142    let python_path = prepend_path_list(take("PYTHONPATH"), runtime_directory);
143    let pytest_plugins = append_list(take("PYTEST_PLUGINS"), "supercov_pytest", ",");
144    // pytest calls its assertion-pass hook only from modules rewritten with
145    // this option on; the plugin gives those rewrites a cache name of their
146    // own. First in the list, so an explicit `-o` on the command line wins.
147    let pytest_addopts = {
148        let mut value = OsString::from("-o enable_assertion_pass_hook=true");
149        if let Some(existing) = take("PYTEST_ADDOPTS").filter(|existing| !existing.is_empty()) {
150            value.push(" ");
151            value.push(existing);
152        }
153        value
154    };
155    for key in [
156        "SUPERCOV_PYTHON_PLAN",
157        "SUPERCOV_PYTHON_EVIDENCE_DIR",
158        "SUPERCOV_RUN_ID",
159        "SUPERCOV_PROJECT_ROOT",
160        "SUPERCOV_CONTEXT",
161        "SUPERCOV_PYTHON_WORKER",
162    ] {
163        take(key);
164    }
165    variables.extend([
166        ("PYTHONPATH".into(), python_path),
167        ("PYTEST_PLUGINS".into(), pytest_plugins),
168        ("PYTEST_ADDOPTS".into(), pytest_addopts),
169        (
170            "SUPERCOV_PYTHON_PLAN".into(),
171            plan_path.as_os_str().to_owned(),
172        ),
173        (
174            "SUPERCOV_PYTHON_EVIDENCE_DIR".into(),
175            evidence_directory.as_os_str().to_owned(),
176        ),
177        ("SUPERCOV_RUN_ID".into(), run_id.into()),
178        ("SUPERCOV_PROJECT_ROOT".into(), root.as_os_str().to_owned()),
179    ]);
180    variables
181}
182
183/// The fingerprint a later query compares against the stored run: the same
184/// discovery and inputs the run used, without preparing a plan.
185pub fn current_python_integrity(
186    root: &Path,
187    command: &[String],
188) -> Result<crate::run_store::RunIntegrity, String> {
189    let root = canonicalize_simplified(root).map_err(|error| error.to_string())?;
190    let files = crate::python_project::discover_python_files(&root)?;
191    create_explicit_run_integrity(
192        &root,
193        &python_integrity_inputs(&files, command),
194        &FrontendIntegrityInputs::embedded_python(),
195    )
196    .map_err(|error| error.to_string())
197}
198
199pub fn run_direct_python(
200    request: &DirectPythonRunRequest,
201    diagnostics: &mut dyn Write,
202) -> Result<DirectPythonRunResult, String> {
203    if request.command.is_empty() {
204        return Err("test command must not be empty".into());
205    }
206    let total_started = Instant::now();
207    let initialization_started = Instant::now();
208    let root = canonicalize_simplified(&request.root)
209        .map_err(|error| format!("{}: {error}", request.root.display()))?;
210    let mut lock = ProjectLock::acquire(&root, &request.run_id, &request.started_at)
211        .map_err(|error| error.to_string())?;
212    let initialization_ms = elapsed_ms(initialization_started);
213    let work_directory = root.join(".supercov/work").join(&request.run_id);
214    let result = (|| {
215        let recovered_runs = recover_abandoned_runs(&root, &request.started_at)
216            .map_err(|error| error.to_string())?;
217        if !recovered_runs.is_empty() {
218            writeln!(
219                diagnostics,
220                "[supercov] recovered abandoned run(s): {}",
221                recovered_runs.join(", ")
222            )
223            .map_err(|error| error.to_string())?;
224        }
225
226        let adapter_started = Instant::now();
227        let project: PreparedPythonProject = prepare_python_project(&root)?;
228        let integrity = create_explicit_run_integrity(
229            &root,
230            &python_integrity_inputs(&project.files, &request.command),
231            &FrontendIntegrityInputs::embedded_python(),
232        )
233        .map_err(|error| error.to_string())?;
234        let assertion_inputs = crate::assertion_inputs::capture(
235            &root,
236            "python",
237            python_integrity_inputs(&project.files, &request.command).assertion_paths(),
238        )?;
239        let python_directory = work_directory.join("python");
240        let runtime_directory = python_directory.join("runtime");
241        let evidence_directory = python_directory.join("evidence");
242        let plan_path = python_directory.join("plan.json");
243        write_runtime(&runtime_directory)?;
244        fs::create_dir_all(&evidence_directory).map_err(|error| error.to_string())?;
245        fs::write(
246            &plan_path,
247            serde_json::to_vec(&project.plan).map_err(|error| error.to_string())?,
248        )
249        .map_err(|error| format!("{}: {error}", plan_path.display()))?;
250        writeln!(
251            diagnostics,
252            "[supercov] detected Python; measuring {} source file(s) in place through CPython monitoring",
253            project.plan.files.len()
254        )
255        .map_err(|error| error.to_string())?;
256        for (file, reason) in &project.unparseable {
257            writeln!(
258                diagnostics,
259                "[supercov] could not parse {file}: {reason}; it carries no obligations"
260            )
261            .map_err(|error| error.to_string())?;
262        }
263        let adapter_setup_ms = elapsed_ms(adapter_started);
264
265        let test_started = Instant::now();
266        let plan = ExecutionPlan {
267            preparation: Vec::new(),
268            test: ExecutionPhase {
269                name: "test".into(),
270                kind: PhaseKind::Test,
271                command: CommandSpec {
272                    program: request.command[0].clone().into(),
273                    arguments: request.command[1..].iter().map(OsString::from).collect(),
274                    cwd: root.clone(),
275                    environment: Some(environment(
276                        &root,
277                        &request.run_id,
278                        &runtime_directory,
279                        &plan_path,
280                        &evidence_directory,
281                    )),
282                    captured_output: None,
283                },
284            },
285        };
286        let options = SupervisionOptions::from_environment().map_err(|error| error.to_string())?;
287        let execution = execute_plan(&plan, options, diagnostics, |_, _| Ok(()))
288            .map_err(|error| error.to_string())?;
289        let test_command_ms = elapsed_ms(test_started);
290        if let Some(signal) = execution.interrupted_signal {
291            return Err(format!(
292                "the test command was interrupted by {signal:?}; no run was published"
293            ));
294        }
295
296        let publication_started = Instant::now();
297        let verbose = std::env::var("SUPERCOV_VERBOSE")
298            .or_else(|_| std::env::var("SUPERCOV_DEBUG"))
299            .is_ok_and(|value| matches!(value.as_str(), "1" | "true" | "yes"));
300        let run: PythonFrontendRun = build_python_frontend_run(
301            &project.manifest,
302            &evidence_directory,
303            &request.run_id,
304            &request.started_at,
305            execution.exit_code,
306            &PythonAssertionInventory::new(&root, &assertion_inputs),
307        )
308        .map_err(|error| error.to_string())?;
309        validate_frontend_report_request(&run.declaration, &run.request)
310            .map_err(|error| error.to_string())?;
311        let joined_ms = elapsed_ms(publication_started);
312        let archive_path = work_directory.join("evidence.raw.gz");
313        let entries = run.archive_entries().map_err(|error| error.to_string())?;
314        let serialized_ms = elapsed_ms(publication_started) - joined_ms;
315        let entries = crate::assertion_inputs::append(entries, &assertion_inputs)?;
316        let raw = write_archive(entries, &archive_path).map_err(|error| error.to_string())?;
317        if verbose {
318            writeln!(
319                diagnostics,
320                "[supercov] python evidence: join={joined_ms}ms serialize={serialized_ms}ms archive={}ms",
321                elapsed_ms(publication_started) - joined_ms - serialized_ms
322            )
323            .map_err(|error| error.to_string())?;
324        }
325        if std::env::var("SUPERCOV_KEEP_WORK").is_ok_and(|value| !value.is_empty()) {
326            let debug_directory = root.join(".supercov/python-debug").join(&request.run_id);
327            fs::create_dir_all(&debug_directory).map_err(|error| error.to_string())?;
328            copy_tree(&python_directory, &debug_directory)?;
329        }
330        remove_stored_tree_deferred(&root, &python_directory).map_err(|error| error.to_string())?;
331        let evidence_publication_ms = elapsed_ms(publication_started);
332        let timings = RunTimings {
333            initialization_ms,
334            workspace_preparation_ms: 0.0,
335            adapter_setup_ms,
336            instrumented_build_ms: 0.0,
337            test_command_ms,
338            evidence_publication_ms,
339        };
340        let metadata = RunMetadata {
341            id: request.run_id.clone(),
342            started_at: request.started_at.clone(),
343            duration_ms: elapsed_ms(total_started),
344            command: request.command.clone(),
345            test_exit_code: Some(execution.exit_code),
346            integrity,
347            raw_evidence: RawEvidenceMetadata {
348                schema_version: raw.schema_version,
349                format: raw.format.into(),
350                file: raw.file.into(),
351                files: raw.files,
352                uncompressed_bytes: raw.uncompressed_bytes,
353                compressed_bytes: raw.compressed_bytes,
354            },
355            isolated_build: None,
356            instrumented_build_cache: None,
357            timings: Some(timings),
358            merged: None,
359            parents: None,
360        };
361        let run_directory =
362            publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
363        finalize_published_run(&root, &request.run_id).map_err(|error| error.to_string())?;
364        Ok(DirectPythonRunResult {
365            run_id: request.run_id.clone(),
366            run_directory,
367            exit_code: execution.exit_code,
368            tests: run.tests,
369            source_files: project.plan.files.len(),
370            interpreters: run.interpreters,
371            python_versions: run.python_versions,
372            recovered_runs,
373            metadata,
374        })
375    })();
376    if result.is_err() {
377        let _ = remove_stored_tree_deferred(&root, &work_directory);
378    }
379    let release = lock.release().map_err(|error| error.to_string());
380    match (result, release) {
381        (Ok(result), Ok(())) => Ok(result),
382        (Err(error), _) => Err(error),
383        (Ok(_), Err(error)) => Err(error),
384    }
385}