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