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