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    for key in [
145        "SUPERCOV_PYTHON_PLAN",
146        "SUPERCOV_PYTHON_EVIDENCE_DIR",
147        "SUPERCOV_RUN_ID",
148        "SUPERCOV_PROJECT_ROOT",
149        "SUPERCOV_CONTEXT",
150        "SUPERCOV_PYTHON_WORKER",
151    ] {
152        take(key);
153    }
154    variables.extend([
155        ("PYTHONPATH".into(), python_path),
156        ("PYTEST_PLUGINS".into(), pytest_plugins),
157        (
158            "SUPERCOV_PYTHON_PLAN".into(),
159            plan_path.as_os_str().to_owned(),
160        ),
161        (
162            "SUPERCOV_PYTHON_EVIDENCE_DIR".into(),
163            evidence_directory.as_os_str().to_owned(),
164        ),
165        ("SUPERCOV_RUN_ID".into(), run_id.into()),
166        ("SUPERCOV_PROJECT_ROOT".into(), root.as_os_str().to_owned()),
167    ]);
168    variables
169}
170
171/// The fingerprint a later query compares against the stored run: the same
172/// discovery and inputs the run used, without preparing a plan.
173pub fn current_python_integrity(
174    root: &Path,
175    command: &[String],
176) -> Result<crate::run_store::RunIntegrity, String> {
177    let root = canonicalize_simplified(root).map_err(|error| error.to_string())?;
178    let files = crate::python_project::discover_python_files(&root)?;
179    create_explicit_run_integrity(
180        &root,
181        &python_integrity_inputs(&files, command),
182        &FrontendIntegrityInputs::embedded_python(),
183    )
184    .map_err(|error| error.to_string())
185}
186
187pub fn run_direct_python(
188    request: &DirectPythonRunRequest,
189    diagnostics: &mut dyn Write,
190) -> Result<DirectPythonRunResult, String> {
191    if request.command.is_empty() {
192        return Err("test command must not be empty".into());
193    }
194    let total_started = Instant::now();
195    let initialization_started = Instant::now();
196    let root = canonicalize_simplified(&request.root)
197        .map_err(|error| format!("{}: {error}", request.root.display()))?;
198    let mut lock = ProjectLock::acquire(&root, &request.run_id, &request.started_at)
199        .map_err(|error| error.to_string())?;
200    let initialization_ms = elapsed_ms(initialization_started);
201    let work_directory = root.join(".supercov/work").join(&request.run_id);
202    let result = (|| {
203        let recovered_runs = recover_abandoned_runs(&root, &request.started_at)
204            .map_err(|error| error.to_string())?;
205        if !recovered_runs.is_empty() {
206            writeln!(
207                diagnostics,
208                "[supercov] recovered abandoned run(s): {}",
209                recovered_runs.join(", ")
210            )
211            .map_err(|error| error.to_string())?;
212        }
213
214        let adapter_started = Instant::now();
215        let project: PreparedPythonProject = prepare_python_project(&root)?;
216        let integrity = create_explicit_run_integrity(
217            &root,
218            &python_integrity_inputs(&project.files, &request.command),
219            &FrontendIntegrityInputs::embedded_python(),
220        )
221        .map_err(|error| error.to_string())?;
222        let python_directory = work_directory.join("python");
223        let runtime_directory = python_directory.join("runtime");
224        let evidence_directory = python_directory.join("evidence");
225        let plan_path = python_directory.join("plan.json");
226        write_runtime(&runtime_directory)?;
227        fs::create_dir_all(&evidence_directory).map_err(|error| error.to_string())?;
228        fs::write(
229            &plan_path,
230            serde_json::to_vec(&project.plan).map_err(|error| error.to_string())?,
231        )
232        .map_err(|error| format!("{}: {error}", plan_path.display()))?;
233        writeln!(
234            diagnostics,
235            "[supercov] detected Python; measuring {} source file(s) in place through CPython monitoring",
236            project.plan.files.len()
237        )
238        .map_err(|error| error.to_string())?;
239        for (file, reason) in &project.unparseable {
240            writeln!(
241                diagnostics,
242                "[supercov] could not parse {file}: {reason}; it carries no obligations"
243            )
244            .map_err(|error| error.to_string())?;
245        }
246        let adapter_setup_ms = elapsed_ms(adapter_started);
247
248        let test_started = Instant::now();
249        let plan = ExecutionPlan {
250            preparation: Vec::new(),
251            test: ExecutionPhase {
252                name: "test".into(),
253                kind: PhaseKind::Test,
254                command: CommandSpec {
255                    program: request.command[0].clone().into(),
256                    arguments: request.command[1..].iter().map(OsString::from).collect(),
257                    cwd: root.clone(),
258                    environment: Some(environment(
259                        &root,
260                        &request.run_id,
261                        &runtime_directory,
262                        &plan_path,
263                        &evidence_directory,
264                    )),
265                    captured_output: None,
266                },
267            },
268        };
269        let options = SupervisionOptions::from_environment().map_err(|error| error.to_string())?;
270        let execution = execute_plan(&plan, options, diagnostics, |_, _| Ok(()))
271            .map_err(|error| error.to_string())?;
272        let test_command_ms = elapsed_ms(test_started);
273        if let Some(signal) = execution.interrupted_signal {
274            return Err(format!(
275                "the test command was interrupted by {signal:?}; no run was published"
276            ));
277        }
278
279        let publication_started = Instant::now();
280        let verbose = std::env::var("SUPERCOV_VERBOSE")
281            .or_else(|_| std::env::var("SUPERCOV_DEBUG"))
282            .is_ok_and(|value| matches!(value.as_str(), "1" | "true" | "yes"));
283        let run: PythonFrontendRun = build_python_frontend_run(
284            &project.manifest,
285            &evidence_directory,
286            &request.run_id,
287            &request.started_at,
288            execution.exit_code,
289        )
290        .map_err(|error| error.to_string())?;
291        validate_frontend_report_request(&run.declaration, &run.request)
292            .map_err(|error| error.to_string())?;
293        let joined_ms = elapsed_ms(publication_started);
294        let archive_path = work_directory.join("evidence.raw.gz");
295        let entries = run.archive_entries().map_err(|error| error.to_string())?;
296        let serialized_ms = elapsed_ms(publication_started) - joined_ms;
297        let raw = write_archive(entries, &archive_path).map_err(|error| error.to_string())?;
298        if verbose {
299            writeln!(
300                diagnostics,
301                "[supercov] python evidence: join={joined_ms}ms serialize={serialized_ms}ms archive={}ms",
302                elapsed_ms(publication_started) - joined_ms - serialized_ms
303            )
304            .map_err(|error| error.to_string())?;
305        }
306        if std::env::var("SUPERCOV_KEEP_WORK").is_ok_and(|value| !value.is_empty()) {
307            let debug_directory = root.join(".supercov/python-debug").join(&request.run_id);
308            fs::create_dir_all(&debug_directory).map_err(|error| error.to_string())?;
309            copy_tree(&python_directory, &debug_directory)?;
310        }
311        remove_stored_tree_deferred(&root, &python_directory).map_err(|error| error.to_string())?;
312        let evidence_publication_ms = elapsed_ms(publication_started);
313        let timings = RunTimings {
314            initialization_ms,
315            workspace_preparation_ms: 0.0,
316            adapter_setup_ms,
317            instrumented_build_ms: 0.0,
318            test_command_ms,
319            evidence_publication_ms,
320        };
321        let metadata = RunMetadata {
322            id: request.run_id.clone(),
323            started_at: request.started_at.clone(),
324            duration_ms: elapsed_ms(total_started),
325            command: request.command.clone(),
326            test_exit_code: Some(execution.exit_code),
327            integrity,
328            raw_evidence: RawEvidenceMetadata {
329                schema_version: raw.schema_version,
330                format: raw.format.into(),
331                file: raw.file.into(),
332                files: raw.files,
333                uncompressed_bytes: raw.uncompressed_bytes,
334                compressed_bytes: raw.compressed_bytes,
335            },
336            isolated_build: None,
337            instrumented_build_cache: None,
338            timings: Some(timings),
339            merged: None,
340            parents: None,
341        };
342        let run_directory =
343            publish_run(&root, &metadata, &archive_path).map_err(|error| error.to_string())?;
344        finalize_published_run(&root, &request.run_id).map_err(|error| error.to_string())?;
345        Ok(DirectPythonRunResult {
346            run_id: request.run_id.clone(),
347            run_directory,
348            exit_code: execution.exit_code,
349            tests: run.tests,
350            source_files: project.plan.files.len(),
351            interpreters: run.interpreters,
352            python_versions: run.python_versions,
353            recovered_runs,
354            metadata,
355        })
356    })();
357    if result.is_err() {
358        let _ = remove_stored_tree_deferred(&root, &work_directory);
359    }
360    let release = lock.release().map_err(|error| error.to_string());
361    match (result, release) {
362        (Ok(result), Ok(())) => Ok(result),
363        (Err(error), _) => Err(error),
364        (Ok(_), Err(error)) => Err(error),
365    }
366}