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