1use 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 Cleaning,
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!(
55 formatter,
56 "coverage run {run_id} is active in this project (pid {pid}). Its storage can be cleaned when no run is active."
57 ),
58 Self::Cleaning => {
59 write!(
60 formatter,
61 "this project's Supercov storage is being cleaned. No test ran: start the run again when the cleaning has finished."
62 )
63 }
64 Self::LockUnavailable => {
65 write!(formatter, "could not acquire the Supercov project lock")
66 }
67 Self::PublicationExists(id) => write!(formatter, "coverage run already exists: {id}"),
68 Self::Metadata(error) => write!(formatter, "invalid run metadata: {error}"),
69 Self::EvidenceLength { expected, actual } => write!(
70 formatter,
71 "evidence length changed before publication: expected {expected}, got {actual}"
72 ),
73 Self::EvidenceChanged => write!(formatter, "evidence changed during publication"),
74 }
75 }
76}
77
78impl std::error::Error for LifecycleError {}
79
80fn io_error(path: &Path, source: io::Error) -> LifecycleError {
81 LifecycleError::Io {
82 path: path.to_owned(),
83 source,
84 }
85}
86
87fn checked_id(id: &str) -> Result<(), LifecycleError> {
88 valid_run_id(id)
89 .then_some(())
90 .ok_or_else(|| LifecycleError::InvalidRunId(id.into()))
91}
92
93fn absolute_root(root: &Path) -> Result<PathBuf, LifecycleError> {
94 if root.is_absolute() {
95 Ok(root.to_owned())
96 } else {
97 std::env::current_dir()
98 .map(|cwd| cwd.join(root))
99 .map_err(|source| io_error(root, source))
100 }
101}
102
103fn lexical_descendant(root: &Path, path: &Path) -> bool {
104 let Ok(local) = path.strip_prefix(root) else {
105 return false;
106 };
107 !local.as_os_str().is_empty()
108 && local
109 .components()
110 .all(|component| matches!(component, Component::Normal(_)))
111}
112
113fn reject_linked_ancestors(
114 root: &Path,
115 path: &Path,
116 include_leaf: bool,
117) -> Result<(), LifecycleError> {
118 let local = path
119 .strip_prefix(root)
120 .map_err(|_| LifecycleError::UnsafePath(path.into()))?;
121 let components = local.components().collect::<Vec<_>>();
122 let through = if include_leaf {
123 components.len()
124 } else {
125 components.len().saturating_sub(1)
126 };
127 let mut current = root.to_owned();
128 for component in components.into_iter().take(through) {
129 let Component::Normal(component) = component else {
130 return Err(LifecycleError::UnsafePath(path.into()));
131 };
132 current.push(component);
133 match fs::symlink_metadata(¤t) {
134 Ok(metadata) if metadata.file_type().is_symlink() => {
135 return Err(LifecycleError::UnsafePath(current));
136 }
137 Ok(metadata) if !metadata.file_type().is_dir() => {
138 return Err(LifecycleError::UnsafePath(current));
139 }
140 Ok(_) => {}
141 Err(error) if error.kind() == io::ErrorKind::NotFound => break,
142 Err(source) => return Err(io_error(¤t, source)),
143 }
144 }
145 Ok(())
146}
147
148fn owned_workspace_container(root: &Path) -> bool {
149 let container = crate::workspace::workspace_container(root);
150 crate::workspace::owned_workspace_path(&container)
151}
152
153fn unique_name() -> String {
154 let nanos = SystemTime::now()
155 .duration_since(UNIX_EPOCH)
156 .unwrap_or_default()
157 .as_nanos();
158 format!(
159 "{}-{nanos}-{}",
160 std::process::id(),
161 UNIQUE.fetch_add(1, Ordering::Relaxed)
162 )
163}
164
165pub(crate) fn sync_directory_handle(path: &Path) -> io::Result<()> {
174 #[cfg(unix)]
175 {
176 File::open(path).and_then(|directory| directory.sync_all())
177 }
178 #[cfg(not(unix))]
179 {
180 let _ = path;
181 Ok(())
182 }
183}
184
185pub(crate) fn sync_directory(path: &Path) -> Result<(), LifecycleError> {
186 sync_directory_handle(path).map_err(|source| io_error(path, source))
187}
188
189pub(crate) fn atomic_rename(source: &Path, destination: &Path) -> Result<(), LifecycleError> {
190 let source_parent = source
191 .parent()
192 .ok_or_else(|| LifecycleError::UnsafePath(source.into()))?;
193 let destination_parent = destination
194 .parent()
195 .ok_or_else(|| LifecycleError::UnsafePath(destination.into()))?;
196 fs::create_dir_all(destination_parent).map_err(|error| io_error(destination_parent, error))?;
197 fs::rename(source, destination).map_err(|error| io_error(destination, error))?;
198 sync_directory(destination_parent)?;
199 if source_parent != destination_parent {
200 sync_directory(source_parent)?;
201 }
202 Ok(())
203}
204
205pub(crate) fn atomic_write(root: &Path, path: &Path, bytes: &[u8]) -> Result<(), LifecycleError> {
206 let parent = path
207 .parent()
208 .ok_or_else(|| LifecycleError::UnsafePath(path.into()))?;
209 reject_linked_ancestors(root, parent, true)?;
210 fs::create_dir_all(parent).map_err(|source| io_error(parent, source))?;
211 for _ in 0..16 {
212 let temporary = parent.join(format!(
213 ".{}.{}.tmp",
214 path.file_name()
215 .and_then(|value| value.to_str())
216 .unwrap_or("state"),
217 unique_name()
218 ));
219 let mut file = match OpenOptions::new()
220 .write(true)
221 .create_new(true)
222 .open(&temporary)
223 {
224 Ok(file) => file,
225 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => continue,
226 Err(source) => return Err(io_error(&temporary, source)),
227 };
228 if let Err(source) = file.write_all(bytes).and_then(|_| file.sync_all()) {
229 let _ = fs::remove_file(&temporary);
230 return Err(io_error(&temporary, source));
231 }
232 drop(file);
233 if let Err(source) = fs::rename(&temporary, path) {
234 let _ = fs::remove_file(&temporary);
235 return Err(io_error(path, source));
236 }
237 sync_directory(parent)?;
238 return Ok(());
239 }
240 Err(LifecycleError::LockUnavailable)
241}
242
243pub fn remove_stored_tree_deferred(
244 project_root: &Path,
245 target: &Path,
246) -> Result<Option<PathBuf>, LifecycleError> {
247 let root = absolute_root(project_root)?;
248 let target = if target.is_absolute() {
249 target.to_owned()
250 } else {
251 root.join(target)
252 };
253 match fs::symlink_metadata(&target) {
254 Ok(_) => {}
255 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
256 Err(source) => return Err(io_error(&target, source)),
257 }
258 let store = root.join(".supercov");
259 let trash = root.join(TRASH);
260 let in_store = lexical_descendant(&store, &target) && !lexical_descendant(&trash, &target);
261 let container = crate::workspace::workspace_container(&root);
262 let in_workspace = owned_workspace_container(&root)
263 && (target == container || lexical_descendant(&container, &target));
264 if !in_store && !in_workspace {
265 return Err(LifecycleError::UnsafePath(target));
266 }
267 reject_linked_ancestors(if in_store { &store } else { &container }, &target, false)?;
268 reject_linked_ancestors(&root, &trash, true)?;
269 fs::create_dir_all(&trash).map_err(|source| io_error(&trash, source))?;
270 let destination = trash.join(unique_name());
271 atomic_rename(&target, &destination)?;
272 Ok(Some(destination))
273}
274
275static BACKGROUND_SWEEP: std::sync::Mutex<Option<std::thread::JoinHandle<()>>> =
276 std::sync::Mutex::new(None);
277
278pub fn sweep_trash_in_background(project_root: &Path) {
291 let root = project_root.to_owned();
292 let sweep = std::thread::spawn(move || {
293 let _ = sweep_trash(&root);
294 });
295 if let Ok(mut running) = BACKGROUND_SWEEP.lock() {
296 *running = Some(sweep);
297 }
298}
299
300pub fn finish_background_sweep(patience: Duration) -> bool {
303 let Some(sweep) = BACKGROUND_SWEEP
304 .lock()
305 .ok()
306 .and_then(|mut running| running.take())
307 else {
308 return true;
309 };
310 let deadline = std::time::Instant::now() + patience;
311 while !sweep.is_finished() {
312 if std::time::Instant::now() >= deadline {
313 return false;
314 }
315 std::thread::sleep(Duration::from_millis(5));
316 }
317 let _ = sweep.join();
318 true
319}
320
321pub fn sweep_trash(project_root: &Path) -> Result<usize, LifecycleError> {
323 let root = absolute_root(project_root)?;
324 let trash = root.join(TRASH);
325 reject_linked_ancestors(&root, &trash, true)?;
326 let entries = match fs::read_dir(&trash) {
327 Ok(entries) => entries,
328 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(0),
329 Err(source) => return Err(io_error(&trash, source)),
330 };
331 let Some(_lock) = TrashLock::acquire(&trash)? else {
332 return Ok(0);
333 };
334 let mut removed = 0;
335 for entry in entries {
336 let entry = entry.map_err(|source| io_error(&trash, source))?;
337 let path = entry.path();
338 if entry.file_name() == ".deleter.lock" {
339 continue;
340 }
341 let gone = |error: &io::Error| error.kind() == io::ErrorKind::NotFound;
344 let metadata = match fs::symlink_metadata(&path) {
345 Ok(metadata) => metadata,
346 Err(error) if gone(&error) => continue,
347 Err(source) => return Err(io_error(&path, source)),
348 };
349 let removal = if metadata.file_type().is_dir() {
350 fs::remove_dir_all(&path)
351 } else {
352 fs::remove_file(&path)
353 };
354 match removal {
355 Ok(()) => removed += 1,
356 Err(error) if gone(&error) => {}
357 Err(source) => return Err(io_error(&path, source)),
358 }
359 }
360 Ok(removed)
361}
362
363struct TrashLock {
364 path: PathBuf,
365}
366
367impl TrashLock {
368 fn acquire(trash: &Path) -> Result<Option<Self>, LifecycleError> {
369 let path = trash.join(".deleter.lock");
370 for _ in 0..2 {
371 match OpenOptions::new().write(true).create_new(true).open(&path) {
372 Ok(mut file) => {
373 write!(file, "{}", std::process::id())
374 .and_then(|_| file.sync_all())
375 .map_err(|source| io_error(&path, source))?;
376 return Ok(Some(Self { path }));
377 }
378 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {
379 let owner = fs::read_to_string(&path)
380 .ok()
381 .and_then(|value| value.parse::<u32>().ok());
382 if owner.is_some_and(process_exists) {
383 return Ok(None);
384 }
385 if owner.is_none() {
386 let age = fs::metadata(&path)
387 .and_then(|metadata| metadata.modified())
388 .ok()
389 .and_then(|modified| SystemTime::now().duration_since(modified).ok())
390 .unwrap_or_default();
391 if age < INCOMPLETE_LOCK_GRACE {
392 return Ok(None);
393 }
394 }
395 fs::remove_file(&path).map_err(|source| io_error(&path, source))?;
396 }
397 Err(source) => return Err(io_error(&path, source)),
398 }
399 }
400 Ok(None)
401 }
402}
403
404impl Drop for TrashLock {
405 fn drop(&mut self) {
406 let _ = fs::remove_file(&self.path);
407 }
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
411#[serde(rename_all = "lowercase")]
412pub enum RunStateStatus {
413 Preparing,
414 Building,
415 Testing,
416 Publishing,
417 Complete,
418 Failed,
419 Interrupted,
420 Abandoned,
421}
422
423impl RunStateStatus {
424 pub fn terminal(self) -> bool {
425 matches!(
426 self,
427 Self::Complete | Self::Failed | Self::Interrupted | Self::Abandoned
428 )
429 }
430}
431
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(rename_all = "camelCase", deny_unknown_fields)]
434pub struct RunState {
435 pub id: String,
436 pub pid: u32,
437 pub root: String,
438 pub workspace: String,
439 pub started_at: String,
440 pub updated_at: String,
441 pub status: RunStateStatus,
442 #[serde(skip_serializing_if = "Option::is_none")]
443 pub signal: Option<String>,
444 #[serde(skip_serializing_if = "Option::is_none")]
445 pub error: Option<String>,
446}
447
448fn state_path(root: &Path, id: &str) -> PathBuf {
449 root.join(".supercov/work").join(id).join("state.json")
450}
451
452pub fn write_run_state(root: &Path, state: &RunState) -> Result<(), LifecycleError> {
453 checked_id(&state.id)?;
454 let mut bytes = serde_json::to_vec_pretty(state).map_err(LifecycleError::Metadata)?;
455 bytes.push(b'\n');
456 atomic_write(root, &state_path(root, &state.id), &bytes)
457}
458
459fn read_state(root: &Path, id: &str) -> Result<Option<RunState>, LifecycleError> {
460 checked_id(id)?;
461 let path = state_path(root, id);
462 let bytes = match fs::read(&path) {
463 Ok(bytes) => bytes,
464 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),
465 Err(source) => return Err(io_error(&path, source)),
466 };
467 serde_json::from_slice(&bytes)
468 .map(Some)
469 .map_err(|error| LifecycleError::InvalidState(error.to_string()))
470}
471
472pub fn update_run_state(
473 root: &Path,
474 id: &str,
475 status: RunStateStatus,
476 updated_at: &str,
477 error: Option<String>,
478) -> Result<RunState, LifecycleError> {
479 let mut state = read_state(root, id)?
480 .ok_or_else(|| LifecycleError::InvalidState(format!("state is missing for {id}")))?;
481 state.status = status;
482 state.updated_at = updated_at.into();
483 state.error = error;
484 write_run_state(root, &state)?;
485 Ok(state)
486}
487
488pub fn interrupt_run_state(
489 root: &Path,
490 id: &str,
491 updated_at: &str,
492 signal: &str,
493) -> Result<RunState, LifecycleError> {
494 let mut state = read_state(root, id)?
495 .ok_or_else(|| LifecycleError::InvalidState(format!("state is missing for {id}")))?;
496 state.status = RunStateStatus::Interrupted;
497 state.updated_at = updated_at.into();
498 state.signal = Some(signal.into());
499 state.error = Some(format!("Interrupted by {signal}"));
500 write_run_state(root, &state)?;
501 Ok(state)
502}
503
504#[cfg(unix)]
505fn process_exists(pid: u32) -> bool {
506 if pid == 0 || pid > libc::pid_t::MAX as u32 {
507 return false;
508 }
509 let result = unsafe { libc::kill(pid as libc::pid_t, 0) };
511 result == 0 || io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
512}
513
514#[cfg(windows)]
515fn process_exists(pid: u32) -> bool {
516 use windows_sys::Win32::Foundation::{
517 CloseHandle, ERROR_ACCESS_DENIED, GetLastError, STILL_ACTIVE,
518 };
519 use windows_sys::Win32::System::Threading::{
520 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
521 };
522 if pid == 0 {
523 return false;
524 }
525 let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
528 if handle.is_null() {
529 return unsafe { GetLastError() } == ERROR_ACCESS_DENIED;
531 }
532 let mut code = 0u32;
533 let read = unsafe { GetExitCodeProcess(handle, &mut code) };
535 unsafe { CloseHandle(handle) };
537 read != 0 && code == STILL_ACTIVE as u32
538}
539
540#[cfg(not(any(unix, windows)))]
541fn process_exists(pid: u32) -> bool {
542 pid == std::process::id()
543}
544
545#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
546#[serde(rename_all = "camelCase", deny_unknown_fields)]
547struct LockOwner {
548 run_id: String,
549 pid: u32,
550 started_at: String,
551}
552
553const MOST_COPIES: usize = 64;
557
558const IDLE_COPY_KEPT: Duration = Duration::from_secs(24 * 60 * 60);
562
563pub struct ProjectLock {
573 root: PathBuf,
574 owner: LockOwner,
575 copy: usize,
576 held: Vec<Held>,
578 released: bool,
579}
580
581fn copy_lock_name(copy: usize) -> String {
584 if copy == 1 {
585 "active".into()
586 } else {
587 format!("active-{copy}")
588 }
589}
590
591fn read_owner(path: &Path) -> Option<LockOwner> {
592 serde_json::from_slice(&fs::read(path).ok()?).ok()
593}
594
595struct Held(File);
602
603impl Drop for Held {
604 fn drop(&mut self) {
605 let _ = self.0.unlock();
606 }
607}
608
609fn take_lock(
614 path: &Path,
615 shared: bool,
616 alive: impl Fn() -> bool,
617) -> Result<Option<Held>, LifecycleError> {
618 let file = OpenOptions::new()
619 .read(true)
620 .write(true)
621 .create(true)
622 .truncate(false)
623 .open(path)
624 .map_err(|source| io_error(path, source))?;
625 let taken = if shared {
626 file.try_lock_shared()
627 } else {
628 file.try_lock()
629 };
630 match taken {
631 Ok(()) => Ok(Some(Held(file))),
632 Err(fs::TryLockError::WouldBlock) => Ok(None),
633 Err(fs::TryLockError::Error(_)) => Ok((!alive()).then_some(Held(file))),
634 }
635}
636
637fn live_owner(locks: &Path, copy: usize) -> Option<LockOwner> {
639 read_owner(&locks.join(format!("{}.json", copy_lock_name(copy))))
640 .filter(|owner| owner.pid != std::process::id() && process_exists(owner.pid))
641}
642
643impl ProjectLock {
644 pub fn acquire(root: &Path, run_id: &str, started_at: &str) -> Result<Self, LifecycleError> {
646 Self::take(root, run_id, started_at, false)
647 }
648
649 pub fn acquire_alone(
651 root: &Path,
652 run_id: &str,
653 started_at: &str,
654 ) -> Result<Self, LifecycleError> {
655 Self::take(root, run_id, started_at, true)
656 }
657
658 fn take(
659 root: &Path,
660 run_id: &str,
661 started_at: &str,
662 alone: bool,
663 ) -> Result<Self, LifecycleError> {
664 checked_id(run_id)?;
665 let locks = root.join(".supercov/locks");
666 reject_linked_ancestors(root, &locks, true)?;
667 fs::create_dir_all(&locks).map_err(|source| io_error(&locks, source))?;
668 let ignore = root.join(".supercov/.gitignore");
672 match OpenOptions::new()
673 .write(true)
674 .create_new(true)
675 .open(&ignore)
676 {
677 Ok(mut file) => file
678 .write_all(b"*\n")
679 .map_err(|source| io_error(&ignore, source))?,
680 Err(error) if error.kind() == io::ErrorKind::AlreadyExists => {}
681 Err(source) => return Err(io_error(&ignore, source)),
682 }
683 let owner = LockOwner {
684 run_id: run_id.into(),
685 pid: std::process::id(),
686 started_at: started_at.into(),
687 };
688 let active = || (1..=MOST_COPIES).find_map(|copy| live_owner(&locks, copy));
689 let store = take_lock(&locks.join("store.lock"), !alone, || {
690 alone && active().is_some()
691 })?;
692 let Some(store) = store else {
693 let holder = || {
696 (1..=MOST_COPIES).find_map(|copy| {
697 read_owner(&locks.join(format!("{}.json", copy_lock_name(copy))))
698 .filter(|owner| process_exists(owner.pid))
699 })
700 };
701 return Err(if alone {
702 holder().map_or(LifecycleError::LockUnavailable, |owner| {
703 LifecycleError::ActiveRun {
704 run_id: owner.run_id,
705 pid: owner.pid,
706 }
707 })
708 } else {
709 LifecycleError::Cleaning
710 });
711 };
712 if alone && let Some(owner) = active() {
715 return Err(LifecycleError::ActiveRun {
716 run_id: owner.run_id,
717 pid: owner.pid,
718 });
719 }
720 for copy in 1..=MOST_COPIES {
721 let name = copy_lock_name(copy);
722 let Some(lock) = take_lock(&locks.join(format!("{name}.lock")), false, || {
723 live_owner(&locks, copy).is_some()
724 })?
725 else {
726 continue;
727 };
728 if live_owner(&locks, copy).is_some() {
729 continue;
730 }
731 let path = locks.join(format!("{name}.json"));
732 let mut payload =
733 serde_json::to_vec_pretty(&owner).map_err(LifecycleError::Metadata)?;
734 payload.push(b'\n');
735 fs::write(&path, payload).map_err(|source| io_error(&path, source))?;
736 return Ok(Self {
737 root: root.to_owned(),
738 owner,
739 copy,
740 held: vec![store, lock],
741 released: false,
742 });
743 }
744 Err(LifecycleError::LockUnavailable)
745 }
746
747 pub fn copy(&self) -> usize {
749 self.copy
750 }
751
752 pub fn release(&mut self) -> Result<(), LifecycleError> {
753 if self.released {
754 return Ok(());
755 }
756 self.released = true;
757 let path = self
758 .root
759 .join(".supercov/locks")
760 .join(format!("{}.json", copy_lock_name(self.copy)));
761 if read_owner(&path).is_some_and(|owner| owner == self.owner) {
762 fs::remove_file(&path).map_err(|source| io_error(&path, source))?;
763 }
764 let _ = self
766 .held
767 .last()
768 .map(|lock| lock.0.set_modified(SystemTime::now()));
769 self.held.clear();
770 Ok(())
771 }
772
773 pub(crate) fn protects(&self, root: &Path) -> bool {
774 !self.released && self.root == root
775 }
776}
777
778impl Drop for ProjectLock {
779 fn drop(&mut self) {
780 let _ = self.release();
781 }
782}
783
784fn copy_regular_file(source: &Path, destination: &Path) -> Result<u64, LifecycleError> {
785 let metadata = fs::symlink_metadata(source).map_err(|error| io_error(source, error))?;
786 if !metadata.file_type().is_file() {
787 return Err(LifecycleError::UnsafePath(source.into()));
788 }
789 if reflink_copy::reflink(source, destination).is_ok() {
793 File::open(destination)
794 .and_then(|file| file.sync_all())
795 .map_err(|error| io_error(destination, error))?;
796 return fs::symlink_metadata(destination)
797 .map(|metadata| metadata.len())
798 .map_err(|error| io_error(destination, error));
799 }
800 let mut input = File::open(source).map_err(|error| io_error(source, error))?;
801 let mut output = OpenOptions::new()
802 .write(true)
803 .create_new(true)
804 .open(destination)
805 .map_err(|error| io_error(destination, error))?;
806 let copied = io::copy(&mut input, &mut output).map_err(|error| io_error(destination, error))?;
807 output
808 .sync_all()
809 .map_err(|error| io_error(destination, error))?;
810 Ok(copied)
811}
812
813fn file_sha256(path: &Path) -> Result<[u8; 32], LifecycleError> {
814 let metadata = fs::symlink_metadata(path).map_err(|source| io_error(path, source))?;
815 if !metadata.file_type().is_file() {
816 return Err(LifecycleError::UnsafePath(path.into()));
817 }
818 let mut file = File::open(path).map_err(|source| io_error(path, source))?;
819 let mut hash = Sha256::new();
820 let mut buffer = [0_u8; 128 * 1024];
821 loop {
822 let read = file
823 .read(&mut buffer)
824 .map_err(|source| io_error(path, source))?;
825 if read == 0 {
826 break;
827 }
828 hash.update(&buffer[..read]);
829 }
830 Ok(hash.finalize().into())
831}
832
833fn hex_digest(digest: &[u8; 32]) -> String {
834 use std::fmt::Write as _;
835 digest
836 .iter()
837 .fold(String::with_capacity(64), |mut text, byte| {
838 let _ = write!(text, "{byte:02x}");
839 text
840 })
841}
842
843pub fn publish_run(
846 root: &Path,
847 metadata: &RunMetadata,
848 evidence_source: &Path,
849) -> Result<PathBuf, LifecycleError> {
850 publish_run_with_fault(root, metadata, evidence_source, Archived::default(), None)
851}
852
853#[derive(Default)]
858pub struct Archived {
859 pub report: Option<crate::coverage_report::CoverageReport>,
860 pub inputs: Option<crate::source_manifest::InputManifest>,
861}
862
863pub fn publish_archived_run(
865 root: &Path,
866 metadata: &RunMetadata,
867 evidence_source: &Path,
868 archived: Archived,
869) -> Result<PathBuf, LifecycleError> {
870 publish_run_with_fault(root, metadata, evidence_source, archived, None)
871}
872
873#[derive(Debug, Clone, Copy, PartialEq, Eq)]
874pub(crate) enum RunPublicationFault {
875 FinalRename,
876 QueryIndexWrite,
878}
879
880pub(crate) fn publish_run_with_fault(
881 root: &Path,
882 metadata: &RunMetadata,
883 evidence_source: &Path,
884 archived: Archived,
885 fault: Option<RunPublicationFault>,
886) -> Result<PathBuf, LifecycleError> {
887 checked_id(&metadata.id)?;
888 let destination = root.join(".supercov/runs").join(&metadata.id);
889 reject_linked_ancestors(root, &destination, false)?;
890 if fs::symlink_metadata(&destination).is_ok() {
891 return Err(LifecycleError::PublicationExists(metadata.id.clone()));
892 }
893 let staging = root
894 .join(".supercov/work")
895 .join(&metadata.id)
896 .join("run-publication");
897 reject_linked_ancestors(root, &staging, true)?;
898 if fs::symlink_metadata(&staging).is_ok() {
899 remove_stored_tree_deferred(root, &staging)?;
900 }
901 let evidence_sha256 = file_sha256(evidence_source)?;
902 fs::create_dir_all(&staging).map_err(|source| io_error(&staging, source))?;
903 let copied = copy_regular_file(evidence_source, &staging.join("evidence.raw.gz"))?;
904 if copied != metadata.raw_evidence.compressed_bytes {
905 remove_stored_tree_deferred(root, &staging)?;
906 return Err(LifecycleError::EvidenceLength {
907 expected: metadata.raw_evidence.compressed_bytes,
908 actual: copied,
909 });
910 }
911 if file_sha256(&staging.join("evidence.raw.gz"))? != evidence_sha256 {
914 remove_stored_tree_deferred(root, &staging)?;
915 return Err(LifecycleError::EvidenceChanged);
916 }
917 let mut json = serde_json::to_vec_pretty(metadata).map_err(LifecycleError::Metadata)?;
918 json.push(b'\n');
919 atomic_write(root, &staging.join("run.json"), &json)?;
920 let staged = crate::run_store::StoredRun {
928 id: metadata.id.clone(),
929 directory: staging.clone(),
930 evidence_path: staging.join("evidence.raw.gz"),
931 metadata_path: staging.join("run.json"),
932 query_index_path: staging.join(crate::run_store::RUST_QUERY_INDEX_FILE),
933 metadata: metadata.clone(),
934 };
935 let analysed = if metadata.merged == Some(true) {
936 None
937 } else if archived.report.is_some() {
938 archived.report
939 } else {
940 crate::run_store::analyze_stored_run(&staged).ok()
941 };
942 let archived_inputs = match archived
943 .inputs
944 .map(|manifest| {
945 crate::source_manifest::archived_manifest(manifest, hex_digest(&evidence_sha256))
946 })
947 .transpose()
948 {
949 Ok(inputs) => inputs,
950 Err(reason) => {
951 let _ = remove_stored_tree_deferred(root, &staging);
952 return Err(LifecycleError::InvalidState(format!(
953 "source manifest publication: {reason}"
954 )));
955 }
956 };
957 let prepared = std::thread::scope(|scope| {
960 let index = analysed.as_ref().map(|report| {
961 scope.spawn(|| {
962 if fault == Some(RunPublicationFault::QueryIndexWrite)
965 || crate::run_store::write_query_index_from(&staged, report).is_err()
966 {
967 let _ = fs::remove_file(&staged.query_index_path);
968 }
969 if crate::run_store::write_statement_spans(&staged, report).is_err() {
972 let _ = fs::remove_file(
973 staged
974 .directory
975 .join(crate::run_store::STATEMENT_SPANS_FILE),
976 );
977 }
978 if crate::run_store::write_assessment_input(&staged, report).is_err() {
979 let _ = fs::remove_file(
980 staged
981 .directory
982 .join(crate::run_store::ASSESSMENT_INPUT_FILE),
983 );
984 }
985 })
986 });
987 let prepared = crate::source_manifest::prepare_publication_with(
988 root,
989 &staging,
990 metadata,
991 analysed.as_ref(),
992 archived_inputs,
993 );
994 if let Some(index) = index {
995 index
996 .join()
997 .unwrap_or_else(|panic| std::panic::resume_unwind(panic));
998 }
999 prepared
1000 });
1001 if let Some(report) = analysed {
1005 std::thread::spawn(move || drop(report));
1006 }
1007 if let Err(reason) = prepared {
1008 let _ = remove_stored_tree_deferred(root, &staging);
1009 return Err(LifecycleError::InvalidState(format!(
1010 "source manifest publication: {reason}"
1011 )));
1012 }
1013 sync_directory(&staging)?;
1014 let runs = destination.parent().expect("runs parent");
1015 fs::create_dir_all(runs).map_err(|source| io_error(runs, source))?;
1016 if fault == Some(RunPublicationFault::FinalRename) {
1017 let error = io_error(
1018 &destination,
1019 io::Error::new(
1020 io::ErrorKind::PermissionDenied,
1021 "injected final run publication rename failure",
1022 ),
1023 );
1024 let _ = remove_stored_tree_deferred(root, &staging);
1025 return Err(error);
1026 }
1027 fs::rename(&staging, &destination).map_err(|source| io_error(&destination, source))?;
1028 sync_directory(runs)?;
1029 Ok(destination)
1030}
1031
1032fn published_started_at(root: &Path, id: &str) -> String {
1036 let directory = root.join(".supercov/runs").join(id);
1037 fs::read(directory.join("run.json"))
1038 .ok()
1039 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok())
1040 .as_ref()
1041 .and_then(|value| value.get("startedAt"))
1042 .and_then(|value| value.as_str())
1043 .unwrap_or_default()
1044 .to_owned()
1045}
1046
1047fn published_run(root: &Path, id: &str) -> bool {
1048 let directory = root.join(".supercov/runs").join(id);
1049 let metadata = fs::read(directory.join("run.json"))
1050 .ok()
1051 .and_then(|bytes| serde_json::from_slice::<serde_json::Value>(&bytes).ok());
1052 metadata
1053 .as_ref()
1054 .and_then(|value| value.get("id"))
1055 .and_then(|value| value.as_str())
1056 == Some(id)
1057 && fs::symlink_metadata(directory.join("evidence.raw.gz"))
1058 .is_ok_and(|metadata| metadata.file_type().is_file())
1059}
1060
1061pub fn finalize_published_run(root: &Path, id: &str) -> Result<bool, LifecycleError> {
1062 checked_id(id)?;
1063 if !published_run(root, id) {
1064 return Ok(false);
1065 }
1066 remove_stored_tree_deferred(root, &root.join(".supercov/evidence").join(id))?;
1067 remove_stored_tree_deferred(root, &root.join(".supercov/work").join(id))?;
1068 Ok(true)
1069}
1070
1071fn child_directories(path: &Path) -> Result<Vec<String>, LifecycleError> {
1072 let root = path
1073 .ancestors()
1074 .find(|ancestor| ancestor.file_name().is_some_and(|name| name == ".supercov"))
1075 .and_then(Path::parent)
1076 .unwrap_or(path);
1077 reject_linked_ancestors(root, path, true)?;
1078 let entries = match fs::read_dir(path) {
1079 Ok(entries) => entries,
1080 Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
1081 Err(source) => return Err(io_error(path, source)),
1082 };
1083 let mut names = Vec::new();
1084 for entry in entries {
1085 let entry = entry.map_err(|source| io_error(path, source))?;
1086 let file_type = entry
1087 .file_type()
1088 .map_err(|source| io_error(&entry.path(), source))?;
1089 if file_type.is_symlink() {
1090 return Err(LifecycleError::UnsafePath(entry.path()));
1091 }
1092 if !file_type.is_dir() {
1093 continue;
1094 }
1095 let name = entry
1096 .file_name()
1097 .into_string()
1098 .map_err(|_| LifecycleError::UnsafePath(entry.path()))?;
1099 checked_id(&name)?;
1100 names.push(name);
1101 }
1102 names.sort();
1103 Ok(names)
1104}
1105
1106const FAILED_EVIDENCE: &str = ".supercov/failed-evidence";
1108
1109pub fn keep_failed_evidence(root: &Path, evidence: &Path, id: &str) -> Option<PathBuf> {
1122 if !evidence.is_dir() {
1123 return None;
1124 }
1125 let kept = root.join(FAILED_EVIDENCE).join(id);
1126 fs::create_dir_all(&kept).ok()?;
1127 let mut files = 0;
1128 if copy_evidence(evidence, &kept, &mut files).is_err() || files == 0 {
1129 let _ = fs::remove_dir_all(&kept);
1132 return None;
1133 }
1134 Some(kept)
1135}
1136
1137pub fn note_kept_evidence(root: &Path, evidence: &Path, id: &str, error: String) -> String {
1143 let Some(kept) = keep_failed_evidence(root, evidence, id) else {
1144 return error;
1145 };
1146 format!(
1147 "{error}\n[supercov] the tests were measured and the run could not be published; \
1148their evidence is kept at {} -- this is a Supercov bug, and that directory is what diagnoses it",
1149 kept.display()
1150 )
1151}
1152
1153fn copy_evidence(source: &Path, destination: &Path, files: &mut usize) -> std::io::Result<()> {
1154 for entry in fs::read_dir(source)? {
1155 let entry = entry?;
1156 let target = destination.join(entry.file_name());
1157 if entry.file_type()?.is_dir() {
1158 fs::create_dir_all(&target)?;
1159 copy_evidence(&entry.path(), &target, files)?;
1160 } else {
1161 fs::copy(entry.path(), &target)?;
1162 *files += 1;
1163 }
1164 }
1165 Ok(())
1166}
1167
1168pub fn recover_abandoned_runs(
1175 root: &Path,
1176 updated_at: &str,
1177) -> Result<Vec<String>, LifecycleError> {
1178 let locks = root.join(".supercov/locks");
1179 fs::create_dir_all(&locks).map_err(|source| io_error(&locks, source))?;
1180 let Some(_recovering) = take_lock(&locks.join("recover.lock"), false, || false)? else {
1181 return Ok(Vec::new());
1182 };
1183 remove_idle_copies(root, &locks)?;
1184 let mut recovered = Vec::new();
1185 for id in child_directories(&root.join(".supercov/work"))? {
1186 let Some(state) = read_state(root, &id)? else {
1187 continue;
1188 };
1189 if state.status.terminal() {
1190 finalize_published_run(root, &id)?;
1191 continue;
1192 }
1193 if process_exists(state.pid) {
1194 continue;
1195 }
1196 let workspace_name = root.file_name().unwrap_or_default();
1197 remove_stored_tree_deferred(
1198 root,
1199 &root.join(".supercov/work").join(&id).join(workspace_name),
1200 )?;
1201 remove_stored_tree_deferred(
1202 root,
1203 &root
1204 .join(".supercov/work")
1205 .join(&id)
1206 .join("run-publication"),
1207 )?;
1208 if !finalize_published_run(root, &id)? {
1209 remove_stored_tree_deferred(root, &root.join(".supercov/evidence").join(&id))?;
1210 update_run_state(
1211 root,
1212 &id,
1213 RunStateStatus::Abandoned,
1214 updated_at,
1215 Some(format!(
1216 "Recovered after process {} exited without cleanup",
1217 state.pid
1218 )),
1219 )?;
1220 remove_stored_tree_deferred(root, &root.join(".supercov/work").join(&id))?;
1221 }
1222 recovered.push(id);
1223 }
1224 recovered.sort();
1225 Ok(recovered)
1226}
1227
1228fn remove_idle_copies(root: &Path, locks: &Path) -> Result<(), LifecycleError> {
1231 let container = crate::workspace::workspace_container(root);
1232 for copy in 2..=MOST_COPIES {
1233 let lock_path = locks.join(format!("{}.lock", copy_lock_name(copy)));
1234 let Ok(metadata) = fs::metadata(&lock_path) else {
1235 continue;
1236 };
1237 let idle = metadata
1238 .modified()
1239 .ok()
1240 .and_then(|used| SystemTime::now().duration_since(used).ok())
1241 .is_some_and(|idle| idle >= IDLE_COPY_KEPT);
1242 if !idle {
1243 continue;
1244 }
1245 let Some(_held) = take_lock(&lock_path, false, || live_owner(locks, copy).is_some())?
1246 else {
1247 continue;
1248 };
1249 for directory in crate::workspace::copy_directories(&container, copy) {
1250 if fs::symlink_metadata(&directory).is_ok() {
1251 remove_stored_tree_deferred(root, &directory)?;
1252 }
1253 }
1254 }
1255 Ok(())
1256}
1257
1258#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1259pub struct CleanupOptions {
1260 pub keep: usize,
1261 pub dry_run: bool,
1262}
1263
1264#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
1265#[serde(rename_all = "camelCase")]
1266pub struct CleanupResult {
1267 pub removed_runs: Vec<String>,
1268 pub removed_workspaces: Vec<String>,
1269 pub removed_evidence: Vec<String>,
1270 pub removed_failed_evidence: Vec<String>,
1275 pub removed_build_cache: bool,
1276}
1277
1278pub fn cleanup_storage_locked(
1279 root: &Path,
1280 options: CleanupOptions,
1281 remove_build_cache: bool,
1282) -> Result<CleanupResult, LifecycleError> {
1283 let runs_root = root.join(".supercov/runs");
1284 let work_root = root.join(".supercov/work");
1285 let evidence_root = root.join(".supercov/evidence");
1286 let published = child_directories(&runs_root)?;
1287 let work = child_directories(&work_root)?;
1288 let evidence = child_directories(&evidence_root)?;
1289 let mut ids = published
1290 .iter()
1291 .chain(&work)
1292 .chain(&evidence)
1293 .cloned()
1294 .collect::<BTreeSet<_>>()
1295 .into_iter()
1296 .collect::<Vec<_>>();
1297 ids.sort_by(|left, right| right.cmp(left));
1298 let mut active = BTreeSet::new();
1299 for id in &ids {
1300 if read_state(root, id)?.is_some_and(|state| !state.status.terminal()) {
1301 active.insert(id.clone());
1302 }
1303 }
1304 let mut retention_order = published
1305 .iter()
1306 .filter(|id| !active.contains(*id))
1307 .map(|id| (published_started_at(root, id), id.clone()))
1308 .collect::<Vec<_>>();
1309 retention_order.sort_by(|left, right| right.0.cmp(&left.0).then_with(|| right.1.cmp(&left.1)));
1310 let retained = retention_order
1311 .into_iter()
1312 .take(options.keep)
1313 .map(|(_, id)| id)
1314 .collect::<BTreeSet<_>>();
1315 let mut result = CleanupResult {
1316 removed_runs: Vec::new(),
1317 removed_workspaces: Vec::new(),
1318 removed_evidence: Vec::new(),
1319 removed_failed_evidence: Vec::new(),
1320 removed_build_cache: false,
1321 };
1322 for id in ids {
1323 if active.contains(&id) {
1324 continue;
1325 }
1326 let has_run = published.contains(&id);
1327 let remove_history = has_run && !retained.contains(&id);
1328 if work.contains(&id) && read_state(root, &id)?.is_none_or(|state| state.status.terminal())
1329 {
1330 result.removed_workspaces.push(id.clone());
1331 if !options.dry_run {
1332 remove_stored_tree_deferred(root, &work_root.join(&id))?;
1333 }
1334 }
1335 if evidence.contains(&id) && (!has_run || remove_history) {
1336 result.removed_evidence.push(id.clone());
1337 if !options.dry_run {
1338 remove_stored_tree_deferred(root, &evidence_root.join(&id))?;
1339 }
1340 }
1341 if remove_history {
1342 result.removed_runs.push(id.clone());
1343 if !options.dry_run {
1344 remove_stored_tree_deferred(root, &runs_root.join(&id))?;
1345 }
1346 }
1347 }
1348 if remove_build_cache && options.keep == 0 && active.is_empty() {
1353 let kept_root = root.join(FAILED_EVIDENCE);
1354 for id in child_directories(&kept_root)? {
1355 result.removed_failed_evidence.push(id.clone());
1356 if !options.dry_run {
1357 remove_stored_tree_deferred(root, &kept_root.join(&id))?;
1358 }
1359 }
1360 }
1361 let container = crate::workspace::workspace_container(root);
1362 let legacy = [root.join(".supercov/.cache"), root.join(".supercov/cache")];
1363 let mut caches = Vec::new();
1364 if remove_build_cache && active.is_empty() {
1365 if owned_workspace_container(root) {
1366 caches.push(container);
1367 }
1368 caches.extend(
1369 legacy
1370 .into_iter()
1371 .filter(|path| fs::symlink_metadata(path).is_ok()),
1372 );
1373 }
1374 result.removed_build_cache = !caches.is_empty();
1375 if !options.dry_run {
1376 for cache in caches {
1377 remove_stored_tree_deferred(root, &cache)?;
1378 }
1379 }
1380 Ok(result)
1381}
1382
1383fn cleanup_storage(
1384 root: &Path,
1385 options: CleanupOptions,
1386 remove_build_cache: bool,
1387 updated_at: &str,
1388) -> Result<CleanupResult, LifecycleError> {
1389 let operation = if remove_build_cache {
1390 "clean"
1391 } else {
1392 "retention"
1393 };
1394 let lock_id = format!("{operation}-{}-{}", std::process::id(), unique_name());
1395 let mut lock = ProjectLock::acquire_alone(root, &lock_id, updated_at)?;
1396 recover_abandoned_runs(root, updated_at)?;
1397 let result = cleanup_storage_locked(root, options, remove_build_cache);
1398 lock.release()?;
1399 result
1400}
1401
1402pub fn clean_storage(
1403 root: &Path,
1404 options: CleanupOptions,
1405 updated_at: &str,
1406) -> Result<CleanupResult, LifecycleError> {
1407 cleanup_storage(root, options, true, updated_at)
1408}
1409
1410#[cfg(test)]
1411mod tests {
1412 use super::*;
1413 use crate::run_store::{RawEvidenceMetadata, RunFingerprint, RunIntegrity};
1414
1415 fn project() -> PathBuf {
1416 let root = std::env::temp_dir().join(format!("supercov-lifecycle-{}", unique_name()));
1417 fs::create_dir_all(root.join("src")).unwrap();
1418 fs::write(root.join("src/index.js"), "user source").unwrap();
1419 root
1420 }
1421
1422 #[cfg(unix)]
1423 #[test]
1424 fn removing_a_stored_tree_never_follows_a_link_out_of_it() {
1425 let root = project();
1430 let outside = std::env::temp_dir().join(format!("supercov-outside-{}", unique_name()));
1431 fs::create_dir_all(outside.join("tsx/dist")).unwrap();
1432 fs::write(outside.join("tsx/dist/loader.mjs"), "the dependency").unwrap();
1433 let tree = root.join(".supercov/work/run_links");
1434 fs::create_dir_all(tree.join("mirror")).unwrap();
1435 std::os::unix::fs::symlink(&outside, tree.join("node_modules")).unwrap();
1436 std::os::unix::fs::symlink(outside.join("tsx"), tree.join("mirror/tsx")).unwrap();
1438 std::os::unix::fs::symlink(&outside, root.join(".supercov/work/run_linked_root")).unwrap();
1440 for target in [tree.clone(), root.join(".supercov/work/run_linked_root")] {
1441 remove_stored_tree_deferred(&root, &target)
1442 .unwrap()
1443 .unwrap();
1444 }
1445 assert!(sweep_trash(&root).unwrap() >= 2);
1446 assert!(!tree.exists());
1447 assert_eq!(
1448 fs::read_to_string(outside.join("tsx/dist/loader.mjs")).unwrap(),
1449 "the dependency"
1450 );
1451 fs::remove_dir_all(&outside).unwrap();
1452 fs::remove_dir_all(&root).unwrap();
1453 }
1454
1455 fn kept_evidence(root: &Path, id: &str) -> PathBuf {
1456 let evidence = root.join(".supercov/work").join(id).join("python/evidence");
1457 fs::create_dir_all(&evidence).unwrap();
1458 fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
1459 keep_failed_evidence(root, &evidence, id).expect("the evidence")
1460 }
1461
1462 fn state(root: &Path, id: &str, status: RunStateStatus, pid: u32) -> RunState {
1463 RunState {
1464 id: id.into(),
1465 pid,
1466 root: root.display().to_string(),
1467 workspace: root.join("dist").display().to_string(),
1468 started_at: "start".into(),
1469 updated_at: "update".into(),
1470 status,
1471 signal: None,
1472 error: None,
1473 }
1474 }
1475
1476 fn metadata(id: &str, bytes: u64) -> RunMetadata {
1477 RunMetadata {
1478 id: id.into(),
1479 started_at: "2026-01-01T00:00:00Z".into(),
1480 duration_ms: 1.0,
1481 command: vec!["test".into()],
1482 test_exit_code: Some(0),
1483 integrity: RunIntegrity {
1484 schema_version: 2,
1485 instrumenter_version: "rust".into(),
1486 git: None,
1487 fingerprint: RunFingerprint {
1488 algorithm: "sha256".into(),
1489 source: "0".repeat(64),
1490 tests: "0".repeat(64),
1491 dependencies: "0".repeat(64),
1492 configuration: "0".repeat(64),
1493 instrumenter: "0".repeat(64),
1494 execution: "0".repeat(64),
1495 combined: "0".repeat(64),
1496 source_files: 1,
1497 test_files: 1,
1498 },
1499 stale: None,
1500 stale_reasons: None,
1501 },
1502 raw_evidence: RawEvidenceMetadata {
1503 schema_version: 2,
1504 format: "supercov-evidence-archive".into(),
1505 file: "evidence.raw.gz".into(),
1506 files: 1,
1507 uncompressed_bytes: bytes,
1508 compressed_bytes: bytes,
1509 },
1510 isolated_build: None,
1511 instrumented_build_cache: None,
1512 timings: None,
1513 merged: None,
1514 parents: None,
1515 source_roots: None,
1516 copy: None,
1517 merged_across: None,
1518 }
1519 }
1520
1521 fn evidence(root: &Path) -> (PathBuf, u64) {
1522 use crate::evidence_archive::{EvidenceArchiveEntry, write_archive};
1523 let mut entries = ["manifest.json", "frontend.json", "coverage-model.json"]
1524 .into_iter()
1525 .map(|path| EvidenceArchiveEntry {
1526 path: path.into(),
1527 contents: b"{}".to_vec(),
1528 })
1529 .collect::<Vec<_>>();
1530 let inputs =
1531 crate::source_capture::capture(root, "javascript", [PathBuf::from("src/index.js")])
1532 .unwrap();
1533 entries = crate::source_capture::append(entries, &inputs).unwrap();
1534 let path = root.join("evidence.gz");
1535 let metadata = write_archive(entries, &path).unwrap();
1536 (path, metadata.compressed_bytes)
1537 }
1538
1539 #[test]
1540 fn defers_only_owned_storage_and_sweeps_without_touching_source() {
1541 let root = project();
1542 let owned = root.join(".supercov/evidence/run");
1543 fs::create_dir_all(&owned).unwrap();
1544 fs::write(owned.join("hit"), "hit").unwrap();
1545 let trash = remove_stored_tree_deferred(&root, &owned).unwrap().unwrap();
1546 assert!(!owned.exists());
1547 assert!(trash.exists());
1548 assert!(matches!(
1549 remove_stored_tree_deferred(&root, &root.join("src")),
1550 Err(LifecycleError::UnsafePath(_))
1551 ));
1552 assert_eq!(sweep_trash(&root).unwrap(), 1);
1553 assert!(root.join("src/index.js").exists());
1554 fs::remove_dir_all(root).unwrap();
1555 }
1556
1557 #[cfg(unix)]
1558 #[test]
1559 fn refuses_linked_storage_ancestors_instead_of_renaming_external_data() {
1560 use std::os::unix::fs::symlink;
1561
1562 let root = project();
1563 let outside = project();
1564 fs::create_dir_all(root.join(".supercov")).unwrap();
1565 fs::create_dir_all(outside.join("run")).unwrap();
1566 fs::write(outside.join("run/user.txt"), "user").unwrap();
1567 symlink(&outside, root.join(".supercov/evidence")).unwrap();
1568 assert!(matches!(
1569 remove_stored_tree_deferred(&root, &root.join(".supercov/evidence/run")),
1570 Err(LifecycleError::UnsafePath(_))
1571 ));
1572 assert_eq!(
1573 fs::read_to_string(outside.join("run/user.txt")).unwrap(),
1574 "user"
1575 );
1576 fs::remove_dir_all(root).unwrap();
1577 fs::remove_dir_all(outside).unwrap();
1578 }
1579
1580 fn analysable_evidence(root: &Path, id: &str) -> (PathBuf, RunMetadata) {
1583 let source = project();
1584 let directory = crate::run_store::create_analyzable_test_run(&source, "source");
1585 let evidence = root.join(format!("{id}.evidence.gz"));
1586 fs::copy(directory.join("evidence.raw.gz"), &evidence).unwrap();
1587 let mut metadata: RunMetadata =
1588 serde_json::from_slice(&fs::read(directory.join("run.json")).unwrap()).unwrap();
1589 metadata.id = id.into();
1590 fs::remove_dir_all(source).unwrap();
1591 (evidence, metadata)
1592 }
1593
1594 fn stored(root: &Path, id: &str) -> crate::run_store::StoredRun {
1596 let directory = root.join(".supercov/runs").join(id);
1597 crate::run_store::StoredRun {
1598 id: id.into(),
1599 evidence_path: directory.join("evidence.raw.gz"),
1600 metadata_path: directory.join("run.json"),
1601 query_index_path: directory.join(crate::run_store::RUST_QUERY_INDEX_FILE),
1602 metadata: serde_json::from_slice(&fs::read(directory.join("run.json")).unwrap())
1603 .unwrap(),
1604 directory,
1605 }
1606 }
1607
1608 #[test]
1609 fn publication_writes_the_query_index_a_first_query_would_have_built() {
1610 let root = project();
1614 let id = "2026-01-01T00-00-00-100Z";
1615 let (evidence, metadata) = analysable_evidence(&root, id);
1616 let published = publish_run(&root, &metadata, &evidence).unwrap();
1617 let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1618 assert!(index.is_file(), "publication wrote the index");
1619 let run = stored(&root, id);
1620 assert!(
1621 crate::run_store::open_existing_query_index(&run)
1622 .unwrap()
1623 .is_some(),
1624 "and it is valid for the published run"
1625 );
1626 let analysed = crate::source_manifest::coverage(&run).unwrap();
1629 assert_eq!(
1630 crate::run_store::read_statement_spans(&run).expect("publication wrote the spans"),
1631 crate::run_store::statement_spans(&analysed)
1632 );
1633 assert_eq!(
1635 crate::run_store::read_assessment_input(&run).expect("publication wrote the input"),
1636 crate::assertion_coverage::assessment_input(&analysed)
1637 );
1638 let written = fs::read(&index).unwrap();
1639 fs::remove_file(&index).unwrap();
1640 crate::run_store::open_or_rebuild_query_index(&run).unwrap();
1641 assert_eq!(
1642 fs::read(&index).unwrap(),
1643 written,
1644 "a query rebuilds the same bytes"
1645 );
1646 fs::remove_dir_all(root).unwrap();
1647 }
1648
1649 #[test]
1650 fn evidence_that_will_not_analyse_is_published_as_it_was_before() {
1651 let root = project();
1655 let id = "2026-01-01T00-00-00-200Z";
1656 let (evidence, bytes) = evidence(&root);
1657 let published = publish_run(&root, &metadata(id, bytes), &evidence).unwrap();
1658 assert!(published.join("run.json").is_file());
1659 assert!(published.join("source-manifest.cache.json").is_file());
1660 assert!(
1661 !published
1662 .join(crate::run_store::RUST_QUERY_INDEX_FILE)
1663 .exists()
1664 );
1665 assert!(
1666 !published
1667 .join(crate::source_manifest::EXECUTIONS_FILE)
1668 .exists()
1669 );
1670 let run = stored(&root, id);
1671 let Err(query) = crate::run_store::open_or_rebuild_query_index(&run) else {
1672 panic!("the first query cannot analyse it either");
1673 };
1674 let direct = crate::run_store::analyze_stored_run(&run).expect_err("unanalysable");
1675 assert_eq!(
1676 query.to_string(),
1677 direct.to_string(),
1678 "and says why in the same words"
1679 );
1680 fs::remove_dir_all(root).unwrap();
1681 }
1682
1683 #[test]
1684 fn a_merged_run_is_indexed_by_its_first_query() {
1685 let root = project();
1687 let id = "2026-01-01T00-00-00-300Z";
1688 let (evidence, mut metadata) = analysable_evidence(&root, id);
1689 metadata.merged = Some(true);
1690 let published = publish_run(&root, &metadata, &evidence).unwrap();
1691 let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1692 assert!(!index.exists());
1693 crate::run_store::open_or_rebuild_query_index(&stored(&root, id)).unwrap();
1694 assert!(index.is_file());
1695 fs::remove_dir_all(root).unwrap();
1696 }
1697
1698 #[test]
1699 fn an_index_that_could_not_be_written_is_built_by_the_first_query() {
1700 let root = project();
1703 let id = "2026-01-01T00-00-00-400Z";
1704 let (evidence, metadata) = analysable_evidence(&root, id);
1705 let published = publish_run_with_fault(
1706 &root,
1707 &metadata,
1708 &evidence,
1709 Archived::default(),
1710 Some(RunPublicationFault::QueryIndexWrite),
1711 )
1712 .unwrap();
1713 let index = published.join(crate::run_store::RUST_QUERY_INDEX_FILE);
1714 assert!(!index.exists(), "no partial index is left");
1715 assert!(published.join("run.json").is_file());
1716 crate::run_store::open_or_rebuild_query_index(&stored(&root, id)).unwrap();
1717 assert!(index.is_file());
1718 fs::remove_dir_all(root).unwrap();
1719 }
1720
1721 #[test]
1722 fn publishes_both_required_files_with_one_visible_rename() {
1723 let root = project();
1724 let id = "2026-01-01T00-00-00-000Z";
1725 let (evidence, bytes) = evidence(&root);
1726 let published = publish_run(&root, &metadata(id, bytes), &evidence).unwrap();
1727 assert!(published.join("run.json").is_file());
1728 assert_eq!(
1729 fs::read(published.join("evidence.raw.gz")).unwrap(),
1730 fs::read(&evidence).unwrap()
1731 );
1732 assert!(published.join("source-manifest.cache.json").is_file());
1733 assert!(matches!(
1734 publish_run(&root, &metadata(id, bytes), &evidence),
1735 Err(LifecycleError::PublicationExists(_))
1736 ));
1737 fs::remove_dir_all(root).unwrap();
1738 }
1739
1740 #[test]
1741 fn final_rename_failure_exposes_no_run_and_removes_staging() {
1742 let root = project();
1743 let id = "2026-01-01T00-00-00-000Z";
1744 let (evidence, bytes) = evidence(&root);
1745 let error = publish_run_with_fault(
1746 &root,
1747 &metadata(id, bytes),
1748 &evidence,
1749 Archived::default(),
1750 Some(RunPublicationFault::FinalRename),
1751 )
1752 .unwrap_err();
1753 assert!(
1754 error
1755 .to_string()
1756 .contains("injected final run publication rename failure")
1757 );
1758 assert!(!root.join(".supercov/runs").join(id).exists());
1759 assert!(
1760 !root
1761 .join(".supercov/work")
1762 .join(id)
1763 .join("run-publication")
1764 .exists()
1765 );
1766 sweep_trash(&root).unwrap();
1767 fs::remove_dir_all(root).unwrap();
1768 }
1769
1770 #[test]
1771 fn malformed_assertion_inputs_expose_no_partial_run() {
1772 use crate::evidence_archive::{read_archive, write_archive};
1773 let root = project();
1774 let id = "2026-01-01T00-00-00-000Z";
1775 let (evidence, _) = evidence(&root);
1776 let mut entries = read_archive(&evidence).unwrap();
1777 entries
1778 .iter_mut()
1779 .find(|e| e.path == crate::source_capture::ARCHIVE_PATH)
1780 .unwrap()
1781 .contents = b"{broken".to_vec();
1782 let raw = write_archive(entries, &evidence).unwrap();
1783 let error = publish_run(&root, &metadata(id, raw.compressed_bytes), &evidence).unwrap_err();
1784 assert!(error.to_string().contains("source manifest publication"));
1785 assert!(!root.join(".supercov/runs").join(id).exists());
1786 assert!(
1787 !root
1788 .join(".supercov/work")
1789 .join(id)
1790 .join("run-publication")
1791 .exists()
1792 );
1793 fs::remove_dir_all(root).unwrap();
1794 }
1795
1796 #[test]
1797 fn recovers_dead_unpublished_and_fully_published_runs_from_derived_paths() {
1798 let root = project();
1799 let dead = "2026-01-01T00-00-00-000Z";
1800 let published = "2026-01-02T00-00-00-000Z";
1801 for id in [dead, published] {
1802 fs::create_dir_all(
1803 root.join(".supercov/work")
1804 .join(id)
1805 .join(root.file_name().unwrap()),
1806 )
1807 .unwrap();
1808 fs::create_dir_all(root.join(".supercov/evidence").join(id)).unwrap();
1809 write_run_state(&root, &state(&root, id, RunStateStatus::Testing, u32::MAX)).unwrap();
1810 }
1811 let (evidence, bytes) = evidence(&root);
1812 publish_run(&root, &metadata(published, bytes), &evidence).unwrap();
1813 assert_eq!(
1814 recover_abandoned_runs(&root, "recovered").unwrap(),
1815 [dead, published]
1816 );
1817 assert!(!root.join(".supercov/work").join(dead).exists());
1818 assert!(!root.join(".supercov/work").join(published).exists());
1819 assert!(root.join(".supercov/runs").join(published).exists());
1820 assert!(root.join("src/index.js").exists());
1821 sweep_trash(&root).unwrap();
1822 fs::remove_dir_all(root).unwrap();
1823 }
1824
1825 #[test]
1826 fn retention_is_deterministic_dry_run_safe_and_preserves_active_work() {
1827 let root = project();
1828 let ids = [
1829 "2026-01-01T00-00-00-000Z",
1830 "2026-01-02T00-00-00-000Z",
1831 "2026-01-03T00-00-00-000Z",
1832 ];
1833 for id in ids {
1834 fs::create_dir_all(root.join(".supercov/runs").join(id)).unwrap();
1835 write_run_state(
1836 &root,
1837 &state(&root, id, RunStateStatus::Complete, std::process::id()),
1838 )
1839 .unwrap();
1840 }
1841 let active = "2025-12-31T00-00-00-000Z";
1842 write_run_state(
1843 &root,
1844 &state(&root, active, RunStateStatus::Testing, std::process::id()),
1845 )
1846 .unwrap();
1847 let preview = cleanup_storage_locked(
1848 &root,
1849 CleanupOptions {
1850 keep: 1,
1851 dry_run: true,
1852 },
1853 false,
1854 )
1855 .unwrap();
1856 assert_eq!(preview.removed_runs, [ids[1], ids[0]]);
1857 assert!(
1858 ids.iter()
1859 .all(|id| root.join(".supercov/runs").join(id).exists())
1860 );
1861 let result = cleanup_storage_locked(
1862 &root,
1863 CleanupOptions {
1864 keep: 1,
1865 dry_run: false,
1866 },
1867 false,
1868 )
1869 .unwrap();
1870 assert_eq!(result, preview);
1871 assert!(root.join(".supercov/work").join(active).exists());
1872 assert!(root.join(".supercov/runs").join(ids[2]).exists());
1873 sweep_trash(&root).unwrap();
1874 fs::remove_dir_all(root).unwrap();
1875 }
1876
1877 #[test]
1878 fn retention_keeps_the_newest_runs_when_run_ids_disagree_with_recency() {
1879 let root = project();
1880 let (evidence, bytes) = evidence(&root);
1881 for (id, started_at) in [
1884 ("run_ffffffffffffffff", "2026-01-01T00:00:00Z"),
1885 ("run_7777777777777777", "2026-05-01T00:00:00Z"),
1886 ("run_0000000000000001", "2026-09-01T00:00:00Z"),
1887 ] {
1888 let mut run = metadata(id, bytes);
1889 run.started_at = started_at.into();
1890 publish_run(&root, &run, &evidence).unwrap();
1891 }
1892 let result = cleanup_storage_locked(
1893 &root,
1894 CleanupOptions {
1895 keep: 1,
1896 dry_run: false,
1897 },
1898 false,
1899 )
1900 .unwrap();
1901 assert_eq!(
1902 result.removed_runs,
1903 ["run_ffffffffffffffff", "run_7777777777777777"]
1904 );
1905 assert!(
1906 root.join(".supercov/runs")
1907 .join("run_0000000000000001")
1908 .exists()
1909 );
1910 sweep_trash(&root).unwrap();
1911 fs::remove_dir_all(root).unwrap();
1912 }
1913
1914 #[test]
1915 fn direct_runs_initialize_store_ignore_without_overwriting_existing_rules() {
1916 let root = project();
1917 let ignore = root.join(".supercov/.gitignore");
1918 let mut lock = ProjectLock::acquire(&root, "first", "start").unwrap();
1919 assert_eq!(fs::read_to_string(&ignore).unwrap(), "*\n");
1920 lock.release().unwrap();
1921 fs::write(&ignore, "custom\n").unwrap();
1922 let mut lock = ProjectLock::acquire(&root, "second", "start").unwrap();
1923 assert_eq!(fs::read_to_string(&ignore).unwrap(), "custom\n");
1924 lock.release().unwrap();
1925 fs::remove_dir_all(root).unwrap();
1926 }
1927
1928 fn owner_file(root: &Path, copy: usize) -> PathBuf {
1929 root.join(".supercov/locks")
1930 .join(format!("{}.json", copy_lock_name(copy)))
1931 }
1932
1933 #[test]
1934 fn runs_at_once_each_hold_a_copy_and_the_lowest_free_is_taken_next() {
1935 let root = project();
1936 let mut first = ProjectLock::acquire(&root, "first", "start").unwrap();
1937 let mut second = ProjectLock::acquire(&root, "second", "start").unwrap();
1938 let third = ProjectLock::acquire(&root, "third", "start").unwrap();
1939 assert_eq!((first.copy(), second.copy(), third.copy()), (1, 2, 3));
1940 assert_eq!(read_owner(&owner_file(&root, 2)).unwrap().run_id, "second");
1941
1942 second.release().unwrap();
1944 assert!(!owner_file(&root, 2).exists());
1945 let again = ProjectLock::acquire(&root, "fourth", "start").unwrap();
1946 assert_eq!(again.copy(), 2);
1947
1948 drop(third);
1950 first.release().unwrap();
1951 assert_eq!(
1952 ProjectLock::acquire(&root, "fifth", "start")
1953 .unwrap()
1954 .copy(),
1955 1
1956 );
1957 fs::remove_dir_all(root).unwrap();
1958 }
1959
1960 #[test]
1961 fn many_runs_starting_in_the_same_instant_never_share_a_copy() {
1962 let root = project();
1963 let start = std::sync::Arc::new(std::sync::Barrier::new(24));
1964 let holds = (0..24)
1965 .map(|each| {
1966 let root = root.clone();
1967 let start = std::sync::Arc::clone(&start);
1968 std::thread::spawn(move || {
1969 start.wait();
1970 let lock =
1971 ProjectLock::acquire(&root, &format!("run-{each}"), "start").unwrap();
1972 recover_abandoned_runs(&root, "start").unwrap();
1974 lock
1975 })
1976 })
1977 .collect::<Vec<_>>()
1978 .into_iter()
1979 .map(|thread| thread.join().unwrap())
1980 .collect::<Vec<_>>();
1981 let mut copies = holds.iter().map(ProjectLock::copy).collect::<Vec<_>>();
1982 copies.sort_unstable();
1983 assert_eq!(copies, (1..=24).collect::<Vec<_>>());
1984 drop(holds);
1985 fs::remove_dir_all(root).unwrap();
1986 }
1987
1988 #[test]
1989 fn no_run_starts_while_the_store_is_cleaned_and_none_is_cleaned_under() {
1990 let root = project();
1991 let mut cleaning = ProjectLock::acquire_alone(&root, "clean", "start").unwrap();
1992 assert!(matches!(
1993 ProjectLock::acquire(&root, "run", "start"),
1994 Err(LifecycleError::Cleaning)
1995 ));
1996 cleaning.release().unwrap();
1997 let _first = ProjectLock::acquire(&root, "first", "start").unwrap();
1998 let _second = ProjectLock::acquire(&root, "second", "start").unwrap();
1999 match ProjectLock::acquire_alone(&root, "clean", "start") {
2000 Err(LifecycleError::ActiveRun { run_id, pid }) => {
2001 assert_eq!((run_id.as_str(), pid), ("first", std::process::id()));
2002 }
2003 other => panic!("cleaning under two runs: {:?}", other.map(|_| ())),
2004 }
2005 fs::remove_dir_all(root).unwrap();
2006 }
2007
2008 #[cfg(unix)]
2009 #[test]
2010 fn a_run_of_a_release_that_locked_nothing_keeps_its_copy() {
2011 let root = project();
2015 let locks = root.join(".supercov/locks");
2016 fs::create_dir_all(&locks).unwrap();
2017 let theirs = std::os::unix::process::parent_id();
2018 fs::write(
2019 owner_file(&root, 1),
2020 format!(r#"{{"runId":"run_theirs","pid":{theirs},"startedAt":"then"}}"#),
2021 )
2022 .unwrap();
2023 let mut beside = ProjectLock::acquire(&root, "beside", "start").unwrap();
2024 assert_eq!(beside.copy(), 2);
2025 assert!(matches!(
2026 ProjectLock::acquire_alone(&root, "clean", "start"),
2027 Err(LifecycleError::ActiveRun { ref run_id, pid }) if run_id == "run_theirs" && pid == theirs
2028 ));
2029 beside.release().unwrap();
2030
2031 let mut gone = std::process::Command::new("true").spawn().unwrap();
2033 let dead = gone.id();
2034 gone.wait().unwrap();
2035 fs::write(
2036 owner_file(&root, 1),
2037 format!(r#"{{"runId":"run_gone","pid":{dead},"startedAt":"then"}}"#),
2038 )
2039 .unwrap();
2040 assert_eq!(
2041 ProjectLock::acquire(&root, "after", "start")
2042 .unwrap()
2043 .copy(),
2044 1
2045 );
2046 fs::remove_dir_all(root).unwrap();
2047 }
2048
2049 #[test]
2050 fn a_copy_past_the_first_goes_a_day_after_its_last_run() {
2051 let root = project();
2052 let container = root.join(".supercov/workspaces");
2053 for copy in [
2054 "workspace",
2055 "workspace-2",
2056 "workspace-3",
2057 "workspace-4",
2058 "source-2",
2059 ] {
2060 fs::create_dir_all(container.join(copy).join("project")).unwrap();
2061 }
2062 fs::write(
2063 container.join(".supercov-workspace-store"),
2064 b"Supercov instrumented workspace. Safe to delete.\n",
2065 )
2066 .unwrap();
2067 let locks = root.join(".supercov/locks");
2068 fs::create_dir_all(&locks).unwrap();
2069 let long_ago = SystemTime::now() - Duration::from_secs(3 * 24 * 60 * 60);
2070 for (copy, used) in [
2073 (2, long_ago),
2074 (3, SystemTime::now() - Duration::from_secs(3600)),
2075 (4, long_ago),
2076 ] {
2077 let lock = File::create(locks.join(format!("{}.lock", copy_lock_name(copy)))).unwrap();
2078 lock.set_modified(used).unwrap();
2079 }
2080 let held = take_lock(&locks.join("active-4.lock"), false, || false)
2081 .unwrap()
2082 .unwrap();
2083 held.0.set_modified(long_ago).unwrap();
2084
2085 recover_abandoned_runs(&root, "now").unwrap();
2086 let left = |copy: &str| container.join(copy).exists();
2087 assert!(left("workspace"), "the first is never idle");
2088 assert!(!left("workspace-2") && !left("source-2"));
2089 assert!(left("workspace-3"));
2090 assert!(left("workspace-4"), "a copy in use is not removed");
2091 drop(held);
2092 sweep_trash(&root).unwrap();
2093 fs::remove_dir_all(root).unwrap();
2094 }
2095
2096 #[test]
2097 fn cleanup_is_project_locked_and_clean_alone_removes_owned_caches() {
2098 let root = project();
2099 let container = root.join(".supercov/workspaces");
2100 fs::create_dir_all(container.join("workspace/project")).unwrap();
2101 fs::write(
2102 container.join(".supercov-workspace-store"),
2103 b"Supercov instrumented workspace. Safe to delete.\n",
2104 )
2105 .unwrap();
2106 fs::create_dir_all(root.join(".supercov/cache/legacy")).unwrap();
2107 let mut active = ProjectLock::acquire(&root, "active", "start").unwrap();
2108 assert!(matches!(
2109 clean_storage(
2110 &root,
2111 CleanupOptions {
2112 keep: 0,
2113 dry_run: false
2114 },
2115 "now"
2116 ),
2117 Err(LifecycleError::ActiveRun { .. })
2118 ));
2119 assert!(container.exists());
2120 active.release().unwrap();
2121
2122 let cleaned = clean_storage(
2123 &root,
2124 CleanupOptions {
2125 keep: 0,
2126 dry_run: false,
2127 },
2128 "now",
2129 )
2130 .unwrap();
2131 assert!(cleaned.removed_build_cache);
2132 assert!(!container.exists());
2133 assert!(!root.join(".supercov/cache").exists());
2134 sweep_trash(&root).unwrap();
2135 fs::remove_dir_all(root).unwrap();
2136 }
2137
2138 #[test]
2143 fn evidence_a_failed_run_measured_outlives_the_work_tree() {
2144 let root = project();
2145 let work = root.join(".supercov/work/run_kept");
2146 let evidence = work.join("python/evidence");
2147 fs::create_dir_all(evidence.join("worker-1")).unwrap();
2148 fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
2149 fs::write(evidence.join("worker-1/mcdc.json"), "{}").unwrap();
2150
2151 let kept = keep_failed_evidence(&root, &evidence, "run_kept").expect("the evidence");
2152 remove_stored_tree_deferred(&root, &work).unwrap();
2153 sweep_trash(&root).unwrap();
2154
2155 assert!(!evidence.exists(), "the work tree still went");
2156 assert_eq!(
2157 fs::read_to_string(kept.join("main.jsonl")).unwrap(),
2158 "what the run saw",
2159 );
2160 assert_eq!(
2163 fs::read_to_string(kept.join("worker-1/mcdc.json")).unwrap(),
2164 "{}"
2165 );
2166 fs::remove_dir_all(root).unwrap();
2167 }
2168
2169 #[test]
2170 fn nothing_to_keep_leaves_no_directory_to_puzzle_over() {
2171 let root = project();
2172 let missing = root.join(".supercov/work/run_early/python/evidence");
2175 assert!(keep_failed_evidence(&root, &missing, "run_early").is_none());
2176 fs::create_dir_all(&missing).unwrap();
2177 assert!(keep_failed_evidence(&root, &missing, "run_early").is_none());
2178 assert!(
2179 !root.join(".supercov/failed-evidence/run_early").exists(),
2180 "an empty directory is worse than none: it reads as evidence",
2181 );
2182 fs::remove_dir_all(root).unwrap();
2183 }
2184
2185 #[test]
2188 fn the_failure_says_where_the_evidence_was_kept() {
2189 let root = project();
2190 let evidence = root.join(".supercov/work/run_told/python/evidence");
2191 fs::create_dir_all(&evidence).unwrap();
2192 fs::write(evidence.join("main.jsonl"), "what the run saw").unwrap();
2193
2194 let told = note_kept_evidence(&root, &evidence, "run_told", "boom".into());
2195 let kept = keep_failed_evidence(&root, &evidence, "run_told").expect("the evidence");
2201 assert_eq!(kept, root.join(FAILED_EVIDENCE).join("run_told"));
2202 assert!(
2203 told.starts_with("boom\n"),
2204 "the failure itself came second: {told}"
2205 );
2206 assert!(told.contains(&kept.display().to_string()), "{told}");
2207
2208 let nothing = root.join(".supercov/work/run_empty/python/evidence");
2211 assert_eq!(
2212 note_kept_evidence(&root, ¬hing, "run_empty", "boom".into()),
2213 "boom",
2214 );
2215 fs::remove_dir_all(root).unwrap();
2216 }
2217
2218 #[test]
2219 fn a_trim_leaves_kept_evidence_alone() {
2220 let root = project();
2221 let kept = kept_evidence(&root, "run_trimmed");
2222
2223 clean_storage(
2227 &root,
2228 CleanupOptions {
2229 keep: 20,
2230 dry_run: false,
2231 },
2232 "now",
2233 )
2234 .unwrap();
2235 let retention = cleanup_storage_locked(
2236 &root,
2237 CleanupOptions {
2238 keep: 0,
2239 dry_run: false,
2240 },
2241 false,
2242 )
2243 .unwrap();
2244 sweep_trash(&root).unwrap();
2245
2246 assert!(retention.removed_failed_evidence.is_empty());
2247 assert!(kept.join("main.jsonl").exists());
2248 fs::remove_dir_all(root).unwrap();
2249 }
2250
2251 #[test]
2252 fn cleaning_everything_reclaims_kept_evidence_and_says_which() {
2253 let root = project();
2254 let kept = kept_evidence(&root, "run_cleaned");
2255
2256 let preview = clean_storage(
2257 &root,
2258 CleanupOptions {
2259 keep: 0,
2260 dry_run: true,
2261 },
2262 "now",
2263 )
2264 .unwrap();
2265 assert_eq!(
2266 preview.removed_failed_evidence,
2267 vec!["run_cleaned".to_string()]
2268 );
2269 assert!(kept.join("main.jsonl").exists(), "a preview removed it");
2270
2271 let result = clean_storage(
2272 &root,
2273 CleanupOptions {
2274 keep: 0,
2275 dry_run: false,
2276 },
2277 "now",
2278 )
2279 .unwrap();
2280 sweep_trash(&root).unwrap();
2281
2282 assert_eq!(
2285 result.removed_failed_evidence,
2286 vec!["run_cleaned".to_string()]
2287 );
2288 assert!(!kept.exists());
2289 fs::remove_dir_all(root).unwrap();
2290 }
2291}