Skip to main content

nextest_runner/record/
store.rs

1// Copyright (c) The nextest Contributors
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Run store management for nextest recordings.
5//!
6//! The run store is a directory that contains all recorded test runs. It provides:
7//!
8//! - A lock file for exclusive access during modifications.
9//! - A zstd-compressed JSON file (`runs.json.zst`) listing all recorded runs.
10//! - Individual directories for each run containing the archive and log.
11
12use super::{
13    display::{DisplayRecordedRunInfo, DisplayRecordedRunInfoDetailed, RunListAlignment, Styles},
14    format::{
15        RUN_LOG_FILE_NAME, RecordedRunList, RunsJsonWritePermission, STORE_FORMAT_VERSION,
16        STORE_ZIP_FILE_NAME, StoreFormatVersion, StoreVersionIncompatibility,
17        store_format_version_for_new_run,
18    },
19    recorder::{RunRecorder, StoreSizes},
20    retention::{
21        PruneKind, PrunePlan, PruneResult, RecordRetentionPolicy, delete_orphaned_dirs, delete_runs,
22    },
23    run_id_index::{PrefixResolutionError, RunIdIndex, RunIdSelector, ShortestRunIdPrefix},
24};
25use crate::{
26    errors::{RunIdResolutionError, RunStoreError},
27    helpers::{ThemeCharacters, decimal_char_width},
28    redact::Redactor,
29};
30use camino::{Utf8Path, Utf8PathBuf};
31use chrono::{DateTime, FixedOffset, Local, TimeDelta, Utc};
32use debug_ignore::DebugIgnore;
33use quick_junit::ReportUuid;
34use semver::Version;
35use std::{
36    collections::{BTreeMap, HashMap, HashSet},
37    fmt,
38    fs::{File, TryLockError},
39    io,
40    num::NonZero,
41    thread,
42    time::{Duration, Instant},
43};
44
45static RUNS_LOCK_FILE_NAME: &str = "runs.lock";
46static RUNS_JSON_FILE_NAME: &str = "runs.json.zst";
47
48/// A reference to the runs directory in a run store.
49///
50/// This provides methods to compute paths within the runs directory.
51#[derive(Clone, Copy, Debug)]
52pub struct StoreRunsDir<'a>(&'a Utf8Path);
53
54impl<'a> StoreRunsDir<'a> {
55    /// Creates a new `StoreRunsDir` from a path.
56    pub fn new(path: &'a Utf8Path) -> Self {
57        Self(path)
58    }
59
60    /// Returns the path to a specific run's directory.
61    pub fn run_dir(self, run_id: ReportUuid) -> Utf8PathBuf {
62        self.0.join(run_id.to_string())
63    }
64
65    /// Returns a [`RunFilesExist`] implementation for checking file existence
66    /// for a specific run in this store.
67    pub fn run_files(self, run_id: ReportUuid) -> StoreRunFiles {
68        StoreRunFiles {
69            run_dir: self.run_dir(run_id),
70        }
71    }
72
73    /// Returns the underlying path to the runs directory.
74    pub fn as_path(self) -> &'a Utf8Path {
75        self.0
76    }
77}
78
79/// Trait for checking whether required run files exist.
80///
81/// This abstracts over different storage backends.
82pub trait RunFilesExist {
83    /// Returns true if `store.zip` exists.
84    fn store_zip_exists(&self) -> bool;
85    /// Returns true if `run.log.zst` exists.
86    fn run_log_exists(&self) -> bool;
87}
88
89/// Checks file existence for a run stored on disk.
90///
91/// Created via [`StoreRunsDir::run_files`].
92pub struct StoreRunFiles {
93    run_dir: Utf8PathBuf,
94}
95
96impl RunFilesExist for StoreRunFiles {
97    fn store_zip_exists(&self) -> bool {
98        self.run_dir.join(STORE_ZIP_FILE_NAME).exists()
99    }
100
101    fn run_log_exists(&self) -> bool {
102        self.run_dir.join(RUN_LOG_FILE_NAME).exists()
103    }
104}
105
106/// Manages the storage of recorded test runs.
107///
108/// The run store is a directory containing a list of recorded runs and their data.
109/// Use [`RunStore::lock_exclusive`] to acquire exclusive access before creating
110/// new runs.
111#[derive(Debug)]
112pub struct RunStore {
113    runs_dir: Utf8PathBuf,
114}
115
116impl RunStore {
117    /// Creates a new `RunStore` at the given directory.
118    ///
119    /// Creates the directory if it doesn't exist.
120    pub fn new(store_dir: &Utf8Path) -> Result<Self, RunStoreError> {
121        let runs_dir = store_dir.join("runs");
122        std::fs::create_dir_all(&runs_dir).map_err(|error| RunStoreError::RunDirCreate {
123            run_dir: runs_dir.clone(),
124            error,
125        })?;
126
127        Ok(Self { runs_dir })
128    }
129
130    /// Returns the runs directory.
131    pub fn runs_dir(&self) -> StoreRunsDir<'_> {
132        StoreRunsDir(&self.runs_dir)
133    }
134
135    /// Acquires a shared lock on the run store for reading.
136    ///
137    /// Multiple readers can hold the shared lock simultaneously, but the shared
138    /// lock is exclusive with the exclusive lock (used for writing).
139    ///
140    /// Uses non-blocking lock attempts with retries to handle both brief
141    /// contention and filesystems where locking may not work (e.g., NFS).
142    pub fn lock_shared(&self) -> Result<SharedLockedRunStore<'_>, RunStoreError> {
143        let lock_file_path = self.runs_dir.join(RUNS_LOCK_FILE_NAME);
144        let file = std::fs::OpenOptions::new()
145            .create(true)
146            .truncate(false)
147            .write(true)
148            .open(&lock_file_path)
149            .map_err(|error| RunStoreError::FileLock {
150                path: lock_file_path.clone(),
151                error,
152            })?;
153
154        acquire_lock_with_retry(&file, &lock_file_path, LockKind::Shared)?;
155        let result = read_runs_json(&self.runs_dir)?;
156        let run_id_index = RunIdIndex::new(&result.runs);
157
158        Ok(SharedLockedRunStore {
159            runs_dir: StoreRunsDir(&self.runs_dir),
160            locked_file: DebugIgnore(file),
161            runs: result.runs,
162            write_permission: result.write_permission,
163            run_id_index,
164        })
165    }
166
167    /// Acquires an exclusive lock on the run store.
168    ///
169    /// This lock should only be held for a short duration (just long enough to
170    /// add a run to the list and create its directory).
171    ///
172    /// Uses non-blocking lock attempts with retries to handle both brief
173    /// contention and filesystems where locking may not work (e.g., NFS).
174    pub fn lock_exclusive(&self) -> Result<ExclusiveLockedRunStore<'_>, RunStoreError> {
175        let lock_file_path = self.runs_dir.join(RUNS_LOCK_FILE_NAME);
176        let file = std::fs::OpenOptions::new()
177            .create(true)
178            .truncate(false)
179            .write(true)
180            .open(&lock_file_path)
181            .map_err(|error| RunStoreError::FileLock {
182                path: lock_file_path.clone(),
183                error,
184            })?;
185
186        acquire_lock_with_retry(&file, &lock_file_path, LockKind::Exclusive)?;
187        let result = read_runs_json(&self.runs_dir)?;
188
189        Ok(ExclusiveLockedRunStore {
190            runs_dir: StoreRunsDir(&self.runs_dir),
191            locked_file: DebugIgnore(file),
192            runs: result.runs,
193            last_pruned_at: result.last_pruned_at,
194            write_permission: result.write_permission,
195        })
196    }
197}
198
199/// A run store that has been locked for exclusive access.
200///
201/// The lifetime parameter ensures this isn't held for longer than the
202/// corresponding [`RunStore`].
203#[derive(Debug)]
204pub struct ExclusiveLockedRunStore<'store> {
205    runs_dir: StoreRunsDir<'store>,
206    // Held for RAII lock semantics; the lock is released when this struct is dropped.
207    #[expect(dead_code)]
208    locked_file: DebugIgnore<File>,
209    runs: Vec<RecordedRunInfo>,
210    last_pruned_at: Option<DateTime<Utc>>,
211    write_permission: RunsJsonWritePermission,
212}
213
214impl<'store> ExclusiveLockedRunStore<'store> {
215    /// Returns the runs directory.
216    pub fn runs_dir(&self) -> StoreRunsDir<'store> {
217        self.runs_dir
218    }
219
220    /// Returns whether this nextest can write to the runs.json.zst file.
221    ///
222    /// If the file has a newer format version than we support, writing is denied.
223    pub fn write_permission(&self) -> RunsJsonWritePermission {
224        self.write_permission
225    }
226
227    /// Marks a run as completed and persists the change to disk.
228    ///
229    /// Updates sizes, `status`, and `duration_secs` to the given values.
230    /// Returns `true` if the run was found and updated, `false` if no run
231    /// with the given ID exists (in which case nothing is persisted).
232    ///
233    /// Returns an error if writing is denied due to a format version mismatch.
234    ///
235    /// The status should not be `Incomplete` since we're completing the run.
236    pub fn complete_run(
237        &mut self,
238        run_id: ReportUuid,
239        sizes: StoreSizes,
240        status: RecordedRunStatus,
241        duration_secs: Option<f64>,
242    ) -> Result<bool, RunStoreError> {
243        if let RunsJsonWritePermission::Denied {
244            file_version,
245            max_supported_version,
246        } = self.write_permission
247        {
248            return Err(RunStoreError::FormatVersionTooNew {
249                file_version,
250                max_supported_version,
251            });
252        }
253
254        let found = self.mark_run_completed_inner(run_id, sizes, status, duration_secs);
255        if found {
256            write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
257        }
258        Ok(found)
259    }
260
261    /// Updates a run's metadata in memory.
262    fn mark_run_completed_inner(
263        &mut self,
264        run_id: ReportUuid,
265        sizes: StoreSizes,
266        status: RecordedRunStatus,
267        duration_secs: Option<f64>,
268    ) -> bool {
269        for run in &mut self.runs {
270            if run.run_id == run_id {
271                run.sizes = RecordedSizes {
272                    log: ComponentSizes {
273                        compressed: sizes.log.compressed,
274                        uncompressed: sizes.log.uncompressed,
275                        entries: sizes.log.entries,
276                    },
277                    store: ComponentSizes {
278                        compressed: sizes.store.compressed,
279                        uncompressed: sizes.store.uncompressed,
280                        entries: sizes.store.entries,
281                    },
282                };
283                run.status = status;
284                run.duration_secs = duration_secs;
285                run.last_written_at = Local::now().fixed_offset();
286                return true;
287            }
288        }
289        false
290    }
291
292    /// Prunes runs according to the given retention policy.
293    ///
294    /// This method:
295    /// 1. Determines which runs to delete based on the policy
296    /// 2. Deletes those run directories from disk
297    /// 3. Deletes any orphaned directories not tracked in runs.json.zst
298    /// 4. Updates the run list in memory and on disk
299    ///
300    /// The `kind` parameter indicates whether this is explicit pruning (from a
301    /// user command) or implicit pruning (automatic during recording). This
302    /// affects how errors are displayed.
303    ///
304    /// Returns the result of the pruning operation, including any errors that
305    /// occurred while deleting individual runs.
306    ///
307    /// Returns an error if writing is denied due to a format version mismatch.
308    pub fn prune(
309        &mut self,
310        policy: &RecordRetentionPolicy,
311        kind: PruneKind,
312    ) -> Result<PruneResult, RunStoreError> {
313        if let RunsJsonWritePermission::Denied {
314            file_version,
315            max_supported_version,
316        } = self.write_permission
317        {
318            return Err(RunStoreError::FormatVersionTooNew {
319                file_version,
320                max_supported_version,
321            });
322        }
323
324        let now = Utc::now();
325        let to_delete: HashSet<_> = policy
326            .compute_runs_to_delete(&self.runs, now)
327            .into_iter()
328            .collect();
329
330        let runs_dir = self.runs_dir();
331        let mut result = if to_delete.is_empty() {
332            PruneResult::default()
333        } else {
334            delete_runs(runs_dir, &mut self.runs, &to_delete)
335        };
336        result.kind = kind;
337
338        let known_runs: HashSet<_> = self.runs.iter().map(|r| r.run_id).collect();
339        delete_orphaned_dirs(self.runs_dir, &known_runs, &mut result);
340
341        if result.deleted_count > 0 || result.orphans_deleted > 0 {
342            // Update last_pruned_at since we performed pruning.
343            self.last_pruned_at = Some(now);
344            write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
345        }
346
347        Ok(result)
348    }
349
350    /// Prunes runs if needed, based on time since last prune and limit thresholds.
351    ///
352    /// This method implements implicit pruning, which occurs:
353    /// - If more than 1 day has passed since the last prune, OR
354    /// - If any retention limit is exceeded by 1.5x.
355    ///
356    /// Use [`Self::prune`] for explicit pruning that always runs regardless of these conditions.
357    ///
358    /// Returns `Ok(None)` if pruning was skipped, `Ok(Some(result))` if pruning occurred.
359    pub fn prune_if_needed(
360        &mut self,
361        policy: &RecordRetentionPolicy,
362    ) -> Result<Option<PruneResult>, RunStoreError> {
363        const PRUNE_INTERVAL: TimeDelta = match TimeDelta::try_days(1) {
364            Some(d) => d,
365            None => panic!("1 day should always be a valid TimeDelta"),
366        };
367        const LIMIT_EXCEEDED_FACTOR: f64 = 1.5;
368
369        let now = Utc::now();
370
371        // Check if pruning is needed.
372        let time_since_last_prune = self
373            .last_pruned_at
374            .map(|last| now.signed_duration_since(last))
375            .unwrap_or(TimeDelta::MAX);
376
377        let should_prune = time_since_last_prune >= PRUNE_INTERVAL
378            || policy.limits_exceeded_by_factor(&self.runs, LIMIT_EXCEEDED_FACTOR);
379
380        if should_prune {
381            Ok(Some(self.prune(policy, PruneKind::Implicit)?))
382        } else {
383            Ok(None)
384        }
385    }
386
387    /// Creates a run recorder for a new run.
388    ///
389    /// Adds the run to the list and creates its directory. Consumes self,
390    /// dropping the exclusive lock.
391    ///
392    /// `max_output_size` specifies the maximum size of a single output (stdout/stderr)
393    /// before truncation.
394    ///
395    /// Returns the recorder and the shortest unique prefix for the run ID (for
396    /// display purposes), or an error if writing is denied due to a format
397    /// version mismatch.
398    #[expect(clippy::too_many_arguments)]
399    pub(crate) fn create_run_recorder(
400        mut self,
401        run_id: ReportUuid,
402        nextest_version: Version,
403        started_at: DateTime<FixedOffset>,
404        cli_args: Vec<String>,
405        env_vars: BTreeMap<String, String>,
406        max_output_size: bytesize::ByteSize,
407        parent_run_id: Option<ReportUuid>,
408    ) -> Result<(RunRecorder, ShortestRunIdPrefix), RunStoreError> {
409        if let RunsJsonWritePermission::Denied {
410            file_version,
411            max_supported_version,
412        } = self.write_permission
413        {
414            return Err(RunStoreError::FormatVersionTooNew {
415                file_version,
416                max_supported_version,
417            });
418        }
419
420        // Add to the list of runs before creating the directory. This ensures
421        // that if creation fails, an empty run directory isn't left behind. (It
422        // does mean that there may be spurious entries in the list of runs,
423        // which will be dealt with during pruning.)
424
425        let now = Local::now().fixed_offset();
426        let run = RecordedRunInfo {
427            run_id,
428            store_format_version: store_format_version_for_new_run(),
429            nextest_version,
430            started_at,
431            last_written_at: now,
432            duration_secs: None,
433            cli_args,
434            env_vars,
435            parent_run_id,
436            sizes: RecordedSizes::default(),
437            status: RecordedRunStatus::Incomplete,
438        };
439        self.runs.push(run);
440
441        // If the parent run ID is set, update its last written at time.
442        if let Some(parent_run_id) = parent_run_id
443            && let Some(parent_run) = self.runs.iter_mut().find(|r| r.run_id == parent_run_id)
444        {
445            parent_run.last_written_at = now;
446        }
447
448        write_runs_json(self.runs_dir.as_path(), &self.runs, self.last_pruned_at)?;
449
450        // Compute the unique prefix now that the run is in the list.
451        let index = RunIdIndex::new(&self.runs);
452        let unique_prefix = index
453            .shortest_unique_prefix(run_id)
454            .expect("run was just added to the list");
455
456        // Create the run directory while still holding the lock. This prevents
457        // a race where another process could prune the newly-added run entry
458        // before the directory exists, leaving an orphaned directory. The lock
459        // is released when `self` is dropped.
460        let run_dir = self.runs_dir().run_dir(run_id);
461
462        let recorder = RunRecorder::new(run_dir, max_output_size)?;
463        Ok((recorder, unique_prefix))
464    }
465}
466
467/// Information about a recorded run.
468#[derive(Clone, Debug)]
469pub struct RecordedRunInfo {
470    /// The unique identifier for this run.
471    pub run_id: ReportUuid,
472    /// The format version of this run's store.zip archive.
473    ///
474    /// This allows checking replayability without opening the archive.
475    pub store_format_version: StoreFormatVersion,
476    /// The version of nextest that created this run.
477    pub nextest_version: Version,
478    /// When the run started.
479    pub started_at: DateTime<FixedOffset>,
480    /// When this run was last written to.
481    ///
482    /// Used for LRU eviction. Updated when the run is created, when the run
483    /// completes, and when a rerun references this run.
484    pub last_written_at: DateTime<FixedOffset>,
485    /// Duration of the run in seconds.
486    ///
487    /// This is `None` for incomplete runs.
488    pub duration_secs: Option<f64>,
489    /// The command-line arguments used to invoke nextest.
490    pub cli_args: Vec<String>,
491    /// Environment variables that affect nextest behavior (NEXTEST_* and CARGO_*).
492    pub env_vars: BTreeMap<String, String>,
493    /// If this is a rerun, the ID of the parent run.
494    ///
495    /// This forms a chain for iterative fix-and-rerun workflows.
496    pub parent_run_id: Option<ReportUuid>,
497    /// Sizes broken down by component (log and store).
498    pub sizes: RecordedSizes,
499    /// The status and statistics for this run.
500    pub status: RecordedRunStatus,
501}
502
503/// Sizes broken down by component (log and store).
504#[derive(Clone, Copy, Debug, Default)]
505pub struct RecordedSizes {
506    /// Sizes for the run log (run.log.zst).
507    pub log: ComponentSizes,
508    /// Sizes for the store archive (store.zip).
509    pub store: ComponentSizes,
510}
511
512/// Compressed and uncompressed sizes for a single component.
513#[derive(Clone, Copy, Debug, Default)]
514pub struct ComponentSizes {
515    /// Compressed size in bytes.
516    pub compressed: u64,
517    /// Uncompressed size in bytes.
518    pub uncompressed: u64,
519    /// Number of entries (records for log, files for store).
520    pub entries: u64,
521}
522
523impl RecordedSizes {
524    /// Returns the total compressed size (log + store).
525    pub fn total_compressed(&self) -> u64 {
526        self.log.compressed + self.store.compressed
527    }
528
529    /// Returns the total uncompressed size (log + store).
530    pub fn total_uncompressed(&self) -> u64 {
531        self.log.uncompressed + self.store.uncompressed
532    }
533
534    /// Returns the total number of entries (log records + store files).
535    pub fn total_entries(&self) -> u64 {
536        self.log.entries + self.store.entries
537    }
538}
539
540/// Status and statistics for a recorded run.
541#[derive(Clone, Debug)]
542pub enum RecordedRunStatus {
543    /// The run was interrupted before completion.
544    Incomplete,
545    /// A normal test run completed (all tests finished).
546    Completed(CompletedRunStats),
547    /// A normal test run was cancelled before all tests finished.
548    Cancelled(CompletedRunStats),
549    /// A stress test run completed (all iterations finished).
550    StressCompleted(StressCompletedRunStats),
551    /// A stress test run was cancelled before all iterations finished.
552    StressCancelled(StressCompletedRunStats),
553    /// An unknown status from a newer version of nextest.
554    ///
555    /// This variant is used for forward compatibility when reading runs.json.zst
556    /// files created by newer nextest versions that may have new status types.
557    Unknown,
558}
559
560impl RecordedRunStatus {
561    /// Returns a short status string for display.
562    pub fn short_status_str(&self) -> &'static str {
563        match self {
564            Self::Incomplete => "incomplete",
565            Self::Unknown => "unknown",
566            Self::Completed(_) => "completed",
567            Self::Cancelled(_) => "cancelled",
568            Self::StressCompleted(_) => "stress completed",
569            Self::StressCancelled(_) => "stress cancelled",
570        }
571    }
572
573    /// Returns the exit code for completed runs, or `None` for incomplete/unknown runs.
574    pub fn exit_code(&self) -> Option<i32> {
575        match self {
576            Self::Incomplete | Self::Unknown => None,
577            Self::Completed(stats) | Self::Cancelled(stats) => Some(stats.exit_code),
578            Self::StressCompleted(stats) | Self::StressCancelled(stats) => Some(stats.exit_code),
579        }
580    }
581}
582
583/// Statistics for a normal test run that finished (completed or cancelled).
584#[derive(Clone, Copy, Debug)]
585pub struct CompletedRunStats {
586    /// The number of tests that were expected to run.
587    pub initial_run_count: usize,
588    /// The number of tests that passed.
589    pub passed: usize,
590    /// The number of tests that failed (including exec failures and timeouts).
591    pub failed: usize,
592    /// The exit code from the run.
593    pub exit_code: i32,
594}
595
596/// Statistics for a stress test run that finished (completed or cancelled).
597#[derive(Clone, Copy, Debug)]
598pub struct StressCompletedRunStats {
599    /// The number of stress iterations that were expected to run, if known.
600    ///
601    /// This is `None` when the stress test was run without a fixed iteration count
602    /// (e.g., `--stress-duration`).
603    pub initial_iteration_count: Option<NonZero<u32>>,
604    /// The number of stress iterations that succeeded.
605    pub success_count: u32,
606    /// The number of stress iterations that failed.
607    pub failed_count: u32,
608    /// The exit code from the run.
609    pub exit_code: i32,
610}
611
612// ---
613// Replayability checking
614// ---
615
616/// The result of checking whether a run can be replayed.
617#[derive(Clone, Debug)]
618pub enum ReplayabilityStatus {
619    /// The run is definitely replayable.
620    ///
621    /// No blocking reasons and no uncertain conditions.
622    Replayable,
623    /// The run is definitely not replayable.
624    ///
625    /// Contains at least one blocking reason.
626    NotReplayable(Vec<NonReplayableReason>),
627    /// The run might be replayable but is incomplete.
628    ///
629    /// The archive might be usable, but we'd need to open `store.zip` to
630    /// verify all expected files are present.
631    Incomplete,
632}
633
634/// A definite reason why a run cannot be replayed.
635#[derive(Clone, Debug, PartialEq, Eq)]
636pub enum NonReplayableReason {
637    /// The run's store format version is incompatible with this nextest version.
638    ///
639    /// This nextest version cannot read the archive format.
640    StoreVersionIncompatible {
641        /// The specific incompatibility.
642        incompatibility: StoreVersionIncompatibility,
643    },
644    /// The `store.zip` file is missing from the run directory.
645    MissingStoreZip,
646    /// The `run.log.zst` file is missing from the run directory.
647    MissingRunLog,
648    /// The run status is `Unknown` (from a newer nextest version).
649    ///
650    /// We cannot safely replay since we don't understand the run's state.
651    StatusUnknown,
652}
653
654impl fmt::Display for NonReplayableReason {
655    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
656        match self {
657            Self::StoreVersionIncompatible { incompatibility } => {
658                write!(f, "store format version incompatible: {}", incompatibility)
659            }
660            Self::MissingStoreZip => {
661                write!(f, "store.zip is missing")
662            }
663            Self::MissingRunLog => {
664                write!(f, "run.log.zst is missing")
665            }
666            Self::StatusUnknown => {
667                write!(f, "run status is unknown (from a newer nextest version)")
668            }
669        }
670    }
671}
672
673/// Result of looking up a run by selector.
674#[derive(Clone, Copy, Debug)]
675pub struct ResolveRunIdResult {
676    /// The run ID.
677    pub run_id: ReportUuid,
678}
679
680impl RecordedRunStatus {
681    /// Returns the width (in decimal digits) needed to display the "passed" count.
682    ///
683    /// For non-completed runs (Incomplete, Unknown), returns 0 since they don't
684    /// display a passed count.
685    pub fn passed_count_width(&self) -> usize {
686        match self {
687            Self::Incomplete | Self::Unknown => 0,
688            Self::Completed(stats) | Self::Cancelled(stats) => decimal_char_width(stats.passed),
689            Self::StressCompleted(stats) | Self::StressCancelled(stats) => {
690                decimal_char_width(stats.success_count)
691            }
692        }
693    }
694}
695
696impl RecordedRunInfo {
697    /// Checks whether this run can be replayed.
698    ///
699    /// This performs a comprehensive check of all conditions that might prevent
700    /// replay, including:
701    /// - Store format version compatibility
702    /// - Presence of required files (store.zip, run.log.zst)
703    /// - Run status (unknown, incomplete)
704    ///
705    /// The `files` parameter is used to check for file existence. Use
706    /// [`StoreRunsDir::run_files`] for runs in the store, or pass in a
707    /// [`PortableRecording`](super::PortableRecording) directly.
708    pub fn check_replayability(&self, files: &dyn RunFilesExist) -> ReplayabilityStatus {
709        let mut blocking = Vec::new();
710        let mut is_incomplete = false;
711
712        // Check store format version compatibility.
713        if let Err(incompatibility) = self
714            .store_format_version
715            .check_readable_by(STORE_FORMAT_VERSION)
716        {
717            blocking.push(NonReplayableReason::StoreVersionIncompatible { incompatibility });
718        }
719
720        // Check for required files.
721        if !files.store_zip_exists() {
722            blocking.push(NonReplayableReason::MissingStoreZip);
723        }
724        if !files.run_log_exists() {
725            blocking.push(NonReplayableReason::MissingRunLog);
726        }
727
728        // Check run status.
729        match &self.status {
730            RecordedRunStatus::Unknown => {
731                blocking.push(NonReplayableReason::StatusUnknown);
732            }
733            RecordedRunStatus::Incomplete => {
734                is_incomplete = true;
735            }
736            RecordedRunStatus::Completed(_)
737            | RecordedRunStatus::Cancelled(_)
738            | RecordedRunStatus::StressCompleted(_)
739            | RecordedRunStatus::StressCancelled(_) => {
740                // These statuses are fine for replay.
741            }
742        }
743
744        // Return the appropriate variant based on what we found.
745        if !blocking.is_empty() {
746            ReplayabilityStatus::NotReplayable(blocking)
747        } else if is_incomplete {
748            ReplayabilityStatus::Incomplete
749        } else {
750            ReplayabilityStatus::Replayable
751        }
752    }
753
754    /// Returns a display wrapper for this run.
755    ///
756    /// The `run_id_index` is used for computing shortest unique prefixes,
757    /// which are highlighted differently in the output (similar to jj).
758    ///
759    /// The `alignment` parameter controls column alignment when displaying a
760    /// list of runs. Use [`RunListAlignment::from_runs`] to precompute
761    /// alignment for a set of runs.
762    ///
763    /// The `redactor` parameter, if provided, redacts timestamps, durations,
764    /// and sizes for snapshot testing while preserving column alignment.
765    pub fn display<'a>(
766        &'a self,
767        run_id_index: &'a RunIdIndex,
768        replayability: &'a ReplayabilityStatus,
769        alignment: RunListAlignment,
770        styles: &'a Styles,
771        redactor: &'a Redactor,
772    ) -> DisplayRecordedRunInfo<'a> {
773        DisplayRecordedRunInfo::new(
774            self,
775            run_id_index,
776            replayability,
777            alignment,
778            styles,
779            redactor,
780        )
781    }
782
783    /// Returns a detailed display wrapper for this run.
784    ///
785    /// Unlike [`Self::display`] which shows a compact table row, this provides
786    /// a multi-line detailed view suitable for the `store info` command.
787    ///
788    /// The `replayability` parameter should be computed by the caller using
789    /// [`Self::check_replayability`].
790    ///
791    /// The `now` parameter is the current time, used to compute relative
792    /// durations (e.g. "30s ago").
793    ///
794    /// The `redactor` parameter redacts paths, timestamps, durations, and sizes
795    /// for snapshot testing. Use `Redactor::noop()` if no redaction is needed.
796    pub fn display_detailed<'a>(
797        &'a self,
798        run_id_index: &'a RunIdIndex,
799        replayability: &'a ReplayabilityStatus,
800        now: DateTime<Utc>,
801        styles: &'a Styles,
802        theme_characters: &'a ThemeCharacters,
803        redactor: &'a Redactor,
804    ) -> DisplayRecordedRunInfoDetailed<'a> {
805        DisplayRecordedRunInfoDetailed::new(
806            self,
807            run_id_index,
808            replayability,
809            now,
810            styles,
811            theme_characters,
812            redactor,
813        )
814    }
815}
816
817/// Result of reading runs.json.zst.
818struct ReadRunsJsonResult {
819    runs: Vec<RecordedRunInfo>,
820    last_pruned_at: Option<DateTime<Utc>>,
821    write_permission: RunsJsonWritePermission,
822}
823
824/// Reads and deserializes `runs.json.zst`, converting to the internal
825/// representation.
826fn read_runs_json(runs_dir: &Utf8Path) -> Result<ReadRunsJsonResult, RunStoreError> {
827    let runs_json_path = runs_dir.join(RUNS_JSON_FILE_NAME);
828    let file = match File::open(&runs_json_path) {
829        Ok(file) => file,
830        Err(error) => {
831            if error.kind() == io::ErrorKind::NotFound {
832                // The file doesn't exist yet, so we can write a new one.
833                return Ok(ReadRunsJsonResult {
834                    runs: Vec::new(),
835                    last_pruned_at: None,
836                    write_permission: RunsJsonWritePermission::Allowed,
837                });
838            } else {
839                return Err(RunStoreError::RunListRead {
840                    path: runs_json_path,
841                    error,
842                });
843            }
844        }
845    };
846
847    let decoder = zstd::stream::Decoder::new(file).map_err(|error| RunStoreError::RunListRead {
848        path: runs_json_path.clone(),
849        error,
850    })?;
851
852    let list: RecordedRunList =
853        serde_json::from_reader(decoder).map_err(|error| RunStoreError::RunListDeserialize {
854            path: runs_json_path,
855            error,
856        })?;
857    let write_permission = list.write_permission();
858    let data = list.into_data();
859    Ok(ReadRunsJsonResult {
860        runs: data.runs,
861        last_pruned_at: data.last_pruned_at,
862        write_permission,
863    })
864}
865
866/// Serializes and writes runs.json.zst from internal representation.
867fn write_runs_json(
868    runs_dir: &Utf8Path,
869    runs: &[RecordedRunInfo],
870    last_pruned_at: Option<DateTime<Utc>>,
871) -> Result<(), RunStoreError> {
872    let runs_json_path = runs_dir.join(RUNS_JSON_FILE_NAME);
873    let list = RecordedRunList::from_data(runs, last_pruned_at);
874
875    atomicwrites::AtomicFile::new(&runs_json_path, atomicwrites::AllowOverwrite)
876        .write(|file| {
877            // Use compression level 3, consistent with other zstd usage in the crate.
878            let mut encoder = zstd::stream::Encoder::new(file, 3)?;
879            serde_json::to_writer_pretty(&mut encoder, &list)?;
880            encoder.finish()?;
881            Ok(())
882        })
883        .map_err(|error| RunStoreError::RunListWrite {
884            path: runs_json_path,
885            error,
886        })?;
887
888    Ok(())
889}
890
891/// A run store that has been locked for shared (read-only) access.
892///
893/// Multiple readers can hold this lock simultaneously, but it is exclusive
894/// with the exclusive lock used for writing.
895#[derive(Debug)]
896pub struct SharedLockedRunStore<'store> {
897    runs_dir: StoreRunsDir<'store>,
898    #[expect(dead_code, reason = "held for lock duration")]
899    locked_file: DebugIgnore<File>,
900    runs: Vec<RecordedRunInfo>,
901    write_permission: RunsJsonWritePermission,
902    run_id_index: RunIdIndex,
903}
904
905impl<'store> SharedLockedRunStore<'store> {
906    /// Returns a snapshot of the runs data, consuming self and releasing the
907    /// lock.
908    pub fn into_snapshot(self) -> RunStoreSnapshot {
909        RunStoreSnapshot {
910            runs_dir: self.runs_dir.as_path().to_owned(),
911            runs: self.runs,
912            write_permission: self.write_permission,
913            run_id_index: self.run_id_index,
914        }
915    }
916}
917
918/// A snapshot of run store data.
919#[derive(Debug)]
920pub struct RunStoreSnapshot {
921    runs_dir: Utf8PathBuf,
922    runs: Vec<RecordedRunInfo>,
923    write_permission: RunsJsonWritePermission,
924    run_id_index: RunIdIndex,
925}
926
927impl RunStoreSnapshot {
928    /// Returns the runs directory.
929    pub fn runs_dir(&self) -> StoreRunsDir<'_> {
930        StoreRunsDir(&self.runs_dir)
931    }
932
933    /// Returns whether this nextest can write to the runs.json.zst file.
934    ///
935    /// If the file has a newer format version than we support, writing is denied.
936    pub fn write_permission(&self) -> RunsJsonWritePermission {
937        self.write_permission
938    }
939
940    /// Returns a list of recorded runs.
941    pub fn runs(&self) -> &[RecordedRunInfo] {
942        &self.runs
943    }
944
945    /// Returns the number of recorded runs.
946    pub fn run_count(&self) -> usize {
947        self.runs.len()
948    }
949
950    /// Returns the total compressed size of all recorded runs in bytes.
951    pub fn total_size(&self) -> u64 {
952        self.runs.iter().map(|r| r.sizes.total_compressed()).sum()
953    }
954
955    /// Resolves a run ID selector to a run result.
956    ///
957    /// For [`RunIdSelector::Latest`], returns the most recent run by start
958    /// time.
959    /// For [`RunIdSelector::Prefix`], resolves the prefix to a specific run.
960    pub fn resolve_run_id(
961        &self,
962        selector: &RunIdSelector,
963    ) -> Result<ResolveRunIdResult, RunIdResolutionError> {
964        match selector {
965            RunIdSelector::Latest => self.most_recent_run(),
966            RunIdSelector::Prefix(prefix) => {
967                let run_id = self.resolve_run_id_prefix(prefix)?;
968                Ok(ResolveRunIdResult { run_id })
969            }
970        }
971    }
972
973    /// Resolves a run ID prefix to a full UUID.
974    ///
975    /// The prefix must be a valid hexadecimal string. If the prefix matches
976    /// exactly one run, that run's UUID is returned. Otherwise, an error is
977    /// returned indicating whether no runs matched or multiple runs matched.
978    fn resolve_run_id_prefix(&self, prefix: &str) -> Result<ReportUuid, RunIdResolutionError> {
979        self.run_id_index.resolve_prefix(prefix).map_err(|err| {
980            match err {
981                PrefixResolutionError::NotFound => RunIdResolutionError::NotFound {
982                    prefix: prefix.to_string(),
983                },
984                PrefixResolutionError::Ambiguous { count, candidates } => {
985                    // Convert UUIDs to full RecordedRunInfo and sort by start time (most recent first).
986                    let mut candidates: Vec<_> = candidates
987                        .into_iter()
988                        .filter_map(|run_id| self.get_run(run_id).cloned())
989                        .collect();
990                    candidates.sort_by_key(|run| std::cmp::Reverse(run.started_at));
991                    RunIdResolutionError::Ambiguous {
992                        prefix: prefix.to_string(),
993                        count,
994                        candidates,
995                        run_id_index: self.run_id_index.clone(),
996                    }
997                }
998                PrefixResolutionError::InvalidPrefix => RunIdResolutionError::InvalidPrefix {
999                    prefix: prefix.to_string(),
1000                },
1001            }
1002        })
1003    }
1004
1005    /// Returns the run ID index for computing shortest unique prefixes.
1006    pub fn run_id_index(&self) -> &RunIdIndex {
1007        &self.run_id_index
1008    }
1009
1010    /// Looks up a run by its exact UUID.
1011    pub fn get_run(&self, run_id: ReportUuid) -> Option<&RecordedRunInfo> {
1012        self.runs.iter().find(|r| r.run_id == run_id)
1013    }
1014
1015    /// Returns the most recent run by start time.
1016    ///
1017    /// Returns an error if there are no runs at all.
1018    pub fn most_recent_run(&self) -> Result<ResolveRunIdResult, RunIdResolutionError> {
1019        self.runs
1020            .iter()
1021            .max_by_key(|r| r.started_at)
1022            .map(|r| ResolveRunIdResult { run_id: r.run_id })
1023            .ok_or(RunIdResolutionError::NoRuns)
1024    }
1025
1026    /// Computes which runs would be deleted by a prune operation.
1027    ///
1028    /// This is used for dry-run mode to show what would be deleted without
1029    /// actually deleting anything. Returns a [`PrunePlan`] containing the runs
1030    /// that would be deleted, sorted by start time (oldest first).
1031    pub fn compute_prune_plan(&self, policy: &RecordRetentionPolicy) -> PrunePlan {
1032        PrunePlan::compute(&self.runs, policy)
1033    }
1034}
1035
1036/// A snapshot paired with precomputed replayability status for all runs.
1037///
1038/// This struct maintains the invariant that every run in the snapshot has a
1039/// corresponding entry in the replayability map. Use [`Self::new`] to compute
1040/// replayability for all runs, or `Self::new_for_test` for testing.
1041#[derive(Debug)]
1042pub struct SnapshotWithReplayability<'a> {
1043    snapshot: &'a RunStoreSnapshot,
1044    replayability: HashMap<ReportUuid, ReplayabilityStatus>,
1045    latest_run_id: Option<ReportUuid>,
1046}
1047
1048impl<'a> SnapshotWithReplayability<'a> {
1049    /// Creates a new snapshot with replayability by checking all runs.
1050    ///
1051    /// This computes [`ReplayabilityStatus`] for each run by checking file
1052    /// existence and format versions.
1053    pub fn new(snapshot: &'a RunStoreSnapshot) -> Self {
1054        let runs_dir = snapshot.runs_dir();
1055        let replayability: HashMap<_, _> = snapshot
1056            .runs()
1057            .iter()
1058            .map(|run| {
1059                (
1060                    run.run_id,
1061                    run.check_replayability(&runs_dir.run_files(run.run_id)),
1062                )
1063            })
1064            .collect();
1065
1066        // Find the latest run by time.
1067        let latest_run_id = snapshot.most_recent_run().ok().map(|r| r.run_id);
1068
1069        Self {
1070            snapshot,
1071            replayability,
1072            latest_run_id,
1073        }
1074    }
1075
1076    /// Returns a reference to the underlying snapshot.
1077    pub fn snapshot(&self) -> &'a RunStoreSnapshot {
1078        self.snapshot
1079    }
1080
1081    /// Returns the replayability map.
1082    pub fn replayability(&self) -> &HashMap<ReportUuid, ReplayabilityStatus> {
1083        &self.replayability
1084    }
1085
1086    /// Returns the replayability status for a specific run.
1087    ///
1088    /// # Panics
1089    ///
1090    /// Panics if the run ID is not in the snapshot. This maintains the
1091    /// invariant that all runs in the snapshot have replayability computed.
1092    pub fn get_replayability(&self, run_id: ReportUuid) -> &ReplayabilityStatus {
1093        self.replayability
1094            .get(&run_id)
1095            .expect("run ID should be in replayability map")
1096    }
1097
1098    /// Returns the ID of the most recent run by start time, if any.
1099    pub fn latest_run_id(&self) -> Option<ReportUuid> {
1100        self.latest_run_id
1101    }
1102}
1103
1104#[cfg(test)]
1105impl SnapshotWithReplayability<'_> {
1106    /// Creates a snapshot with replayability for testing.
1107    ///
1108    /// All runs are marked as [`ReplayabilityStatus::Replayable`] by default.
1109    pub fn new_for_test(snapshot: &RunStoreSnapshot) -> SnapshotWithReplayability<'_> {
1110        let replayability: HashMap<_, _> = snapshot
1111            .runs()
1112            .iter()
1113            .map(|run| (run.run_id, ReplayabilityStatus::Replayable))
1114            .collect();
1115
1116        // For tests, latest is just the most recent by time.
1117        let latest_run_id = snapshot
1118            .runs()
1119            .iter()
1120            .max_by_key(|r| r.started_at)
1121            .map(|r| r.run_id);
1122
1123        SnapshotWithReplayability {
1124            snapshot,
1125            replayability,
1126            latest_run_id,
1127        }
1128    }
1129}
1130
1131#[cfg(test)]
1132impl RunStoreSnapshot {
1133    /// Creates a new snapshot for testing.
1134    pub(crate) fn new_for_test(runs: Vec<RecordedRunInfo>) -> Self {
1135        use super::run_id_index::RunIdIndex;
1136
1137        let run_id_index = RunIdIndex::new(&runs);
1138        Self {
1139            runs_dir: Utf8PathBuf::from("/test/runs"),
1140            runs,
1141            write_permission: RunsJsonWritePermission::Allowed,
1142            run_id_index,
1143        }
1144    }
1145}
1146
1147/// The kind of lock to acquire.
1148#[derive(Clone, Copy)]
1149enum LockKind {
1150    Shared,
1151    Exclusive,
1152}
1153
1154/// Acquires a file lock with retries, timing out after 5 seconds.
1155///
1156/// This handles both brief contention (another nextest process finishing up)
1157/// and filesystems where locking may not work properly (e.g., NFS).
1158fn acquire_lock_with_retry(
1159    file: &File,
1160    lock_file_path: &Utf8Path,
1161    kind: LockKind,
1162) -> Result<(), RunStoreError> {
1163    const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
1164    const LOCK_RETRY_INTERVAL: Duration = Duration::from_millis(100);
1165
1166    let start = Instant::now();
1167    loop {
1168        let result = match kind {
1169            LockKind::Shared => file.try_lock_shared(),
1170            LockKind::Exclusive => file.try_lock(),
1171        };
1172
1173        match result {
1174            Ok(()) => return Ok(()),
1175            Err(TryLockError::WouldBlock) => {
1176                // Lock is held by another process. Retry if we haven't timed out.
1177                if start.elapsed() >= LOCK_TIMEOUT {
1178                    return Err(RunStoreError::FileLockTimeout {
1179                        path: lock_file_path.to_owned(),
1180                        timeout_secs: LOCK_TIMEOUT.as_secs(),
1181                    });
1182                }
1183                thread::sleep(LOCK_RETRY_INTERVAL);
1184            }
1185            Err(TryLockError::Error(error)) => {
1186                // Some other error (e.g., locking not supported on this filesystem).
1187                return Err(RunStoreError::FileLock {
1188                    path: lock_file_path.to_owned(),
1189                    error,
1190                });
1191            }
1192        }
1193    }
1194}