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::{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 python_directory = work_directory.join("python");
235        let runtime_directory = python_directory.join("runtime");
236        let evidence_directory = python_directory.join("evidence");
237        let plan_path = python_directory.join("plan.json");
238        write_runtime(&runtime_directory)?;
239        fs::create_dir_all(&evidence_directory).map_err(|error| error.to_string())?;
240        fs::write(
241            &plan_path,
242            serde_json::to_vec(&project.plan).map_err(|error| error.to_string())?,
243        )
244        .map_err(|error| format!("{}: {error}", plan_path.display()))?;
245        writeln!(
246            diagnostics,
247            "[supercov] detected Python; measuring {} source file(s) in place through CPython monitoring",
248            project.plan.files.len()
249        )
250        .map_err(|error| error.to_string())?;
251        for (file, reason) in &project.unparseable {
252            writeln!(
253                diagnostics,
254                "[supercov] could not parse {file}: {reason}; it carries no obligations"
255            )
256            .map_err(|error| error.to_string())?;
257        }
258        let adapter_setup_ms = elapsed_ms(adapter_started);
259
260        let test_started = Instant::now();
261        let plan = ExecutionPlan {
262            preparation: Vec::new(),
263            test: ExecutionPhase {
264                name: "test".into(),
265                kind: PhaseKind::Test,
266                command: CommandSpec {
267                    program: request.command[0].clone().into(),
268                    arguments: request.command[1..].iter().map(OsString::from).collect(),
269                    cwd: root.clone(),
270                    environment: Some(environment(
271                        &root,
272                        &request.run_id,
273                        &runtime_directory,
274                        &plan_path,
275                        &evidence_directory,
276                    )),
277                    captured_output: None,
278                },
279            },
280        };
281        let options = SupervisionOptions::from_environment().map_err(|error| error.to_string())?;
282        let execution = execute_plan(&plan, options, diagnostics, |_, _| Ok(()))
283            .map_err(|error| error.to_string())?;
284        let test_command_ms = elapsed_ms(test_started);
285        if let Some(signal) = execution.interrupted_signal {
286            return Err(format!(
287                "the test command was interrupted by {signal:?}; no run was published"
288            ));
289        }
290
291        let publication_started = Instant::now();
292        let verbose = std::env::var("SUPERCOV_VERBOSE")
293            .or_else(|_| std::env::var("SUPERCOV_DEBUG"))
294            .is_ok_and(|value| matches!(value.as_str(), "1" | "true" | "yes"));
295        let run: PythonFrontendRun = build_python_frontend_run(
296            &project.manifest,
297            &evidence_directory,
298            &request.run_id,
299            &request.started_at,
300            execution.exit_code,
301        )
302        .map_err(|error| error.to_string())?;
303        validate_frontend_report_request(&run.declaration, &run.request)
304            .map_err(|error| error.to_string())?;
305        let joined_ms = elapsed_ms(publication_started);
306        let archive_path = work_directory.join("evidence.raw.gz");
307        let entries = run.archive_entries().map_err(|error| error.to_string())?;
308        let serialized_ms = elapsed_ms(publication_started) - joined_ms;
309        let raw = write_archive(entries, &archive_path).map_err(|error| error.to_string())?;
310        if verbose {
311            writeln!(
312                diagnostics,
313                "[supercov] python evidence: join={joined_ms}ms serialize={serialized_ms}ms archive={}ms",
314                elapsed_ms(publication_started) - joined_ms - serialized_ms
315            )
316            .map_err(|error| error.to_string())?;
317        }
318        if std::env::var("SUPERCOV_KEEP_WORK").is_ok_and(|value| !value.is_empty()) {
319            let debug_directory = root.join(".supercov/python-debug").join(&request.run_id);
320            fs::create_dir_all(&debug_directory).map_err(|error| error.to_string())?;
321            copy_tree(&python_directory, &debug_directory)?;
322        }
323        remove_stored_tree_deferred(&root, &python_directory).map_err(|error| error.to_string())?;
324        let evidence_publication_ms = elapsed_ms(publication_started);
325        let timings = RunTimings {
326            initialization_ms,
327            workspace_preparation_ms: 0.0,
328            adapter_setup_ms,
329            instrumented_build_ms: 0.0,
330            test_command_ms,
331            evidence_publication_ms,
332        };
333        let metadata = RunMetadata {
334            id: request.run_id.clone(),
335            started_at: request.started_at.clone(),
336            duration_ms: elapsed_ms(total_started),
337            command: request.command.clone(),
338            test_exit_code: Some(execution.exit_code),
339            integrity,
340            raw_evidence: RawEvidenceMetadata {
341                schema_version: raw.schema_version,
342                format: raw.format.into(),
343                file: raw.file.into(),
344                files: raw.files,
345                uncompressed_bytes: raw.uncompressed_bytes,
346                compressed_bytes: raw.compressed_bytes,
347            },
348            isolated_build: None,
349            instrumented_build_cache: None,
350            timings: Some(timings),
351            merged: None,
352            parents: None,
353        };
354        let run_directory =
355            publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
356        finalize_published_run(&root, &request.run_id).map_err(|error| error.to_string())?;
357        Ok(DirectPythonRunResult {
358            run_id: request.run_id.clone(),
359            run_directory,
360            exit_code: execution.exit_code,
361            tests: run.tests,
362            source_files: project.plan.files.len(),
363            interpreters: run.interpreters,
364            python_versions: run.python_versions,
365            recovered_runs,
366            metadata,
367        })
368    })();
369    if result.is_err() {
370        let _ = remove_stored_tree_deferred(&root, &work_directory);
371    }
372    let release = lock.release().map_err(|error| error.to_string());
373    match (result, release) {
374        (Ok(result), Ok(())) => Ok(result),
375        (Err(error), _) => Err(error),
376        (Ok(_), Err(error)) => Err(error),
377    }
378}