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