Skip to main content

supercov_engine/
lifecycle.rs

1//! Crash-safe run publication, recovery and explicit retention.
2//!
3//! Deletion targets are derived from a trusted project root. Large trees are
4//! atomically moved into durable trash; recursive unlinking is a separate,
5//! retryable operation that the CLI can run in a detached child.
6
7use std::{
8    collections::BTreeSet,
9    fs::{self, File, OpenOptions},
10    io::{self, Read, Write},
11    path::{Component, Path, PathBuf},
12    sync::atomic::{AtomicU64, Ordering},
13    time::{Duration, SystemTime, UNIX_EPOCH},
14};
15
16use serde::{Deserialize, Serialize};
17use sha2::{Digest, Sha256};
18
19use crate::run_store::{RunMetadata, valid_run_id};
20
21const TRASH: &str = ".supercov/.trash";
22const INCOMPLETE_LOCK_GRACE: Duration = Duration::from_secs(30);
23static UNIQUE: AtomicU64 = AtomicU64::new(0);
24
25#[derive(Debug)]
26pub enum LifecycleError {
27    Io { path: PathBuf, source: io::Error },
28    InvalidRunId(String),
29    UnsafePath(PathBuf),
30    InvalidState(String),
31    ActiveRun { run_id: String, pid: u32 },
32    LockAcquiring,
33    LockUnavailable,
34    PublicationExists(String),
35    Metadata(serde_json::Error),
36    EvidenceLength { expected: u64, actual: u64 },
37    EvidenceChanged,
38}
39
40impl std::fmt::Display for LifecycleError {
41    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        match self {
43            Self::Io { path, source } => write!(formatter, "{}: {source}", path.display()),
44            Self::InvalidRunId(id) => write!(formatter, "invalid coverage run ID: {id}"),
45            Self::UnsafePath(path) => {
46                write!(
47                    formatter,
48                    "unsafe Supercov storage path: {}",
49                    path.display()
50                )
51            }
52            Self::InvalidState(reason) => write!(formatter, "invalid run state: {reason}"),
53            Self::ActiveRun { run_id, pid } => write!(
54                formatter,
55                "coverage run {run_id} is already active in this project (pid {pid})"
56            ),
57            Self::LockAcquiring => {
58                write!(
59                    formatter,
60                    "a coverage run is currently acquiring the project lock"
61                )
62            }
63            Self::LockUnavailable => {
64                write!(formatter, "could not acquire the Supercov project lock")
65            }
66            Self::PublicationExists(id) => write!(formatter, "coverage run already exists: {id}"),
67            Self::Metadata(error) => write!(formatter, "invalid run metadata: {error}"),
68            Self::EvidenceLength { expected, actual } => write!(
69                formatter,
70                "evidence length changed before publication: expected {expected}, got {actual}"
71            ),
72            Self::EvidenceChanged => write!(formatter, "evidence changed during publication"),
73        }
74    }
75}
76
77impl std::error::Error for LifecycleError {}
78
79fn io_error(path: &Path, source: io::Error) -> LifecycleError {
80    LifecycleError::Io {
81        path: path.to_owned(),
82        source,
83    }
84}
85
86fn checked_id(id: &str) -> Result<(), LifecycleError> {
87    valid_run_id(id)
88        .then_some(())
89        .ok_or_else(|| LifecycleError::InvalidRunId(id.into()))
90}
91
92fn absolute_root(root: &Path) -> Result<PathBuf, LifecycleError> {
93    if root.is_absolute() {
94        Ok(root.to_owned())
95    } else {
96        std::env::current_dir()
97            .map(|cwd| cwd.join(root))
98            .map_err(|source| io_error(root, source))
99    }
100}
101
102fn lexical_descendant(root: &Path, path: &Path) -> bool {
103    let Ok(local) = path.strip_prefix(root) else {
104        return false;
105    };
106    !local.as_os_str().is_empty()
107        && local
108            .components()
109            .all(|component| matches!(component, Component::Normal(_)))
110}
111
112fn reject_linked_ancestors(
113    root: &Path,
114    path: &Path,
115    include_leaf: bool,
116) -> Result<(), LifecycleError> {
117    let local = path
118        .strip_prefix(root)
119        .map_err(|_| LifecycleError::UnsafePath(path.into()))?;
120    let components = local.components().collect::<Vec<_>>();
121    let through = if include_leaf {
122        components.len()
123    } else {
124        components.len().saturating_sub(1)
125    };
126    let mut current = root.to_owned();
127    for component in components.into_iter().take(through) {
128        let Component::Normal(component) = component else {
129            return Err(LifecycleError::UnsafePath(path.into()));
130        };
131        current.push(component);
132        match fs::symlink_metadata(&current) {
133            Ok(metadata) if metadata.file_type().is_symlink() => {
134                return Err(LifecycleError::UnsafePath(current));
135            }
136            Ok(metadata) if !metadata.file_type().is_dir() => {
137                return Err(LifecycleError::UnsafePath(current));
138            }
139            Ok(_) => {}
140            Err(error) if error.kind() == io::ErrorKind::NotFound => break,
141            Err(source) => return Err(io_error(&current, source)),
142        }
143    }
144    Ok(())
145}
146
147fn owned_workspace_container(root: &Path) -> bool {
148    let container = crate::workspace::workspace_container(root);
149    crate::workspace::owned_workspace_path(&container)
150}
151
152fn unique_name() -> String {
153    let nanos = SystemTime::now()
154        .duration_since(UNIX_EPOCH)
155        .unwrap_or_default()
156        .as_nanos();
157    format!(
158        "{}-{nanos}-{}",
159        std::process::id(),
160        UNIQUE.fetch_add(1, Ordering::Relaxed)
161    )
162}
163
164/// Make a rename or creation inside `path` durable. On Unix a directory opens
165/// like a file and fsync flushes its entries. On Windows there is nothing to
166/// do and no way to do it: CreateFileW refuses to open a directory without
167/// FILE_FLAG_BACKUP_SEMANTICS and answers ERROR_ACCESS_DENIED, which is how
168/// the first Windows run died -- in the JavaScript frontend's own copy of this
169/// idiom, on the generated node_modules directory it had just created -- and
170/// NTFS journals directory metadata without an explicit sync. Every place
171/// that syncs a directory goes through here so the rule is stated once.
172pub(crate) fn sync_directory_handle(path: &Path) -> io::Result<()> {
173    #[cfg(unix)]
174    {
175        File::open(path).and_then(|directory| directory.sync_all())
176    }
177    #[cfg(not(unix))]
178    {
179        let _ = path;
180        Ok(())
181    }
182}
183
184pub(crate) fn sync_directory(path: &Path) -> Result<(), LifecycleError> {
185    sync_directory_handle(path).map_err(|source| io_error(path, source))
186}
187
188pub(crate) fn atomic_rename(source: &Path, destination: &Path) -> Result<(), LifecycleError> {
189    let source_parent = source
190        .parent()
191        .ok_or_else(|| LifecycleError::UnsafePath(source.into()))?;
192    let destination_parent = destination
193        .parent()
194        .ok_or_else(|| LifecycleError::UnsafePath(destination.into()))?;
195    fs::create_dir_all(destination_parent).map_err(|error| io_error(destination_parent, error))?;
196    fs::rename(source, destination).map_err(|error| io_error(destination, error))?;
197    sync_directory(destination_parent)?;
198    if source_parent != destination_parent {
199        sync_directory(source_parent)?;
200    }
201    Ok(())
202}
203
204pub(crate) fn atomic_write(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), LifecycleError> {
205    let parent = path
206        .parent()
207        .ok_or_else(|| LifecycleError::UnsafePath(path.into()))?;
208    reject_linked_ancestors(root, parent, true)?;
209    fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;
210    for _ in 0..16 {
211        let temporary = parent.join(format!(
212            ".{}.{}.tmp",
213            path.file_name()
214                .and_then(|value| value.to_str())
215                .unwrap_or("state"),
216            unique_name()
217        ));
218        let mut file = match OpenOptions::new()
219            .write(true)
220            .create_new(true)
221            .open(&temporary)
222        {
223            Ok(file) => file,
224            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
225            Err(source) => return Err(io_error(&temporary, source)),
226        };
227        if let Err(source) = file.write_all(bytes).and_then(|_| file.sync_all()) {
228            let _ = fs::remove_file(&temporary);
229            return Err(io_error(&temporary, source));
230        }
231        drop(file);
232        if let Err(source) = fs::rename(&temporary, path) {
233            let _ = fs::remove_file(&temporary);
234            return Err(io_error(path, source));
235        }
236        sync_directory(parent)?;
237        return Ok(());
238    }
239    Err(LifecycleError::LockUnavailable)
240}
241
242pub fn remove_stored_tree_deferred(
243    project_root: &Path,
244    target: &Path,
245) -> Result<Option<PathBuf>, LifecycleError> {
246    let root = absolute_root(project_root)?;
247    let target = if target.is_absolute() {
248        target.to_owned()
249    } else {
250        root.join(target)
251    };
252    match fs::symlink_metadata(&target) {
253        Ok(_) => {}
254        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
255        Err(source) => return Err(io_error(&target, source)),
256    }
257    let store = root.join(".supercov");
258    let trash = root.join(TRASH);
259    let in_store = lexical_descendant(&store, &target) && !lexical_descendant(&trash, &target);
260    let container = crate::workspace::workspace_container(&root);
261    let in_workspace = owned_workspace_container(&root)
262        && (target == container || lexical_descendant(&container, &target));
263    if !in_store && !in_workspace {
264        return Err(LifecycleError::UnsafePath(target));
265    }
266    reject_linked_ancestors(if in_store { &store } else { &container }, &target, false)?;
267    reject_linked_ancestors(&root, &trash, true)?;
268    fs::create_dir_all(&trash).map_err(|source| io_error(&trash, source))?;
269    let destination = trash.join(unique_name());
270    atomic_rename(&target, &destination)?;
271    Ok(Some(destination))
272}
273
274/// Retryable trash unlinking. Public commands execute this in a child.
275pub fn sweep_trash(project_root: &Path) -> Result<usize, LifecycleError> {
276    let root = absolute_root(project_root)?;
277    let trash = root.join(TRASH);
278    reject_linked_ancestors(&root, &trash, true)?;
279    let entries = match fs::read_dir(&trash) {
280        Ok(entries) => entries,
281        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(0),
282        Err(source) => return Err(io_error(&trash, source)),
283    };
284    let Some(_lock) = TrashLock::acquire(&trash)? else {
285        return Ok(0);
286    };
287    let mut removed = 0;
288    for entry in entries {
289        let entry = entry.map_err(|source| io_error(&trash, source))?;
290        let path = entry.path();
291        if entry.file_name() == ".deleter.lock" {
292            continue;
293        }
294        // An entry already gone -- removed by hand, or by a sweeper whose
295        // lock was replaced -- is as swept as one removed here.
296        let gone = |error: &io::Error| error.kind() == io::ErrorKind::NotFound;
297        let metadata = match fs::symlink_metadata(&path) {
298            Ok(metadata) => metadata,
299            Err(error) if gone(&error) => continue,
300            Err(source) => return Err(io_error(&path, source)),
301        };
302        let removal = if metadata.file_type().is_dir() {
303            fs::remove_dir_all(&path)
304        } else {
305            fs::remove_file(&path)
306        };
307        match removal {
308            Ok(()) => removed += 1,
309            Err(error) if gone(&error) => {}
310            Err(source) => return Err(io_error(&path, source)),
311        }
312    }
313    Ok(removed)
314}
315
316struct TrashLock {
317    path: PathBuf,
318}
319
320impl TrashLock {
321    fn acquire(trash: &Path) -> Result<Option<Self>, LifecycleError> {
322        let path = trash.join(".deleter.lock");
323        for _ in 0..2 {
324            match OpenOptions::new().write(true).create_new(true).open(&path) {
325                Ok(mut file) => {
326                    write!(file, "{}", std::process::id())
327                        .and_then(|_| file.sync_all())
328                        .map_err(|source| io_error(&path, source))?;
329                    return Ok(Some(Self { path }));
330                }
331                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
332                    let owner = fs::read_to_string(&path)
333                        .ok()
334                        .and_then(|value| value.parse::<u32>().ok());
335                    if owner.is_some_and(process_exists) {
336                        return Ok(None);
337                    }
338                    if owner.is_none() {
339                        let age = fs::metadata(&path)
340                            .and_then(|metadata| metadata.modified())
341                            .ok()
342                            .and_then(|modified| SystemTime::now().duration_since(modified).ok())
343                            .unwrap_or_default();
344                        if age < INCOMPLETE_LOCK_GRACE {
345                            return Ok(None);
346                        }
347                    }
348                    fs::remove_file(&path).map_err(|source| io_error(&path, source))?;
349                }
350                Err(source) => return Err(io_error(&path, source)),
351            }
352        }
353        Ok(None)
354    }
355}
356
357impl Drop for TrashLock {
358    fn drop(&mut self) {
359        let _ = fs::remove_file(&self.path);
360    }
361}
362
363#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
364#[serde(rename_all = "lowercase")]
365pub enum RunStateStatus {
366    Preparing,
367    Building,
368    Testing,
369    Publishing,
370    Complete,
371    Failed,
372    Interrupted,
373    Abandoned,
374}
375
376impl RunStateStatus {
377    pub fn terminal(self) -> bool {
378        matches!(
379            self,
380            Self::Complete | Self::Failed | Self::Interrupted | Self::Abandoned
381        )
382    }
383}
384
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(rename_all = "camelCase", deny_unknown_fields)]
387pub struct RunState {
388    pub id: String,
389    pub pid: u32,
390    pub root: String,
391    pub workspace: String,
392    pub started_at: String,
393    pub updated_at: String,
394    pub status: RunStateStatus,
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub signal: Option<String>,
397    #[serde(skip_serializing_if = "Option::is_none")]
398    pub error: Option<String>,
399}
400
401fn state_path(root: &Path, id: &str) -> PathBuf {
402    root.join(".supercov/work").join(id).join("state.json")
403}
404
405pub fn write_run_state(root: &Path, state: &RunState) -> Result<(), LifecycleError> {
406    checked_id(&state.id)?;
407    let mut bytes = serde_json::to_vec_pretty(state).map_err(LifecycleError::Metadata)?;
408    bytes.push(b'\n');
409    atomic_write(root, &state_path(root, &state.id), &bytes)
410}
411
412fn read_state(root: &Path, id: &str) -> Result<Option<RunState>, LifecycleError> {
413    checked_id(id)?;
414    let path = state_path(root, id);
415    let bytes = match fs::read(&path) {
416        Ok(bytes) => bytes,
417        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
418        Err(source) => return Err(io_error(&path, source)),
419    };
420    serde_json::from_slice(&bytes)
421        .map(Some)
422        .map_err(|error| LifecycleError::InvalidState(error.to_string()))
423}
424
425pub fn update_run_state(
426    root: &Path,
427    id: &str,
428    status: RunStateStatus,
429    updated_at: &str,
430    error: Option<String>,
431) -> Result<RunState, LifecycleError> {
432    let mut state = read_state(root, id)?
433        .ok_or_else(|| LifecycleError::InvalidState(format!("state is missing for {id}")))?;
434    state.status = status;
435    state.updated_at = updated_at.into();
436    state.error = error;
437    write_run_state(root, &state)?;
438    Ok(state)
439}
440
441pub fn interrupt_run_state(
442    root: &Path,
443    id: &str,
444    updated_at: &str,
445    signal: &str,
446) -> Result<RunState, LifecycleError> {
447    let mut state = read_state(root, id)?
448        .ok_or_else(|| LifecycleError::InvalidState(format!("state is missing for {id}")))?;
449    state.status = RunStateStatus::Interrupted;
450    state.updated_at = updated_at.into();
451    state.signal = Some(signal.into());
452    state.error = Some(format!("Interrupted by {signal}"));
453    write_run_state(root, &state)?;
454    Ok(state)
455}
456
457#[cfg(unix)]
458fn process_exists(pid: u32) -> bool {
459    if pid == 0 || pid > libc::pid_t::MAX as u32 {
460        return false;
461    }
462    // SAFETY: signal zero only checks existence/permission.
463    let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
464    result == 0 || io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
465}
466
467#[cfg(windows)]
468fn process_exists(pid: u32) -> bool {
469    use windows_sys::Win32::Foundation::{
470        CloseHandle, ERROR_ACCESS_DENIED, GetLastError, STILL_ACTIVE,
471    };
472    use windows_sys::Win32::System::Threading::{
473        GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
474    };
475    if pid == 0 {
476        return false;
477    }
478    // SAFETY: a query-only handle, closed below; nothing is read through it
479    // but the exit code.
480    let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
481    if handle.is_null() {
482        // A process another account owns refuses the query, and exists.
483        return unsafe { GetLastError() } == ERROR_ACCESS_DENIED;
484    }
485    let mut code = 0u32;
486    // SAFETY: `handle` is open and `code` outlives the call.
487    let read = unsafe { GetExitCodeProcess(handle, &mut code) };
488    // SAFETY: opened above and not used after this.
489    unsafe { CloseHandle(handle) };
490    read != 0 && code == STILL_ACTIVE as u32
491}
492
493#[cfg(not(any(unix, windows)))]
494fn process_exists(pid: u32) -> bool {
495    pid == std::process::id()
496}
497
498#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
499#[serde(rename_all = "camelCase", deny_unknown_fields)]
500struct LockOwner {
501    run_id: String,
502    pid: u32,
503    started_at: String,
504}
505
506pub struct ProjectLock {
507    root: PathBuf,
508    path: PathBuf,
509    owner: LockOwner,
510    released: bool,
511}
512
513impl ProjectLock {
514    pub fn acquire(root: &Path, run_id: &str, started_at: &str) -> Result<Self, LifecycleError> {
515        checked_id(run_id)?;
516        let path = root.join(".supercov/locks/active.json");
517        let parent = path.parent().expect("lock parent");
518        reject_linked_ancestors(root, parent, true)?;
519        fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;
520        // Direct frontends do not create an isolated workspace. Initialize
521        // the store's ignore file here as well, without replacing user rules
522        // or following a pre-existing symlink.
523        let ignore = root.join(".supercov/.gitignore");
524        match OpenOptions::new()
525            .write(true)
526            .create_new(true)
527            .open(&ignore)
528        {
529            Ok(mut file) => file
530                .write_all(b"*\n")
531                .map_err(|source| io_error(&ignore, source))?,
532            Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
533            Err(source) => return Err(io_error(&ignore, source)),
534        }
535        let owner = LockOwner {
536            run_id: run_id.into(),
537            pid: std::process::id(),
538            started_at: started_at.into(),
539        };
540        let mut payload = serde_json::to_vec_pretty(&owner).map_err(LifecycleError::Metadata)?;
541        payload.push(b'\n');
542        for _ in 0..2 {
543            match OpenOptions::new().write(true).create_new(true).open(&path) {
544                Ok(mut file) => {
545                    file.write_all(&payload)
546                        .and_then(|_| file.sync_all())
547                        .map_err(|source| io_error(&path, source))?;
548                    sync_directory(parent)?;
549                    return Ok(Self {
550                        root: root.to_owned(),
551                        path,
552                        owner,
553                        released: false,
554                    });
555                }
556                Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
557                    let existing = fs::read(&path)
558                        .ok()
559                        .and_then(|bytes| serde_json::from_slice::<LockOwner>(&bytes).ok());
560                    if let Some(existing) = existing {
561                        if process_exists(existing.pid) {
562                            return Err(LifecycleError::ActiveRun {
563                                run_id: existing.run_id,
564                                pid: existing.pid,
565                            });
566                        }
567                    } else {
568                        let age = fs::metadata(&path)
569                            .and_then(|metadata| metadata.modified())
570                            .ok()
571                            .and_then(|modified| SystemTime::now().duration_since(modified).ok())
572                            .unwrap_or_default();
573                        if age < INCOMPLETE_LOCK_GRACE {
574                            return Err(LifecycleError::LockAcquiring);
575                        }
576                    }
577                    fs::remove_file(&path).map_err(|source| io_error(&path, source))?;
578                }
579                Err(source) => return Err(io_error(&path, source)),
580            }
581        }
582        Err(LifecycleError::LockUnavailable)
583    }
584
585    pub fn release(&mut self) -> Result<(), LifecycleError> {
586        if self.released {
587            return Ok(());
588        }
589        self.released = true;
590        let owned = fs::read(&self.path)
591            .ok()
592            .and_then(|bytes| serde_json::from_slice::<LockOwner>(&bytes).ok())
593            .is_some_and(|owner| owner == self.owner);
594        if owned {
595            fs::remove_file(&self.path).map_err(|source| io_error(&self.path, source))?;
596        }
597        Ok(())
598    }
599
600    pub(crate) fn protects(&self, root: &Path) -> bool {
601        !self.released && self.root == root
602    }
603}
604
605impl Drop for ProjectLock {
606    fn drop(&mut self) {
607        let _ = self.release();
608    }
609}
610
611fn copy_regular_file(source: &Path, destination: &Path) -> Result<u64, LifecycleError> {
612    let metadata = fs::symlink_metadata(source).map_err(|error| io_error(source, error))?;
613    if !metadata.file_type().is_file() {
614        return Err(LifecycleError::UnsafePath(source.into()));
615    }
616    // A clone where the filesystem can make one (APFS, Btrfs, XFS): the
617    // archive's blocks are shared, not copied -- 150 MB on a large run --
618    // and the clone is the source as it was at that instant.
619    if reflink_copy::reflink(source, destination).is_ok() {
620        File::open(destination)
621            .and_then(|file| file.sync_all())
622            .map_err(|error| io_error(destination, error))?;
623        return fs::symlink_metadata(destination)
624            .map(|metadata| metadata.len())
625            .map_err(|error| io_error(destination, error));
626    }
627    let mut input = File::open(source).map_err(|error| io_error(source, error))?;
628    let mut output = OpenOptions::new()
629        .write(true)
630        .create_new(true)
631        .open(destination)
632        .map_err(|error| io_error(destination, error))?;
633    let copied = io::copy(&mut input, &mut output).map_err(|error| io_error(destination, error))?;
634    output
635        .sync_all()
636        .map_err(|error| io_error(destination, error))?;
637    Ok(copied)
638}
639
640fn file_sha256(path: &Path) -> Result<[u8; 32], LifecycleError> {
641    let metadata = fs::symlink_metadata(path).map_err(|source| io_error(path, source))?;
642    if !metadata.file_type().is_file() {
643        return Err(LifecycleError::UnsafePath(path.into()));
644    }
645    let mut file = File::open(path).map_err(|source| io_error(path, source))?;
646    let mut hash = Sha256::new();
647    let mut buffer = [0_u8; 128 * 1024];
648    loop {
649        let read = file
650            .read(&mut buffer)
651            .map_err(|source| io_error(path, source))?;
652        if read == 0 {
653            break;
654        }
655        hash.update(&buffer[..read]);
656    }
657    Ok(hash.finalize().into())
658}
659
660fn hex_digest(digest: &[u8; 32]) -> String {
661    use std::fmt::Write as _;
662    digest
663        .iter()
664        .fold(String::with_capacity(64), |mut text, byte| {
665            let _ = write!(text, "{byte:02x}");
666            text
667        })
668}
669
670/// Publish immutable run evidence with its source manifest cache and per-test
671/// execution record together.
672pub fn publish_run(
673    root: &Path,
674    metadata: &RunMetadata,
675    evidence_source: &Path,
676) -> Result<PathBuf, LifecycleError> {
677    publish_run_with_fault(root, metadata, evidence_source, Archived::default(), None)
678}
679
680/// What a frontend that still holds the run it archived hands publication,
681/// so it need not read the archive back: the analysis of the archived
682/// request, and the assertion inputs archived beside it. Each must be what
683/// the archive gives; a frontend that cannot say so leaves it out.
684#[derive(Default)]
685pub struct Archived {
686    pub report: Option<crate::coverage_report::CoverageReport>,
687    pub inputs: Option<crate::source_manifest::InputManifest>,
688}
689
690/// `publish_run` for a frontend that holds what it archived; see `Archived`.
691pub fn publish_archived_run(
692    root: &Path,
693    metadata: &RunMetadata,
694    evidence_source: &Path,
695    archived: Archived,
696) -> Result<PathBuf, LifecycleError> {
697    publish_run_with_fault(root, metadata, evidence_source, archived, None)
698}
699
700#[derive(Debug, Clone, Copy, PartialEq, Eq)]
701pub(crate) enum RunPublicationFault {
702    FinalRename,
703    /// The query index cannot be written at publication.
704    QueryIndexWrite,
705}
706
707pub(crate) fn publish_run_with_fault(
708    root: &Path,
709    metadata: &RunMetadata,
710    evidence_source: &Path,
711    archived: Archived,
712    fault: Option<RunPublicationFault>,
713) -> Result<PathBuf, LifecycleError> {
714    checked_id(&metadata.id)?;
715    let destination = root.join(".supercov/runs").join(&metadata.id);
716    reject_linked_ancestors(root, &destination, false)?;
717    if fs::symlink_metadata(&destination).is_ok() {
718        return Err(LifecycleError::PublicationExists(metadata.id.clone()));
719    }
720    let staging = root
721        .join(".supercov/work")
722        .join(&metadata.id)
723        .join("run-publication");
724    reject_linked_ancestors(root, &staging, true)?;
725    if fs::symlink_metadata(&staging).is_ok() {
726        remove_stored_tree_deferred(root, &staging)?;
727    }
728    let evidence_sha256 = file_sha256(evidence_source)?;
729    fs::create_dir_all(&staging).map_err(|source| io_error(&staging, source))?;
730    let copied = copy_regular_file(evidence_source, &staging.join("evidence.raw.gz"))?;
731    if copied != metadata.raw_evidence.compressed_bytes {
732        remove_stored_tree_deferred(root, &staging)?;
733        return Err(LifecycleError::EvidenceLength {
734            expected: metadata.raw_evidence.compressed_bytes,
735            actual: copied,
736        });
737    }
738    // What is published is the copy: it must be the evidence as hashed
739    // before it was taken.
740    if file_sha256(&staging.join("evidence.raw.gz"))? != evidence_sha256 {
741        remove_stored_tree_deferred(root, &staging)?;
742        return Err(LifecycleError::EvidenceChanged);
743    }
744    let mut json = serde_json::to_vec_pretty(metadata).map_err(LifecycleError::Metadata)?;
745    json.push(b'\n');
746    atomic_write(root, &staging.join("run.json"), &json)?;
747    // Everything publication derives from the evidence -- the record of what
748    // each test ran and the query index -- comes from one analysis of it, made
749    // here. Each used to analyse
750    // the archive on its own: once here, twice more in the first query after
751    // the run, and on a 3,900-test Python suite each analysis took 5 to 8
752    // seconds. Evidence that will not analyse is published as before; the
753    // first query then reports why.
754    let staged = crate::run_store::StoredRun {
755        id: metadata.id.clone(),
756        directory: staging.clone(),
757        evidence_path: staging.join("evidence.raw.gz"),
758        metadata_path: staging.join("run.json"),
759        query_index_path: staging.join(crate::run_store::RUST_QUERY_INDEX_FILE),
760        metadata: metadata.clone(),
761    };
762    let analysed = if metadata.merged == Some(true) {
763        None
764    } else if archived.report.is_some() {
765        archived.report
766    } else {
767        crate::run_store::analyze_stored_run(&staged).ok()
768    };
769    let archived_inputs = match archived
770        .inputs
771        .map(|manifest| {
772            crate::source_manifest::archived_manifest(manifest, hex_digest(&evidence_sha256))
773        })
774        .transpose()
775    {
776        Ok(inputs) => inputs,
777        Err(reason) => {
778            let _ = remove_stored_tree_deferred(root, &staging);
779            return Err(LifecycleError::InvalidState(format!(
780                "source manifest publication: {reason}"
781            )));
782        }
783    };
784    // The execution record and the query index both read the analysis and
785    // write their own files, so they are written side by side.
786    let prepared = std::thread::scope(|scope| {
787        let index = analysed.as_ref().map(|report| {
788            scope.spawn(|| {
789                // Disposable, like every query index: one that failed to
790                // write is rebuilt by the first query.
791                if fault == Some(RunPublicationFault::QueryIndexWrite)
792                    || crate::run_store::write_query_index_from(&staged, report).is_err()
793                {
794                    let _ = fs::remove_file(&staged.query_index_path);
795                }
796            })
797        });
798        let prepared = crate::source_manifest::prepare_publication_with(
799            root,
800            &staging,
801            metadata,
802            analysed.as_ref(),
803            archived_inputs,
804        );
805        if let Some(index) = index {
806            index
807                .join()
808                .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
809        }
810        prepared
811    });
812    // Everything publication derives from the analysis is written. It is
813    // gigabytes of small allocations on a large run, and freeing them is
814    // nobody's wait.
815    if let Some(report) = analysed {
816        std::thread::spawn(move || drop(report));
817    }
818    if let Err(reason) = prepared {
819        let _ = remove_stored_tree_deferred(root, &staging);
820        return Err(LifecycleError::InvalidState(format!(
821            "source manifest publication: {reason}"
822        )));
823    }
824    sync_directory(&staging)?;
825    let runs = destination.parent().expect("runs parent");
826    fs::create_dir_all(runs).map_err(|source| io_error(runs, source))?;
827    if fault == Some(RunPublicationFault::FinalRename) {
828        let error = io_error(
829            &destination,
830            io::Error::new(
831                io::ErrorKind::PermissionDenied,
832                "injected final run publication rename failure",
833            ),
834        );
835        let _ = remove_stored_tree_deferred(root, &staging);
836        return Err(error);
837    }
838    fs::rename(&staging, &destination).map_err(|source| io_error(&destination, source))?;
839    sync_directory(runs)?;
840    Ok(destination)
841}
842
843/// Read a published run's start timestamp for retention ordering. Runs whose
844/// metadata is missing or unreadable sort as oldest, matching the run inventory,
845/// which leaves such directories out of its listing altogether.
846fn published_started_at(root: &Path, id: &str) -> String {
847    let directory = root.join(".supercov/runs").join(id);
848    fs::read(directory.join("run.json"))
849        .ok()
850        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
851        .as_ref()
852        .and_then(|value| value.get("startedAt"))
853        .and_then(|value| value.as_str())
854        .unwrap_or_default()
855        .to_owned()
856}
857
858fn published_run(root: &Path, id: &str) -> bool {
859    let directory = root.join(".supercov/runs").join(id);
860    let metadata = fs::read(directory.join("run.json"))
861        .ok()
862        .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
863    metadata
864        .as_ref()
865        .and_then(|value| value.get("id"))
866        .and_then(|value| value.as_str())
867        == Some(id)
868        && fs::symlink_metadata(directory.join("evidence.raw.gz"))
869            .is_ok_and(|metadata| metadata.file_type().is_file())
870}
871
872pub fn finalize_published_run(root: &Path, id: &str) -> Result<bool, LifecycleError> {
873    checked_id(id)?;
874    if !published_run(root, id) {
875        return Ok(false);
876    }
877    remove_stored_tree_deferred(root, &root.join(".supercov/evidence").join(id))?;
878    remove_stored_tree_deferred(root, &root.join(".supercov/work").join(id))?;
879    Ok(true)
880}
881
882fn child_directories(path: &Path) -> Result<Vec<String>, LifecycleError> {
883    let root = path
884        .ancestors()
885        .find(|ancestor| ancestor.file_name().is_some_and(|name| name == ".supercov"))
886        .and_then(Path::parent)
887        .unwrap_or(path);
888    reject_linked_ancestors(root, path, true)?;
889    let entries = match fs::read_dir(path) {
890        Ok(entries) => entries,
891        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
892        Err(source) => return Err(io_error(path, source)),
893    };
894    let mut names = Vec::new();
895    for entry in entries {
896        let entry = entry.map_err(|source| io_error(path, source))?;
897        let file_type = entry
898            .file_type()
899            .map_err(|source| io_error(&entry.path(), source))?;
900        if file_type.is_symlink() {
901            return Err(LifecycleError::UnsafePath(entry.path()));
902        }
903        if !file_type.is_dir() {
904            continue;
905        }
906        let name = entry
907            .file_name()
908            .into_string()
909            .map_err(|_| LifecycleError::UnsafePath(entry.path()))?;
910        checked_id(&name)?;
911        names.push(name);
912    }
913    names.sort();
914    Ok(names)
915}
916
917/// Where a run's evidence is kept when Supercov could not publish it.
918const FAILED_EVIDENCE: &str = ".supercov/failed-evidence";
919
920/// Keep what a run measured when Supercov itself is what failed.
921///
922/// A suite pays for its measurement in wall clock, and the one that lost a run
923/// to a phase reported twice had spent two and three-quarter hours on it. The
924/// work directory goes when a run does not publish, and it held the only copy
925/// of the evidence: nothing was left to diagnose the failure with, and nothing
926/// to recover. The evidence is kept outside the work tree, where neither the
927/// recovery sweep nor the next run reclaims it, and the failure says where.
928///
929/// Best effort by design: a run has already failed by the time this is called,
930/// and being unable to keep the evidence must not replace the failure that
931/// matters with one about copying it.
932pub fn keep_failed_evidence(root: &Path, evidence: &Path, id: &str) -> Option<PathBuf> {
933    if !evidence.is_dir() {
934        return None;
935    }
936    let kept = root.join(FAILED_EVIDENCE).join(id);
937    fs::create_dir_all(&kept).ok()?;
938    let mut files = 0;
939    if copy_evidence(evidence, &kept, &mut files).is_err() || files == 0 {
940        // Nothing worth keeping, or nothing that could be: leave no empty
941        // directory behind to puzzle over.
942        let _ = fs::remove_dir_all(&kept);
943        return None;
944    }
945    Some(kept)
946}
947
948/// Say where a failed run's evidence was kept, on the failure itself.
949///
950/// The user is looking at a Supercov bug at this point; the one thing they can
951/// do about it is send the evidence, and they only will if the failure says
952/// where it is. Returns the error unchanged when there was nothing to keep.
953pub fn note_kept_evidence(root: &Path, evidence: &Path, id: &str, error: String) -> String {
954    let Some(kept) = keep_failed_evidence(root, evidence, id) else {
955        return error;
956    };
957    format!(
958        "{error}\n[supercov] the tests were measured and the run could not be published; \
959their evidence is kept at {} -- this is a Supercov bug, and that directory is what diagnoses it",
960        kept.display()
961    )
962}
963
964fn copy_evidence(source: &Path, destination: &Path, files: &mut usize) -> std::io::Result<()> {
965    for entry in fs::read_dir(source)? {
966        let entry = entry?;
967        let target = destination.join(entry.file_name());
968        if entry.file_type()?.is_dir() {
969            fs::create_dir_all(&target)?;
970            copy_evidence(&entry.path(), &target, files)?;
971        } else {
972            fs::copy(entry.path(), &target)?;
973            *files += 1;
974        }
975    }
976    Ok(())
977}
978
979pub fn recover_abandoned_runs(
980    root: &Path,
981    updated_at: &str,
982) -> Result<Vec<String>, LifecycleError> {
983    let mut recovered = Vec::new();
984    for id in child_directories(&root.join(".supercov/work"))? {
985        let Some(state) = read_state(root, &id)? else {
986            continue;
987        };
988        if state.status.terminal() {
989            finalize_published_run(root, &id)?;
990            continue;
991        }
992        if process_exists(state.pid) {
993            continue;
994        }
995        let workspace_name = root.file_name().unwrap_or_default();
996        remove_stored_tree_deferred(
997            root,
998            &root.join(".supercov/work").join(&id).join(workspace_name),
999        )?;
1000        remove_stored_tree_deferred(
1001            root,
1002            &root
1003                .join(".supercov/work")
1004                .join(&id)
1005                .join("run-publication"),
1006        )?;
1007        if !finalize_published_run(root, &id)? {
1008            remove_stored_tree_deferred(root, &root.join(".supercov/evidence").join(&id))?;
1009            update_run_state(
1010                root,
1011                &id,
1012                RunStateStatus::Abandoned,
1013                updated_at,
1014                Some(format!(
1015                    "Recovered after process {} exited without cleanup",
1016                    state.pid
1017                )),
1018            )?;
1019            remove_stored_tree_deferred(root, &root.join(".supercov/work").join(&id))?;
1020        }
1021        recovered.push(id);
1022    }
1023    recovered.sort();
1024    Ok(recovered)
1025}
1026
1027#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1028pub struct CleanupOptions {
1029    pub keep: usize,
1030    pub dry_run: bool,
1031}
1032
1033#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1034#[serde(rename_all = "camelCase")]
1035pub struct CleanupResult {
1036    pub removed_runs: Vec<String>,
1037    pub removed_workspaces: Vec<String>,
1038    pub removed_evidence: Vec<String>,
1039    /// Evidence kept from runs Supercov itself failed to publish. Retention
1040    /// leaves it alone -- it is the only copy, and the automatic path taking it
1041    /// is what made a lost run unrecoverable -- but `clean` is the user asking
1042    /// for the project's storage back, so it goes then, and the summary says so.
1043    pub removed_failed_evidence: Vec<String>,
1044    pub removed_build_cache: bool,
1045}
1046
1047pub fn cleanup_storage_locked(
1048    root: &Path,
1049    options: CleanupOptions,
1050    remove_build_cache: bool,
1051) -> Result<CleanupResult, LifecycleError> {
1052    let runs_root = root.join(".supercov/runs");
1053    let work_root = root.join(".supercov/work");
1054    let evidence_root = root.join(".supercov/evidence");
1055    let published = child_directories(&runs_root)?;
1056    let work = child_directories(&work_root)?;
1057    let evidence = child_directories(&evidence_root)?;
1058    let mut ids = published
1059        .iter()
1060        .chain(&work)
1061        .chain(&evidence)
1062        .cloned()
1063        .collect::<BTreeSet<_>>()
1064        .into_iter()
1065        .collect::<Vec<_>>();
1066    ids.sort_by(|left, right| right.cmp(left));
1067    let mut active = BTreeSet::new();
1068    for id in &ids {
1069        if read_state(root, id)?.is_some_and(|state| !state.status.terminal()) {
1070            active.insert(id.clone());
1071        }
1072    }
1073    let mut retention_order = published
1074        .iter()
1075        .filter(|id| !active.contains(*id))
1076        .map(|id| (published_started_at(root, id), id.clone()))
1077        .collect::<Vec<_>>();
1078    retention_order.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| right.1.cmp(&left.1)));
1079    let retained = retention_order
1080        .into_iter()
1081        .take(options.keep)
1082        .map(|(_, id)| id)
1083        .collect::<BTreeSet<_>>();
1084    let mut result = CleanupResult {
1085        removed_runs: Vec::new(),
1086        removed_workspaces: Vec::new(),
1087        removed_evidence: Vec::new(),
1088        removed_failed_evidence: Vec::new(),
1089        removed_build_cache: false,
1090    };
1091    for id in ids {
1092        if active.contains(&id) {
1093            continue;
1094        }
1095        let has_run = published.contains(&id);
1096        let remove_history = has_run && !retained.contains(&id);
1097        if work.contains(&id) && read_state(root, &id)?.is_none_or(|state| state.status.terminal())
1098        {
1099            result.removed_workspaces.push(id.clone());
1100            if !options.dry_run {
1101                remove_stored_tree_deferred(root, &work_root.join(&id))?;
1102            }
1103        }
1104        if evidence.contains(&id) && (!has_run || remove_history) {
1105            result.removed_evidence.push(id.clone());
1106            if !options.dry_run {
1107                remove_stored_tree_deferred(root, &evidence_root.join(&id))?;
1108            }
1109        }
1110        if remove_history {
1111            result.removed_runs.push(id.clone());
1112            if !options.dry_run {
1113                remove_stored_tree_deferred(root, &runs_root.join(&id))?;
1114            }
1115        }
1116    }
1117    // Only a full `clean` reclaims kept evidence. `--keep N` is a trim, and the
1118    // evidence of a run Supercov failed to publish is the last thing a user
1119    // trimming their history means to lose; a retention pass would take it
1120    // within one run of keeping it.
1121    if remove_build_cache && options.keep == 0 && active.is_empty() {
1122        let kept_root = root.join(FAILED_EVIDENCE);
1123        for id in child_directories(&kept_root)? {
1124            result.removed_failed_evidence.push(id.clone());
1125            if !options.dry_run {
1126                remove_stored_tree_deferred(root, &kept_root.join(&id))?;
1127            }
1128        }
1129    }
1130    let container = crate::workspace::workspace_container(root);
1131    let legacy = [root.join(".supercov/.cache"), root.join(".supercov/cache")];
1132    let mut caches = Vec::new();
1133    if remove_build_cache && active.is_empty() {
1134        if owned_workspace_container(root) {
1135            caches.push(container);
1136        }
1137        caches.extend(
1138            legacy
1139                .into_iter()
1140                .filter(|path| fs::symlink_metadata(path).is_ok()),
1141        );
1142    }
1143    result.removed_build_cache = !caches.is_empty();
1144    if !options.dry_run {
1145        for cache in caches {
1146            remove_stored_tree_deferred(root, &cache)?;
1147        }
1148    }
1149    Ok(result)
1150}
1151
1152fn cleanup_storage(
1153    root: &Path,
1154    options: CleanupOptions,
1155    remove_build_cache: bool,
1156    updated_at: &str,
1157) -> Result<CleanupResult, LifecycleError> {
1158    let operation = if remove_build_cache {
1159        "clean"
1160    } else {
1161        "retention"
1162    };
1163    let lock_id = format!("{operation}-{}-{}", std::process::id(), unique_name());
1164    let mut lock = ProjectLock::acquire(root, &lock_id, updated_at)?;
1165    recover_abandoned_runs(root, updated_at)?;
1166    let result = cleanup_storage_locked(root, options, remove_build_cache);
1167    lock.release()?;
1168    result
1169}
1170
1171pub fn clean_storage(
1172    root: &Path,
1173    options: CleanupOptions,
1174    updated_at: &str,
1175) -> Result<CleanupResult, LifecycleError> {
1176    cleanup_storage(root, options, true, updated_at)
1177}
1178
1179#[cfg(test)]
1180mod tests {
1181    use super::*;
1182    use crate::run_store::{RawEvidenceMetadata, RunFingerprint, RunIntegrity};
1183
1184    fn project() -> PathBuf {
1185        let root = std::env::temp_dir().join(format!("supercov-lifecycle-{}", unique_name()));
1186        fs::create_dir_all(root.join("src")).unwrap();
1187        fs::write(root.join("src/index.js"), "user source").unwrap();
1188        root
1189    }
1190
1191    fn kept_evidence(root: &Path, id: &str) -> PathBuf {
1192        let evidence = root.join(".supercov/work").join(id).join("python/evidence");
1193        fs::create_dir_all(&evidence).unwrap();
1194        fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
1195        keep_failed_evidence(root, &evidence, id).expect("the evidence")
1196    }
1197
1198    fn state(root: &Path, id: &str, status: RunStateStatus, pid: u32) -> RunState {
1199        RunState {
1200            id: id.into(),
1201            pid,
1202            root: root.display().to_string(),
1203            workspace: root.join("dist").display().to_string(),
1204            started_at: "start".into(),
1205            updated_at: "update".into(),
1206            status,
1207            signal: None,
1208            error: None,
1209        }
1210    }
1211
1212    fn metadata(id: &str, bytes: u64) -> RunMetadata {
1213        RunMetadata {
1214            id: id.into(),
1215            started_at: "2026-01-01T00:00:00Z".into(),
1216            duration_ms: 1.0,
1217            command: vec!["test".into()],
1218            test_exit_code: Some(0),
1219            integrity: RunIntegrity {
1220                schema_version: 2,
1221                instrumenter_version: "rust".into(),
1222                git: None,
1223                fingerprint: RunFingerprint {
1224                    algorithm: "sha256".into(),
1225                    source: "0".repeat(64),
1226                    tests: "0".repeat(64),
1227                    dependencies: "0".repeat(64),
1228                    configuration: "0".repeat(64),
1229                    instrumenter: "0".repeat(64),
1230                    execution: "0".repeat(64),
1231                    combined: "0".repeat(64),
1232                    source_files: 1,
1233                    test_files: 1,
1234                },
1235                stale: None,
1236                stale_reasons: None,
1237            },
1238            raw_evidence: RawEvidenceMetadata {
1239                schema_version: 2,
1240                format: "supercov-evidence-archive".into(),
1241                file: "evidence.raw.gz".into(),
1242                files: 1,
1243                uncompressed_bytes: bytes,
1244                compressed_bytes: bytes,
1245            },
1246            isolated_build: None,
1247            instrumented_build_cache: None,
1248            timings: None,
1249            merged: None,
1250            parents: None,
1251            source_roots: None,
1252        }
1253    }
1254
1255    fn evidence(root: &Path) -> (PathBuf, u64) {
1256        use crate::evidence_archive::{EvidenceArchiveEntry, write_archive};
1257        let mut entries = ["manifest.json", "frontend.json", "coverage-model.json"]
1258            .into_iter()
1259            .map(|path| EvidenceArchiveEntry {
1260                path: path.into(),
1261                contents: b"{}".to_vec(),
1262            })
1263            .collect::<Vec<_>>();
1264        let inputs =
1265            crate::source_capture::capture(root, "javascript", [PathBuf::from("src/index.js")])
1266                .unwrap();
1267        entries = crate::source_capture::append(entries, &inputs).unwrap();
1268        let path = root.join("evidence.gz");
1269        let metadata = write_archive(entries, &path).unwrap();
1270        (path, metadata.compressed_bytes)
1271    }
1272
1273    #[test]
1274    fn defers_only_owned_storage_and_sweeps_without_touching_source() {
1275        let root = project();
1276        let owned = root.join(".supercov/evidence/run");
1277        fs::create_dir_all(&owned).unwrap();
1278        fs::write(owned.join("hit"), "hit").unwrap();
1279        let trash = remove_stored_tree_deferred(&root, &owned).unwrap().unwrap();
1280        assert!(!owned.exists());
1281        assert!(trash.exists());
1282        assert!(matches!(
1283            remove_stored_tree_deferred(&root, &root.join("src")),
1284            Err(LifecycleError::UnsafePath(_))
1285        ));
1286        assert_eq!(sweep_trash(&root).unwrap(), 1);
1287        assert!(root.join("src/index.js").exists());
1288        fs::remove_dir_all(root).unwrap();
1289    }
1290
1291    #[cfg(unix)]
1292    #[test]
1293    fn refuses_linked_storage_ancestors_instead_of_renaming_external_data() {
1294        use std::os::unix::fs::symlink;
1295
1296        let root = project();
1297        let outside = project();
1298        fs::create_dir_all(root.join(".supercov")).unwrap();
1299        fs::create_dir_all(outside.join("run")).unwrap();
1300        fs::write(outside.join("run/user.txt"), "user").unwrap();
1301        symlink(&outside, root.join(".supercov/evidence")).unwrap();
1302        assert!(matches!(
1303            remove_stored_tree_deferred(&root, &root.join(".supercov/evidence/run")),
1304            Err(LifecycleError::UnsafePath(_))
1305        ));
1306        assert_eq!(
1307            fs::read_to_string(outside.join("run/user.txt")).unwrap(),
1308            "user"
1309        );
1310        fs::remove_dir_all(root).unwrap();
1311        fs::remove_dir_all(outside).unwrap();
1312    }
1313
1314    /// Evidence that analyses -- the analysable fixture run -- to publish as
1315    /// `id`, from outside the project's runs.
1316    fn analysable_evidence(root: &Path, id: &str) -> (PathBuf, RunMetadata) {
1317        let source = project();
1318        let directory = crate::run_store::create_analyzable_test_run(&source, "source");
1319        let evidence = root.join(format!("{id}.evidence.gz"));
1320        fs::copy(directory.join("evidence.raw.gz"), &evidence).unwrap();
1321        let mut metadata: RunMetadata =
1322            serde_json::from_slice(&fs::read(directory.join("run.json")).unwrap()).unwrap();
1323        metadata.id = id.into();
1324        fs::remove_dir_all(source).unwrap();
1325        (evidence, metadata)
1326    }
1327
1328    /// The published run as a query reads it.
1329    fn stored(root: &Path, id: &str) -> crate::run_store::StoredRun {
1330        let directory = root.join(".supercov/runs").join(id);
1331        crate::run_store::StoredRun {
1332            id: id.into(),
1333            evidence_path: directory.join("evidence.raw.gz"),
1334            metadata_path: directory.join("run.json"),
1335            query_index_path: directory.join(crate::run_store::RUST_QUERY_INDEX_FILE),
1336            metadata: serde_json::from_slice(&fs::read(directory.join("run.json")).unwrap())
1337                .unwrap(),
1338            directory,
1339        }
1340    }
1341
1342    #[test]
1343    fn publication_writes_the_query_index_a_first_query_would_have_built() {
1344        // Written beside staged evidence and renamed with it, the index must be
1345        // the one the first query builds from the published evidence -- the
1346        // same bytes, valid under the published run's identity.
1347        let root = project();
1348        let id = "2026-01-01T00-00-00-100Z";
1349        let (evidence, metadata) = analysable_evidence(&root, id);
1350        let published = publish_run(&root, &metadata, &evidence).unwrap();
1351        let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1352        assert!(index.is_file(), "publication wrote the index");
1353        let run = stored(&root, id);
1354        assert!(
1355            crate::run_store::open_existing_query_index(&run)
1356                .unwrap()
1357                .is_some(),
1358            "and it is valid for the published run"
1359        );
1360        let written = fs::read(&index).unwrap();
1361        fs::remove_file(&index).unwrap();
1362        crate::run_store::open_or_rebuild_query_index(&run).unwrap();
1363        assert_eq!(
1364            fs::read(&index).unwrap(),
1365            written,
1366            "a query rebuilds the same bytes"
1367        );
1368        fs::remove_dir_all(root).unwrap();
1369    }
1370
1371    #[test]
1372    fn evidence_that_will_not_analyse_is_published_as_it_was_before() {
1373        // Publication used to tolerate evidence it could not analyse and leave
1374        // the first query to report why. It still publishes it, writes neither
1375        // index nor summary, and the first query fails as it did.
1376        let root = project();
1377        let id = "2026-01-01T00-00-00-200Z";
1378        let (evidence, bytes) = evidence(&root);
1379        let published = publish_run(&root, &metadata(id, bytes), &evidence).unwrap();
1380        assert!(published.join("run.json").is_file());
1381        assert!(published.join("source-manifest.cache.json").is_file());
1382        assert!(
1383            !published
1384                .join(crate::run_store::RUST_QUERY_INDEX_FILE)
1385                .exists()
1386        );
1387        assert!(
1388            !published
1389                .join(crate::source_manifest::EXECUTIONS_FILE)
1390                .exists()
1391        );
1392        let run = stored(&root, id);
1393        let Err(query) = crate::run_store::open_or_rebuild_query_index(&run) else {
1394            panic!("the first query cannot analyse it either");
1395        };
1396        let direct = crate::run_store::analyze_stored_run(&run).expect_err("unanalysable");
1397        assert_eq!(
1398            query.to_string(),
1399            direct.to_string(),
1400            "and says why in the same words"
1401        );
1402        fs::remove_dir_all(root).unwrap();
1403    }
1404
1405    #[test]
1406    fn a_merged_run_is_indexed_by_its_first_query() {
1407        // Publication does not analyse a merged run; its first query does.
1408        let root = project();
1409        let id = "2026-01-01T00-00-00-300Z";
1410        let (evidence, mut metadata) = analysable_evidence(&root, id);
1411        metadata.merged = Some(true);
1412        let published = publish_run(&root, &metadata, &evidence).unwrap();
1413        let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1414        assert!(!index.exists());
1415        crate::run_store::open_or_rebuild_query_index(&stored(&root, id)).unwrap();
1416        assert!(index.is_file());
1417        fs::remove_dir_all(root).unwrap();
1418    }
1419
1420    #[test]
1421    fn an_index_that_could_not_be_written_is_built_by_the_first_query() {
1422        // A failed index write loses nothing: publication succeeds without a
1423        // partial file, and the first query builds the index as it used to.
1424        let root = project();
1425        let id = "2026-01-01T00-00-00-400Z";
1426        let (evidence, metadata) = analysable_evidence(&root, id);
1427        let published = publish_run_with_fault(
1428            &root,
1429            &metadata,
1430            &evidence,
1431            Archived::default(),
1432            Some(RunPublicationFault::QueryIndexWrite),
1433        )
1434        .unwrap();
1435        let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1436        assert!(!index.exists(), "no partial index is left");
1437        assert!(published.join("run.json").is_file());
1438        crate::run_store::open_or_rebuild_query_index(&stored(&root, id)).unwrap();
1439        assert!(index.is_file());
1440        fs::remove_dir_all(root).unwrap();
1441    }
1442
1443    #[test]
1444    fn publishes_both_required_files_with_one_visible_rename() {
1445        let root = project();
1446        let id = "2026-01-01T00-00-00-000Z";
1447        let (evidence, bytes) = evidence(&root);
1448        let published = publish_run(&root, &metadata(id, bytes), &evidence).unwrap();
1449        assert!(published.join("run.json").is_file());
1450        assert_eq!(
1451            fs::read(published.join("evidence.raw.gz")).unwrap(),
1452            fs::read(&evidence).unwrap()
1453        );
1454        assert!(published.join("source-manifest.cache.json").is_file());
1455        assert!(matches!(
1456            publish_run(&root, &metadata(id, bytes), &evidence),
1457            Err(LifecycleError::PublicationExists(_))
1458        ));
1459        fs::remove_dir_all(root).unwrap();
1460    }
1461
1462    #[test]
1463    fn final_rename_failure_exposes_no_run_and_removes_staging() {
1464        let root = project();
1465        let id = "2026-01-01T00-00-00-000Z";
1466        let (evidence, bytes) = evidence(&root);
1467        let error = publish_run_with_fault(
1468            &root,
1469            &metadata(id, bytes),
1470            &evidence,
1471            Archived::default(),
1472            Some(RunPublicationFault::FinalRename),
1473        )
1474        .unwrap_err();
1475        assert!(
1476            error
1477                .to_string()
1478                .contains("injected final run publication rename failure")
1479        );
1480        assert!(!root.join(".supercov/runs").join(id).exists());
1481        assert!(
1482            !root
1483                .join(".supercov/work")
1484                .join(id)
1485                .join("run-publication")
1486                .exists()
1487        );
1488        sweep_trash(&root).unwrap();
1489        fs::remove_dir_all(root).unwrap();
1490    }
1491
1492    #[test]
1493    fn malformed_assertion_inputs_expose_no_partial_run() {
1494        use crate::evidence_archive::{read_archive, write_archive};
1495        let root = project();
1496        let id = "2026-01-01T00-00-00-000Z";
1497        let (evidence, _) = evidence(&root);
1498        let mut entries = read_archive(&evidence).unwrap();
1499        entries
1500            .iter_mut()
1501            .find(|e| e.path == crate::source_capture::ARCHIVE_PATH)
1502            .unwrap()
1503            .contents = b"{broken".to_vec();
1504        let raw = write_archive(entries, &evidence).unwrap();
1505        let error = publish_run(&root, &metadata(id, raw.compressed_bytes), &evidence).unwrap_err();
1506        assert!(error.to_string().contains("source manifest publication"));
1507        assert!(!root.join(".supercov/runs").join(id).exists());
1508        assert!(
1509            !root
1510                .join(".supercov/work")
1511                .join(id)
1512                .join("run-publication")
1513                .exists()
1514        );
1515        fs::remove_dir_all(root).unwrap();
1516    }
1517
1518    #[test]
1519    fn recovers_dead_unpublished_and_fully_published_runs_from_derived_paths() {
1520        let root = project();
1521        let dead = "2026-01-01T00-00-00-000Z";
1522        let published = "2026-01-02T00-00-00-000Z";
1523        for id in [dead, published] {
1524            fs::create_dir_all(
1525                root.join(".supercov/work")
1526                    .join(id)
1527                    .join(root.file_name().unwrap()),
1528            )
1529            .unwrap();
1530            fs::create_dir_all(root.join(".supercov/evidence").join(id)).unwrap();
1531            write_run_state(&root, &state(&root, id, RunStateStatus::Testing, u32::MAX)).unwrap();
1532        }
1533        let (evidence, bytes) = evidence(&root);
1534        publish_run(&root, &metadata(published, bytes), &evidence).unwrap();
1535        assert_eq!(
1536            recover_abandoned_runs(&root, "recovered").unwrap(),
1537            [dead, published]
1538        );
1539        assert!(!root.join(".supercov/work").join(dead).exists());
1540        assert!(!root.join(".supercov/work").join(published).exists());
1541        assert!(root.join(".supercov/runs").join(published).exists());
1542        assert!(root.join("src/index.js").exists());
1543        sweep_trash(&root).unwrap();
1544        fs::remove_dir_all(root).unwrap();
1545    }
1546
1547    #[test]
1548    fn retention_is_deterministic_dry_run_safe_and_preserves_active_work() {
1549        let root = project();
1550        let ids = [
1551            "2026-01-01T00-00-00-000Z",
1552            "2026-01-02T00-00-00-000Z",
1553            "2026-01-03T00-00-00-000Z",
1554        ];
1555        for id in ids {
1556            fs::create_dir_all(root.join(".supercov/runs").join(id)).unwrap();
1557            write_run_state(
1558                &root,
1559                &state(&root, id, RunStateStatus::Complete, std::process::id()),
1560            )
1561            .unwrap();
1562        }
1563        let active = "2025-12-31T00-00-00-000Z";
1564        write_run_state(
1565            &root,
1566            &state(&root, active, RunStateStatus::Testing, std::process::id()),
1567        )
1568        .unwrap();
1569        let preview = cleanup_storage_locked(
1570            &root,
1571            CleanupOptions {
1572                keep: 1,
1573                dry_run: true,
1574            },
1575            false,
1576        )
1577        .unwrap();
1578        assert_eq!(preview.removed_runs, [ids[1], ids[0]]);
1579        assert!(
1580            ids.iter()
1581                .all(|id| root.join(".supercov/runs").join(id).exists())
1582        );
1583        let result = cleanup_storage_locked(
1584            &root,
1585            CleanupOptions {
1586                keep: 1,
1587                dry_run: false,
1588            },
1589            false,
1590        )
1591        .unwrap();
1592        assert_eq!(result, preview);
1593        assert!(root.join(".supercov/work").join(active).exists());
1594        assert!(root.join(".supercov/runs").join(ids[2]).exists());
1595        sweep_trash(&root).unwrap();
1596        fs::remove_dir_all(root).unwrap();
1597    }
1598
1599    #[test]
1600    fn retention_keeps_the_newest_runs_when_run_ids_disagree_with_recency() {
1601        let root = project();
1602        let (evidence, bytes) = evidence(&root);
1603        // Run IDs are random hex, so ordering them as strings says nothing about
1604        // time. The newest run here carries the smallest ID and must survive.
1605        for (id, started_at) in [
1606            ("run_ffffffffffffffff", "2026-01-01T00:00:00Z"),
1607            ("run_7777777777777777", "2026-05-01T00:00:00Z"),
1608            ("run_0000000000000001", "2026-09-01T00:00:00Z"),
1609        ] {
1610            let mut run = metadata(id, bytes);
1611            run.started_at = started_at.into();
1612            publish_run(&root, &run, &evidence).unwrap();
1613        }
1614        let result = cleanup_storage_locked(
1615            &root,
1616            CleanupOptions {
1617                keep: 1,
1618                dry_run: false,
1619            },
1620            false,
1621        )
1622        .unwrap();
1623        assert_eq!(
1624            result.removed_runs,
1625            ["run_ffffffffffffffff", "run_7777777777777777"]
1626        );
1627        assert!(
1628            root.join(".supercov/runs")
1629                .join("run_0000000000000001")
1630                .exists()
1631        );
1632        sweep_trash(&root).unwrap();
1633        fs::remove_dir_all(root).unwrap();
1634    }
1635
1636    #[test]
1637    fn direct_runs_initialize_store_ignore_without_overwriting_existing_rules() {
1638        let root = project();
1639        let ignore = root.join(".supercov/.gitignore");
1640        let mut lock = ProjectLock::acquire(&root, "first", "start").unwrap();
1641        assert_eq!(fs::read_to_string(&ignore).unwrap(), "*\n");
1642        lock.release().unwrap();
1643        fs::write(&ignore, "custom\n").unwrap();
1644        let mut lock = ProjectLock::acquire(&root, "second", "start").unwrap();
1645        assert_eq!(fs::read_to_string(&ignore).unwrap(), "custom\n");
1646        lock.release().unwrap();
1647        fs::remove_dir_all(root).unwrap();
1648    }
1649
1650    #[test]
1651    fn cleanup_is_project_locked_and_clean_alone_removes_owned_caches() {
1652        let root = project();
1653        let container = root.join(".supercov/workspaces");
1654        fs::create_dir_all(container.join("workspace/project")).unwrap();
1655        fs::write(
1656            container.join(".supercov-workspace-store"),
1657            b"Supercov instrumented workspace. Safe to delete.\n",
1658        )
1659        .unwrap();
1660        fs::create_dir_all(root.join(".supercov/cache/legacy")).unwrap();
1661        let mut active = ProjectLock::acquire(&root, "active", "start").unwrap();
1662        assert!(matches!(
1663            clean_storage(
1664                &root,
1665                CleanupOptions {
1666                    keep: 0,
1667                    dry_run: false
1668                },
1669                "now"
1670            ),
1671            Err(LifecycleError::ActiveRun { .. })
1672        ));
1673        assert!(container.exists());
1674        active.release().unwrap();
1675
1676        let cleaned = clean_storage(
1677            &root,
1678            CleanupOptions {
1679                keep: 0,
1680                dry_run: false,
1681            },
1682            "now",
1683        )
1684        .unwrap();
1685        assert!(cleaned.removed_build_cache);
1686        assert!(!container.exists());
1687        assert!(!root.join(".supercov/cache").exists());
1688        sweep_trash(&root).unwrap();
1689        fs::remove_dir_all(root).unwrap();
1690    }
1691
1692    // What a failed run measured is the only record of hours of test time, and
1693    // it lived in the work tree that failing removes. #40 lost a run to a phase
1694    // reported twice after two and three-quarter hours, with nothing left to
1695    // diagnose it from.
1696    #[test]
1697    fn evidence_a_failed_run_measured_outlives_the_work_tree() {
1698        let root = project();
1699        let work = root.join(".supercov/work/run_kept");
1700        let evidence = work.join("python/evidence");
1701        fs::create_dir_all(evidence.join("worker-1")).unwrap();
1702        fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
1703        fs::write(evidence.join("worker-1/mcdc.json"), "{}").unwrap();
1704
1705        let kept = keep_failed_evidence(&root, &evidence, "run_kept").expect("the evidence");
1706        remove_stored_tree_deferred(&root, &work).unwrap();
1707        sweep_trash(&root).unwrap();
1708
1709        assert!(!evidence.exists(), "the work tree still went");
1710        assert_eq!(
1711            fs::read_to_string(kept.join("main.jsonl")).unwrap(),
1712            "what the run saw",
1713        );
1714        // Nested workers are evidence too: a run measured by several of them
1715        // cannot be diagnosed from one.
1716        assert_eq!(
1717            fs::read_to_string(kept.join("worker-1/mcdc.json")).unwrap(),
1718            "{}"
1719        );
1720        fs::remove_dir_all(root).unwrap();
1721    }
1722
1723    #[test]
1724    fn nothing_to_keep_leaves_no_directory_to_puzzle_over() {
1725        let root = project();
1726        // A run that failed before it measured anything: the frontend never
1727        // reached the point of writing evidence, or wrote none.
1728        let missing = root.join(".supercov/work/run_early/python/evidence");
1729        assert!(keep_failed_evidence(&root, &missing, "run_early").is_none());
1730        fs::create_dir_all(&missing).unwrap();
1731        assert!(keep_failed_evidence(&root, &missing, "run_early").is_none());
1732        assert!(
1733            !root.join(".supercov/failed-evidence/run_early").exists(),
1734            "an empty directory is worse than none: it reads as evidence",
1735        );
1736        fs::remove_dir_all(root).unwrap();
1737    }
1738
1739    // The failure is the only thing the user reads. Keeping the evidence and
1740    // not saying where is the same as not keeping it.
1741    #[test]
1742    fn the_failure_says_where_the_evidence_was_kept() {
1743        let root = project();
1744        let evidence = root.join(".supercov/work/run_told/python/evidence");
1745        fs::create_dir_all(&evidence).unwrap();
1746        fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
1747
1748        let told = note_kept_evidence(&root, &evidence, "run_told", "boom".into());
1749        // Taken from the keeper rather than spelled out here: a path written as
1750        // one string renders every separator the same way, which is not what a
1751        // Windows path built join by join looks like, so asserting on the
1752        // spelling tested this test instead of the message. Keeping is
1753        // idempotent, so asking again names the directory already kept.
1754        let kept = keep_failed_evidence(&root, &evidence, "run_told").expect("the evidence");
1755        assert_eq!(kept, root.join(FAILED_EVIDENCE).join("run_told"));
1756        assert!(
1757            told.starts_with("boom\n"),
1758            "the failure itself came second: {told}"
1759        );
1760        assert!(told.contains(&kept.display().to_string()), "{told}");
1761
1762        // Nothing kept, nothing to say: the failure that matters is not buried
1763        // under one about copying it.
1764        let nothing = root.join(".supercov/work/run_empty/python/evidence");
1765        assert_eq!(
1766            note_kept_evidence(&root, &nothing, "run_empty", "boom".into()),
1767            "boom",
1768        );
1769        fs::remove_dir_all(root).unwrap();
1770    }
1771
1772    #[test]
1773    fn a_trim_leaves_kept_evidence_alone() {
1774        let root = project();
1775        let kept = kept_evidence(&root, "run_trimmed");
1776
1777        // `--keep N` is the user trimming history, not asking for a reset, and
1778        // a retention pass runs on its own: either taking the evidence would
1779        // undo the keeping within one run.
1780        clean_storage(
1781            &root,
1782            CleanupOptions {
1783                keep: 20,
1784                dry_run: false,
1785            },
1786            "now",
1787        )
1788        .unwrap();
1789        let retention = cleanup_storage_locked(
1790            &root,
1791            CleanupOptions {
1792                keep: 0,
1793                dry_run: false,
1794            },
1795            false,
1796        )
1797        .unwrap();
1798        sweep_trash(&root).unwrap();
1799
1800        assert!(retention.removed_failed_evidence.is_empty());
1801        assert!(kept.join("main.jsonl").exists());
1802        fs::remove_dir_all(root).unwrap();
1803    }
1804
1805    #[test]
1806    fn cleaning_everything_reclaims_kept_evidence_and_says_which() {
1807        let root = project();
1808        let kept = kept_evidence(&root, "run_cleaned");
1809
1810        let preview = clean_storage(
1811            &root,
1812            CleanupOptions {
1813                keep: 0,
1814                dry_run: true,
1815            },
1816            "now",
1817        )
1818        .unwrap();
1819        assert_eq!(
1820            preview.removed_failed_evidence,
1821            vec!["run_cleaned".to_string()]
1822        );
1823        assert!(kept.join("main.jsonl").exists(), "a preview removed it");
1824
1825        let result = clean_storage(
1826            &root,
1827            CleanupOptions {
1828                keep: 0,
1829                dry_run: false,
1830            },
1831            "now",
1832        )
1833        .unwrap();
1834        sweep_trash(&root).unwrap();
1835
1836        // Removing it is irreversible and it is not a run, so the summary has
1837        // to name it rather than fold it into the run count.
1838        assert_eq!(
1839            result.removed_failed_evidence,
1840            vec!["run_cleaned".to_string()]
1841        );
1842        assert!(!kept.exists());
1843        fs::remove_dir_all(root).unwrap();
1844    }
1845}