Skip to main content

scientific_workflow/persistence/
local.rs

1//! Private local persistence adapter and verified reconstruction.
2//!
3//! This module is not API. Runtime reaches it only through the parent
4//! `PersistenceSession`, which supplies Study's immutable plan, inferred path,
5//! observation plan, schema, and provenance. Execution units and applications cannot
6//! construct or drive these writers.
7//!
8//! One bounded queue and worker serve every configured stream. Each stream
9//! accumulates an independent byte-targeted chunk in reusable userspace memory
10//! and performs filesystem IO only when publishing that chunk. A recording
11//! owns exactly one authoritative `metadata.json` lifecycle.
12//!
13//! # Ownership and backpressure
14//!
15//! Sampling never clones, removes, or retains a scientific payload. The
16//! selected values are borrowed only while Serde creates one owned JSONL
17//! record. That record is then moved into the recording writer. If the configured
18//! queue-byte budget is full, [`SystemStateWriter::observe_state`] blocks until the writer
19//! commits enough queued bytes or reports a terminal error. Records are never
20//! split between chunks.
21//!
22//! # Lifecycle
23//!
24//! [`SystemStateWriter::create`] refuses an existing output root, consumes an
25//! observation plan already bound to the shared state schema, infers deterministic
26//! stream layout, and publishes initial `running`
27//! metadata, and then starts the recording writer. A complete buffered chunk is
28//! written once, synchronized, described in metadata, and atomically sealed.
29//! [`SystemStateWriter::complete_recording`] drains the writer, atomically commits
30//! completion timing and terminal metadata;
31//! [`SystemStateWriter::mark_recording_failed`] records an explicit failed
32//! lifecycle instead. Dropping an active recording drains its writer thread for
33//! memory and file safety but deliberately leaves metadata as `running`.
34//!
35//! # Reading
36//!
37//! [`StoredStateSeriesReader`] accepts a completed output directory and a [`JsonPayloadDecoderRegistry`]
38//! registry. The reader validates metadata, chunks, checksums, record order,
39//! and decoder coverage before reconstructing typed
40//! [`StateSeries`](crate::state::StateSeries) values. Decoder
41//! implementations remain per payload type and registrations remain per exact
42//! state key. Latest-state reads verify and decode only the newest chunk.
43//!
44//! # Boundary
45//!
46//! This adapter owns local durable mechanics: run directories, stream chunking, queue
47//! flushing, metadata transitions, and reconstruction integrity checks. The
48//! observation subsystem owns scientific stream schemas, cadence, and
49//! encoding; callers own simulation evolution and decoder registrations. The
50//! adapter does not define
51//! modeling APIs, RNG behavior, or artifact semantics.
52
53use std::fs::{self, File, OpenOptions};
54use std::io::Write;
55use std::num::NonZeroU64;
56use std::path::{Path, PathBuf};
57use std::sync::{Arc, Mutex, MutexGuard};
58use std::time::{Duration, Instant};
59
60use fs2::FileExt;
61use serde::{Deserialize, Serialize};
62use serde_json::{Map, Value};
63
64use crate::clock::{duration_nanoseconds, utc_now_rfc3339};
65use crate::observation::{
66    BoundObservationPlan, BoundObservationStream, EncodedObservation, ObservationSession,
67};
68use crate::state::SystemState;
69
70mod error;
71mod json_payload_decoder;
72mod jsonl_format;
73mod queued_state_writer;
74mod stored_state_series_reader;
75
76pub use error::PersistenceError;
77pub use json_payload_decoder::{JsonPayloadDecoder, JsonPayloadDecoderRegistry};
78pub use stored_state_series_reader::StoredStateSeriesReader;
79
80use jsonl_format::{
81    EncodedStateRecord, RecordingMetadata, RecordingStatus, StateFieldMetadata,
82    StateStreamMetadata, TimeAxisMetadata as StoredTimeAxis,
83};
84use queued_state_writer::{StateStreamStorageConfig, StateWriterWorker};
85
86/// Stable name of the sole structural metadata file in one output root.
87const METADATA_FILE: &str = "metadata.json";
88
89/// Temporary sibling used for atomic metadata replacement.
90const METADATA_TEMP_FILE: &str = ".metadata.json.tmp";
91
92/// Immutable operational timing returned after successful recording completion.
93///
94/// These values describe host execution rather than scientific coordinates.
95/// Scientific iteration and physical time remain part of each recorded
96/// [`SystemState`].
97#[derive(Clone, Debug, Eq, PartialEq)]
98pub struct RecordingTiming {
99    created_at_utc: String,
100    finalized_at_utc: String,
101    active_duration_ns: u64,
102}
103
104impl RecordingTiming {
105    /// Converts the validated private wire representation into the public view.
106    fn from_stored(
107        timing: &jsonl_format::RecordingTiming,
108        metadata_path: &Path,
109    ) -> Result<Self, PersistenceError> {
110        let finalized_at_utc =
111            timing
112                .finalized_at_utc
113                .clone()
114                .ok_or_else(|| PersistenceError::InvalidMetadata {
115                    path: metadata_path.to_path_buf(),
116                    reason: "completed recording lacks finalized timestamp".to_owned(),
117                })?;
118        Ok(Self {
119            created_at_utc: timing.created_at_utc.clone(),
120            finalized_at_utc,
121            active_duration_ns: timing.active_duration_ns,
122        })
123    }
124
125    /// Returns the recording's original UTC creation timestamp in RFC 3339 form.
126    pub fn created_at_utc(&self) -> &str {
127        &self.created_at_utc
128    }
129
130    /// Returns the successful completion timestamp in UTC RFC 3339 form.
131    pub fn finalized_at_utc(&self) -> &str {
132        &self.finalized_at_utc
133    }
134
135    /// Returns the accumulated active writer duration as a standard duration.
136    pub fn active_duration(&self) -> Duration {
137        Duration::from_nanos(self.active_duration_ns)
138    }
139}
140
141/// Coordinate-aware interval used to select states for one output stream.
142///
143/// The noun variant identifies the coordinate on which the interval is
144/// measured. The current storage format supports iteration-based sampling;
145/// adding physical-time sampling later will not require overloading the word
146/// `step` or changing the surrounding stream API.
147///
148/// Human-authored configuration may use the concise JSON value `10` for every
149/// ten iterations. Deserialization also accepts the stable tagged form
150/// `{"iterations": 10}` emitted by serialization.
151#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
152#[serde(rename_all = "snake_case")]
153pub(crate) enum SamplingInterval {
154    /// Select iteration zero and each iteration divisible by this interval.
155    Iterations(NonZeroU64),
156}
157
158#[derive(Deserialize)]
159#[serde(untagged)]
160enum SamplingIntervalInput {
161    /// Concise configuration form: `10` means every ten iterations.
162    Iterations(NonZeroU64),
163    /// Stable tagged form emitted by [`SamplingInterval`]'s serializer.
164    Tagged { iterations: NonZeroU64 },
165}
166
167impl<'de> Deserialize<'de> for SamplingInterval {
168    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
169    where
170        D: serde::Deserializer<'de>,
171    {
172        match SamplingIntervalInput::deserialize(deserializer)? {
173            SamplingIntervalInput::Iterations(interval)
174            | SamplingIntervalInput::Tagged {
175                iterations: interval,
176            } => Ok(Self::Iterations(interval)),
177        }
178    }
179}
180
181impl SamplingInterval {
182    /// Creates an iteration interval, returning `None` for zero.
183    pub(crate) const fn iterations(interval: u64) -> Option<Self> {
184        match NonZeroU64::new(interval) {
185            Some(interval) => Some(Self::Iterations(interval)),
186            None => None,
187        }
188    }
189}
190
191/// Filesystem layout for one logical state stream.
192#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
193#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
194pub(crate) enum StateStreamLayout {
195    /// Accumulate encoded records in memory until the rollover target is met.
196    Chunked {
197        /// Approximate encoded-byte threshold at which a chunk is sealed.
198        target_bytes: NonZeroU64,
199    },
200    /// Publish every encoded record as its own immutable file.
201    IndividualFiles,
202}
203
204/// Persistence and backpressure policy for one logical state stream.
205#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
206#[serde(deny_unknown_fields)]
207pub(crate) struct StateStreamStorage {
208    layout: StateStreamLayout,
209    storage_queue_bytes: NonZeroU64,
210}
211
212impl StateStreamStorage {
213    /// Creates an in-memory chunking policy with a strict queue-byte budget.
214    pub(crate) const fn chunked(target_bytes: NonZeroU64, storage_queue_bytes: NonZeroU64) -> Self {
215        Self {
216            layout: StateStreamLayout::Chunked { target_bytes },
217            storage_queue_bytes,
218        }
219    }
220
221    /// Returns the configured on-disk stream layout.
222    pub(crate) const fn layout(self) -> StateStreamLayout {
223        self.layout
224    }
225
226    /// Returns the strict byte capacity shared by queued records.
227    pub(crate) const fn storage_queue_bytes(self) -> NonZeroU64 {
228        self.storage_queue_bytes
229    }
230}
231
232/// Exclusive queued writer for all persistent streams in one recording.
233///
234/// This type is intentionally non-Clone. It owns the only writer handles and
235/// the only legal transition from `running` metadata to a terminal status.
236/// It owns no [`SystemState`] and never extends a payload borrow beyond one
237/// synchronous [`SystemStateWriter::observe_state`] call.
238pub(crate) struct SystemStateWriter {
239    manifest: Arc<RecordingManifest>,
240    session: ObservationSession,
241    writer: Option<StateWriterWorker>,
242    session_started: Instant,
243    /// Held after writers so normal field drop keeps the lease until every
244    /// worker has drained and released its manifest handle.
245    _lease: RecordingLease,
246}
247
248impl SystemStateWriter {
249    /// Creates the sole local writer from settings already resolved by Study.
250    pub(crate) fn create(
251        root: PathBuf,
252        descriptor: BoundObservationPlan,
253        user_metadata: Map<String, Value>,
254        storage: StateStreamStorage,
255    ) -> Result<Self, PersistenceError> {
256        ensure_absent(&root)?;
257        let prepared = PreparedRecording::new(root, descriptor, user_metadata, storage)?;
258        create_root(&prepared.root)?;
259        let lease = RecordingLease::acquire(&prepared.root)?;
260        for stream in &prepared.streams {
261            stream.create_directory()?;
262        }
263        commit_metadata(&prepared.root, &prepared.metadata_path, &prepared.metadata)?;
264        let manifest = Arc::new(RecordingManifest::new(
265            prepared.root.clone(),
266            prepared.metadata_path,
267            prepared.metadata,
268        ));
269        Self::start_new_prepared(prepared.descriptor, prepared.streams, manifest, lease)
270    }
271
272    /// Offers the current live state to every configured sampling stream.
273    ///
274    /// The writer first reads only the state's iteration. Streams that are
275    /// not due perform no field lookup, payload borrow, serialization,
276    /// allocation, or queue operation. Every due stream encodes its selected
277    /// fields before bounded queue admission, so backpressure retains only
278    /// owned bytes and never extends a scientific payload borrow.
279    ///
280    /// # Errors
281    ///
282    /// Returns state or payload serialization errors from a due stream,
283    /// queue-limit and ordering errors, or the writer's authoritative terminal
284    /// failure.
285    pub(crate) fn observe_state(&mut self, state: &SystemState) -> Result<(), PersistenceError> {
286        let observations = self
287            .session
288            .observe(state)
289            .map_err(|source| PersistenceError::Observation { source })?;
290        let writer = self
291            .writer
292            .as_ref()
293            .expect("an active recording owns its writer worker");
294        submit_observations(writer, observations)?;
295        Ok(())
296    }
297
298    /// Drains every stream, seals all chunks, and atomically publishes complete
299    /// metadata.
300    ///
301    /// The method consumes the coordinator, making repeated finish or sampling
302    /// impossible in safe Rust. If a writer fails, all remaining writers are
303    /// still drained and a best-effort failed metadata transition is attempted
304    /// before the originating writer error is returned.
305    #[cfg(test)]
306    pub(crate) fn complete_recording(self) -> Result<(), PersistenceError> {
307        self.complete_recording_with_terminal_metadata(Map::new())
308    }
309
310    /// Completes the recording and atomically commits values known only at the
311    /// terminal boundary.
312    ///
313    /// Terminal values are stored separately from immutable creation-time user
314    /// metadata and therefore cannot silently replace configuration parameters.
315    pub(crate) fn complete_recording_with_terminal_metadata(
316        mut self,
317        terminal_metadata: Map<String, Value>,
318    ) -> Result<(), PersistenceError> {
319        if let Err(error) = self.finish_writer() {
320            let _ = self.transition_terminal(
321                RecordingStatus::Failed {
322                    message: error.to_string(),
323                },
324                Map::new(),
325            );
326            return Err(error);
327        }
328        self.transition_terminal(RecordingStatus::Complete, terminal_metadata)
329    }
330
331    /// Records one final state to every stream exactly once, then completes.
332    ///
333    /// This terminal observation is independent of the sampling interval. A stream
334    /// already recorded at the same iteration is skipped, while a non-aligned final
335    /// iteration is encoded once. The writer therefore owns both interval-based and
336    /// terminal sampling decisions; the simulation supplies only a borrowed state.
337    pub(crate) fn complete_recording_with_final_state(
338        mut self,
339        state: &SystemState,
340        terminal_metadata: Map<String, Value>,
341    ) -> Result<(), PersistenceError> {
342        if let Err(error) = self.record_final_state(state) {
343            let _ = self.mark_recording_failed(error.to_string());
344            return Err(error);
345        }
346        self.complete_recording_with_terminal_metadata(terminal_metadata)
347    }
348
349    /// Encodes the supplied terminal state for streams that lack this iteration.
350    pub(crate) fn record_final_state(
351        &mut self,
352        state: &SystemState,
353    ) -> Result<(), PersistenceError> {
354        let observations = self
355            .session
356            .observe_final(state)
357            .map_err(|source| PersistenceError::Observation { source })?;
358        let writer = self
359            .writer
360            .as_ref()
361            .expect("an active recording owns its writer worker");
362        submit_observations(writer, observations)?;
363        Ok(())
364    }
365
366    /// Drains every stream and atomically records an intentional failed run.
367    ///
368    /// This is appropriate when the simulation itself fails after storage has
369    /// started. The supplied message is structural recording metadata and must not be
370    /// empty or whitespace-only. Successfully accepted records remain as
371    /// immutable chunks and are listed in the failed metadata, but
372    /// [`StoredStateSeriesReader`] deliberately reconstructs only completed runs.
373    ///
374    /// If a writer also fails, its error takes precedence as the returned and
375    /// persisted reason; the caller's message would no longer describe the
376    /// authoritative storage termination.
377    pub(crate) fn mark_recording_failed(
378        self,
379        message: impl Into<String>,
380    ) -> Result<(), PersistenceError> {
381        self.mark_recording_failed_with_terminal_metadata(message, Map::new())
382    }
383
384    /// Records an intentional failure with terminal-only user metadata.
385    pub(crate) fn mark_recording_failed_with_terminal_metadata(
386        mut self,
387        message: impl Into<String>,
388        terminal_metadata: Map<String, Value>,
389    ) -> Result<(), PersistenceError> {
390        let message = message.into();
391        if message.trim().is_empty() {
392            return Err(PersistenceError::InvalidConfiguration {
393                setting: "failure_message",
394                reason: "failed run message must not be empty".to_owned(),
395            });
396        }
397
398        if let Err(error) = self.finish_writer() {
399            let _ = self.transition_terminal(
400                RecordingStatus::Failed {
401                    message: error.to_string(),
402                },
403                Map::new(),
404            );
405            return Err(error);
406        }
407        self.transition_terminal(RecordingStatus::Failed { message }, terminal_metadata)
408    }
409
410    /// Spawns every empty writer after the initial manifest is durable.
411    fn start_new_prepared(
412        descriptor: BoundObservationPlan,
413        streams: Vec<StateStreamStorageConfig>,
414        manifest: Arc<RecordingManifest>,
415        lease: RecordingLease,
416    ) -> Result<Self, PersistenceError> {
417        let mut configs = Vec::with_capacity(streams.len());
418        configs.extend(streams);
419        let writer = StateWriterWorker::start_new_recording(configs, Arc::clone(&manifest))?;
420        Ok(Self {
421            manifest,
422            session: ObservationSession::new(descriptor),
423            writer: Some(writer),
424            session_started: Instant::now(),
425            _lease: lease,
426        })
427    }
428
429    /// Drains and joins the recording's sole queued writer worker.
430    fn finish_writer(&mut self) -> Result<(), PersistenceError> {
431        let Some(writer) = self.writer.take() else {
432            return Ok(());
433        };
434        writer.finish_recording()
435    }
436
437    /// Commits one terminal status, timestamp, duration, and metadata map.
438    fn transition_terminal(
439        &self,
440        status: RecordingStatus,
441        terminal_metadata: Map<String, Value>,
442    ) -> Result<(), PersistenceError> {
443        let finalized_at_utc =
444            utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
445                operation: "finalize recording",
446                source,
447            })?;
448        let active_duration_ns = duration_nanoseconds(self.session_started.elapsed())
449            .ok_or(PersistenceError::OperationalDurationOverflow)?;
450        self.manifest.transition_terminal(
451            status,
452            finalized_at_utc,
453            active_duration_ns,
454            terminal_metadata,
455        )
456    }
457}
458
459/// Fully validated builder output before any writer thread starts.
460struct PreparedRecording {
461    root: PathBuf,
462    metadata_path: PathBuf,
463    descriptor: BoundObservationPlan,
464    metadata: RecordingMetadata,
465    streams: Vec<StateStreamStorageConfig>,
466}
467
468impl PreparedRecording {
469    /// Builds persisted metadata from one already-bound observation plan.
470    fn new(
471        root: PathBuf,
472        descriptor: BoundObservationPlan,
473        user_metadata: Map<String, Value>,
474        storage: StateStreamStorage,
475    ) -> Result<Self, PersistenceError> {
476        let metadata_path = root.join(METADATA_FILE);
477        let stored_time = StoredTimeAxis {
478            iteration_name: "iteration".to_owned(),
479            iteration_unit: descriptor.iteration_unit().map(str::to_owned),
480            physical_time_name: Some("physical_time".to_owned()),
481            physical_time_unit: descriptor.physical_time_unit().map(str::to_owned),
482        };
483        let mut streams = Vec::with_capacity(descriptor.streams().len());
484        let mut declarations = Vec::with_capacity(descriptor.streams().len());
485
486        for (index, stream) in descriptor.streams().iter().enumerate() {
487            let stream: &BoundObservationStream = stream;
488            let directory = format!("stream_{index:04}");
489            let sampling_interval = SamplingInterval::iterations(stream.every_iterations())
490                .expect("bound observation streams contain positive sampling intervals");
491            let fields = stream
492                .fields()
493                .iter()
494                .map(|field| StateFieldMetadata {
495                    name: field.name().to_owned(),
496                    description: field.description().map(str::to_owned),
497                })
498                .collect::<Vec<_>>();
499            declarations.push(StateStreamMetadata {
500                name: stream.name().to_owned(),
501                directory: directory.clone(),
502                sampling_interval,
503                fields,
504                storage,
505                chunks: Vec::new(),
506            });
507            streams.push(StateStreamStorageConfig::new(
508                stream.name(),
509                root.join(&directory),
510                storage,
511            )?);
512        }
513
514        let created_at_utc =
515            utc_now_rfc3339().map_err(|source| PersistenceError::OperationalTimestamp {
516                operation: "create recording",
517                source,
518            })?;
519        let metadata =
520            RecordingMetadata::running(stored_time, user_metadata, declarations, created_at_utc);
521        metadata.validate(&metadata_path)?;
522        Ok(Self {
523            root,
524            metadata_path,
525            descriptor,
526            metadata,
527            streams,
528        })
529    }
530}
531
532fn submit_observations(
533    writer: &StateWriterWorker,
534    observations: Vec<EncodedObservation>,
535) -> Result<(), PersistenceError> {
536    for observation in observations {
537        let (stream, time, bytes) = observation.into_parts();
538        writer.submit_record(stream, EncodedStateRecord::new(time, bytes))?;
539    }
540    Ok(())
541}
542
543/// Serialized authority over the sole mutable metadata document.
544///
545/// Every worker shares this small coordinator. A transaction clones metadata,
546/// validates and persists the candidate, then replaces the in-memory snapshot
547/// only after the atomic filesystem commit succeeds.
548pub(crate) struct RecordingManifest {
549    root: PathBuf,
550    path: PathBuf,
551    metadata: Mutex<RecordingMetadata>,
552}
553
554impl RecordingManifest {
555    /// Creates an authority from the exact snapshot already present on disk.
556    fn new(root: PathBuf, path: PathBuf, metadata: RecordingMetadata) -> Self {
557        Self {
558            root,
559            path,
560            metadata: Mutex::new(metadata),
561        }
562    }
563
564    /// Appends one prepared descriptor and commits it before filename sealing.
565    pub(crate) fn prepare_chunk(
566        &self,
567        stream: &str,
568        descriptor: jsonl_format::ChunkMetadata,
569    ) -> Result<(), PersistenceError> {
570        let mut current = lock_metadata(&self.metadata);
571        if !matches!(current.status, RecordingStatus::Running) {
572            return Err(PersistenceError::RecordingFinished);
573        }
574        let mut candidate = current.clone();
575        let declaration =
576            candidate
577                .stream_mut(stream)
578                .ok_or_else(|| PersistenceError::UnknownStateStream {
579                    stream: stream.to_owned(),
580                })?;
581        let expected = u64::try_from(declaration.chunks.len()).map_err(|_| {
582            PersistenceError::ByteCountOverflow {
583                stream: stream.to_owned(),
584            }
585        })?;
586        if descriptor.ordinal != expected {
587            return Err(PersistenceError::InvalidMetadata {
588                path: self.path.clone(),
589                reason: format!(
590                    "stream `{stream}` prepared chunk ordinal {}, expected {expected}",
591                    descriptor.ordinal
592                ),
593            });
594        }
595        declaration.chunks.push(descriptor);
596        commit_metadata(&self.root, &self.path, &candidate)?;
597        *current = candidate;
598        Ok(())
599    }
600
601    /// Atomically commits terminal lifecycle, timing, and user metadata.
602    fn transition_terminal(
603        &self,
604        status: RecordingStatus,
605        finalized_at_utc: String,
606        active_duration_ns: u64,
607        terminal_metadata: Map<String, Value>,
608    ) -> Result<(), PersistenceError> {
609        let mut current = lock_metadata(&self.metadata);
610        let mut candidate = current.clone();
611        candidate.status = status;
612        candidate.timing.finalized_at_utc = Some(finalized_at_utc);
613        candidate.timing.active_duration_ns = candidate
614            .timing
615            .active_duration_ns
616            .checked_add(active_duration_ns)
617            .ok_or(PersistenceError::OperationalDurationOverflow)?;
618        candidate.terminal_metadata = terminal_metadata;
619        commit_metadata(&self.root, &self.path, &candidate)?;
620        *current = candidate;
621        Ok(())
622    }
623}
624
625/// Advisory exclusive ownership of the output root directory itself.
626///
627/// Locking the directory handle creates no lockfile or status artifact and the
628/// operating system releases the lease automatically after process death.
629struct RecordingLease {
630    directory: File,
631}
632
633impl RecordingLease {
634    /// Acquires non-blocking exclusive writer ownership.
635    fn acquire(root: &Path) -> Result<Self, PersistenceError> {
636        let directory = File::open(root).map_err(|source| PersistenceError::Io {
637            operation: "open output root for exclusive ownership",
638            path: root.to_path_buf(),
639            source,
640        })?;
641        match FileExt::try_lock_exclusive(&directory) {
642            Ok(()) => Ok(Self { directory }),
643            Err(source) if source.kind() == std::io::ErrorKind::WouldBlock => {
644                Err(PersistenceError::RecordingDirectoryInUse {
645                    path: root.to_path_buf(),
646                })
647            }
648            Err(source) => Err(PersistenceError::Io {
649                operation: "acquire exclusive output ownership",
650                path: root.to_path_buf(),
651                source,
652            }),
653        }
654    }
655}
656
657impl Drop for RecordingLease {
658    fn drop(&mut self) {
659        // Release explicitly instead of relying on file-descriptor teardown.
660        // Several recording attempts can occur back-to-back in one process,
661        // and the next attempt must never observe the previous lease.
662        let _ = FileExt::unlock(&self.directory);
663    }
664}
665
666/// Locks the metadata snapshot while recovering from a participant panic.
667fn lock_metadata(metadata: &Mutex<RecordingMetadata>) -> MutexGuard<'_, RecordingMetadata> {
668    metadata
669        .lock()
670        .unwrap_or_else(|poisoned| poisoned.into_inner())
671}
672
673/// Rejects every existing filesystem object and preserves IO inspection errors.
674fn ensure_absent(root: &Path) -> Result<(), PersistenceError> {
675    match root.try_exists() {
676        Ok(false) => Ok(()),
677        Ok(true) => Err(PersistenceError::RecordingDirectoryExists {
678            path: root.to_path_buf(),
679        }),
680        Err(source) => Err(PersistenceError::Io {
681            operation: "inspect output root",
682            path: root.to_path_buf(),
683            source,
684        }),
685    }
686}
687
688/// Exclusively creates the run root, closing the check/create race safely.
689fn create_root(root: &Path) -> Result<(), PersistenceError> {
690    if let Some(parent) = root.parent() {
691        fs::create_dir_all(parent).map_err(|source| PersistenceError::Io {
692            operation: "create recording parent directories",
693            path: parent.to_path_buf(),
694            source,
695        })?;
696    }
697    match fs::create_dir(root) {
698        Ok(()) => Ok(()),
699        Err(source) if source.kind() == std::io::ErrorKind::AlreadyExists => {
700            Err(PersistenceError::RecordingDirectoryExists {
701                path: root.to_path_buf(),
702            })
703        }
704        Err(source) => Err(PersistenceError::Io {
705            operation: "create output root",
706            path: root.to_path_buf(),
707            source,
708        }),
709    }
710}
711
712/// Atomically replaces the sole authoritative metadata document.
713///
714/// The temporary file is created exclusively, serialized once, flushed with
715/// `sync_all`, renamed over the previous snapshot, and followed by a directory
716/// sync. A failed attempt removes only its precisely owned temporary path when
717/// possible; the previous authoritative metadata remains untouched until the
718/// rename succeeds.
719fn commit_metadata(
720    root: &Path,
721    metadata_path: &Path,
722    metadata: &RecordingMetadata,
723) -> Result<(), PersistenceError> {
724    metadata.validate(metadata_path)?;
725    let mut bytes =
726        serde_json::to_vec_pretty(metadata).map_err(|source| PersistenceError::Json {
727            operation: "serialize metadata",
728            path: metadata_path.to_path_buf(),
729            source,
730        })?;
731    bytes.push(b'\n');
732
733    let temporary_path = root.join(METADATA_TEMP_FILE);
734    let result = write_and_replace_metadata(root, metadata_path, &temporary_path, &bytes);
735    if result.is_err() {
736        let _ = fs::remove_file(&temporary_path);
737    }
738    result
739}
740
741/// Performs the fallible filesystem portion of one metadata transaction.
742fn write_and_replace_metadata(
743    root: &Path,
744    metadata_path: &Path,
745    temporary_path: &Path,
746    bytes: &[u8],
747) -> Result<(), PersistenceError> {
748    let mut temporary = OpenOptions::new()
749        .write(true)
750        .create_new(true)
751        .open(temporary_path)
752        .map_err(|source| PersistenceError::Io {
753            operation: "create temporary metadata",
754            path: temporary_path.to_path_buf(),
755            source,
756        })?;
757    temporary
758        .write_all(bytes)
759        .map_err(|source| PersistenceError::Io {
760            operation: "write temporary metadata",
761            path: temporary_path.to_path_buf(),
762            source,
763        })?;
764    temporary
765        .sync_all()
766        .map_err(|source| PersistenceError::Io {
767            operation: "sync temporary metadata",
768            path: temporary_path.to_path_buf(),
769            source,
770        })?;
771    drop(temporary);
772
773    fs::rename(temporary_path, metadata_path).map_err(|source| PersistenceError::Io {
774        operation: "publish metadata",
775        path: metadata_path.to_path_buf(),
776        source,
777    })?;
778
779    File::open(root)
780        .and_then(|directory| directory.sync_all())
781        .map_err(|source| PersistenceError::Io {
782            operation: "sync output root",
783            path: root.to_path_buf(),
784            source,
785        })
786}