Skip to main content

scientific_workflow/state/
series.rs

1//! Owned in-memory collections of scientific system states.
2//!
3//! [`StateSeries`] is the analysis-facing growable array for complete
4//! [`SystemState`] snapshots. It owns states, preserves one canonical
5//! [`SystemStateSchema`], and maintains strictly increasing state iterations.
6//!
7//! # Scope
8//!
9//! This module performs no sampling, serialization, decoding, filesystem IO,
10//! chunking, or queue management. Runtime sends borrowed observations to
11//! persistence; a `StateSeries` is instead built when an application or reader
12//! wants an owned collection for analysis.
13//!
14//! # Ownership and cloning
15//!
16//! Successful [`StateSeries::push_state`] calls move a complete state into the
17//! backing `Vec`. [`StateSeries::pop_state`], [`StateSeries::into_states`], and owned
18//! iteration move those owners back out. None of these paths clones a payload.
19//! A rejected append returns [`StateSeriesPushError`], which retains the unchanged state.
20//!
21//! Explicitly cloning a `StateSeries` is intentionally expensive: every
22//! populated payload is deep-cloned through [`SystemState::clone`]. Prefer a
23//! borrowed `&StateSeries` for scoped immutable access or an application-owned
24//! `Arc<StateSeries>` when shared ownership is required.
25//!
26//! # Invariants
27//!
28//! Every accepted state must:
29//!
30//! - share the exact immutable layout allocation held by the series; and
31//! - have an iteration greater than the current final iteration.
32//!
33//! Iteration gaps are valid. Optional physical time does not determine
34//! ordering. The module never exposes `&mut SystemState`, because callers could
35//! otherwise change time or replace structural state behind the collection's
36//! validation boundary. [`StateSeries::payload_mut_at`] permits mutation of one
37//! payload while leaving those invariants inaccessible.
38
39use std::any::Any;
40use std::error::Error;
41use std::fmt;
42
43use super::error::StateSeriesError;
44use super::schema::{StateSchemaAccess, SystemStateSchema};
45use super::state::SystemState;
46
47/// A growable homogeneous array of owned, time-ordered system states.
48///
49/// `spec` remains present even when the collection is empty, so later appends
50/// can be checked with constant-time layout identity. Each stored state carries
51/// its own cheap handle to the same immutable layout allocation and therefore
52/// remains independently valid after removal from the series. Like its owned
53/// states, a series is `Send` but not `Sync`; shared cross-thread ownership
54/// requires external synchronization.
55pub struct StateSeries {
56    spec: SystemStateSchema,
57    states: Vec<SystemState>,
58}
59
60impl StateSeries {
61    /// Creates an empty series with no state capacity reserved.
62    ///
63    /// This stores the supplied specification handle but allocates no state or
64    /// payload storage. Use [`StateSeries::with_capacity`] when an analysis or
65    /// reader already knows an approximate state count.
66    pub fn new(spec: SystemStateSchema) -> Self {
67        Self {
68            spec,
69            states: Vec::new(),
70        }
71    }
72
73    /// Creates an empty series with capacity for at least `capacity` states.
74    ///
75    /// The reservation covers only `SystemState` owners in the backing vector.
76    /// It does not create states, duplicate the shared layout, or allocate any
77    /// scientific payload.
78    pub fn with_capacity(spec: SystemStateSchema, capacity: usize) -> Self {
79        Self {
80            spec,
81            states: Vec::with_capacity(capacity),
82        }
83    }
84
85    /// Returns the canonical immutable specification for this collection.
86    pub fn schema(&self) -> &SystemStateSchema {
87        &self.spec
88    }
89
90    /// Returns the number of states currently owned by the collection.
91    pub fn len(&self) -> usize {
92        self.states.len()
93    }
94
95    /// Reports whether the collection currently owns no states.
96    pub fn is_empty(&self) -> bool {
97        self.states.is_empty()
98    }
99
100    /// Returns the backing vector's current state-owner capacity.
101    pub fn capacity(&self) -> usize {
102        self.states.capacity()
103    }
104
105    /// Reserves capacity for at least `additional` more state owners.
106    ///
107    /// Existing states and their payload allocations remain logically
108    /// unchanged. As with [`Vec::reserve`], the allocator may reserve more than
109    /// the exact requested amount.
110    pub fn reserve(&mut self, additional: usize) {
111        self.states.reserve(additional);
112    }
113
114    /// Returns one immutable state by zero-based collection position.
115    ///
116    /// This follows slice conventions and returns `None` when `position` is
117    /// outside the collection. The position is distinct from the state's
118    /// iteration because sampled iterations may contain gaps.
119    pub fn state_at(&self, position: usize) -> Option<&SystemState> {
120        self.states.get(position)
121    }
122
123    /// Mutably borrows one typed payload in one stored state.
124    ///
125    /// This is the collection's only mutable analysis boundary. It delegates
126    /// concrete type validation to [`SystemState::payload_mut`] but does not expose
127    /// the containing `SystemState`; callers therefore cannot change its time,
128    /// clear unrelated fields, or replace it with a foreign layout.
129    ///
130    /// Only one payload can be borrowed mutably at a time under ordinary Rust
131    /// borrowing rules. Applications requiring coupled mutation should group
132    /// the coupled values into one payload type.
133    ///
134    /// # Errors
135    ///
136    /// Returns [`StateSeriesError::PositionOutOfBounds`] when no state exists at
137    /// `position`. An unknown key, empty field, or concrete type mismatch is
138    /// returned as [`StateSeriesError::PayloadAccess`] with the original
139    /// [`StateError`](super::error::StateError) preserved as its source.
140    pub fn payload_mut_at<T>(
141        &mut self,
142        position: usize,
143        key: &str,
144    ) -> Result<&mut T, StateSeriesError>
145    where
146        T: Any,
147    {
148        let len = self.states.len();
149        let state = self
150            .states
151            .get_mut(position)
152            .ok_or(StateSeriesError::PositionOutOfBounds { position, len })?;
153
154        state
155            .payload_mut::<T>(key)
156            .map_err(|source| StateSeriesError::PayloadAccess { position, source })
157    }
158
159    /// Returns the earliest stored state, or `None` when the series is empty.
160    pub fn first_state(&self) -> Option<&SystemState> {
161        self.states.first()
162    }
163
164    /// Returns the latest stored state, or `None` when the series is empty.
165    pub fn last_state(&self) -> Option<&SystemState> {
166        self.states.last()
167    }
168
169    /// Returns every state as one immutable contiguous slice.
170    ///
171    /// No mutable slice is exposed because element replacement could bypass
172    /// both shared-layout validation and increasing-iteration validation.
173    pub fn as_state_slice(&self) -> &[SystemState] {
174        &self.states
175    }
176
177    /// Returns an iterator over immutable states in increasing iteration order.
178    pub fn iter(&self) -> std::slice::Iter<'_, SystemState> {
179        self.states.iter()
180    }
181
182    /// Appends one owned state after validating collection invariants.
183    ///
184    /// Success moves `state` directly into the backing vector without cloning
185    /// it or any payload. Failure returns [`StateSeriesPushError`] containing the complete
186    /// unchanged state, allowing the caller to recover expensive data without
187    /// cloning before the operation.
188    ///
189    /// # Errors
190    ///
191    /// - [`StateSeriesError::SchemaMismatch`] if `state` does not share the exact
192    ///   canonical layout allocation;
193    /// - [`StateSeriesError::NonIncreasingIteration`] if its iteration is not
194    ///   greater than the current final iteration.
195    pub fn push_state(&mut self, state: SystemState) -> Result<(), StateSeriesPushError> {
196        if !self.spec.shares_schema_instance(state.schema()) {
197            return Err(StateSeriesPushError::new(
198                StateSeriesError::SchemaMismatch {
199                    iteration: state.time().iteration(),
200                },
201                state,
202            ));
203        }
204
205        if let Some(previous) = self.last_state().map(|state| state.time().iteration()) {
206            let next = state.time().iteration();
207            if next <= previous {
208                return Err(StateSeriesPushError::new(
209                    StateSeriesError::NonIncreasingIteration { previous, next },
210                    state,
211                ));
212            }
213        }
214
215        self.states.push(state);
216        Ok(())
217    }
218
219    /// Removes and returns the latest state without cloning its payloads.
220    ///
221    /// A later append is compared with the new final state. Once empty, the
222    /// series accepts any iteration from a state sharing its layout.
223    pub fn pop_state(&mut self) -> Option<SystemState> {
224        self.states.pop()
225    }
226
227    /// Drops every state while retaining specification and vector capacity.
228    ///
229    /// Stored payloads are dropped with their owning states. This method is an
230    /// explicit analysis working-set operation and has no relationship to
231    /// writer rollover or persistent chunks.
232    pub fn clear_states(&mut self) {
233        self.states.clear();
234    }
235
236    /// Consumes the series and returns its complete state vector.
237    ///
238    /// The vector allocation, states, and payload allocations move unchanged.
239    /// Dropping the separate canonical specification handle is safe because
240    /// every returned state retains its own shared handle.
241    pub fn into_states(self) -> Vec<SystemState> {
242        self.states
243    }
244}
245
246impl Clone for StateSeries {
247    /// Creates a fully independent deep copy of all states and payloads.
248    ///
249    /// # Performance warning
250    ///
251    /// Cost scales with the complete populated payload volume and may involve
252    /// gigabytes of allocation and copying. This method is appropriate only
253    /// when analysis requires independent mutable payload ownership. Use
254    /// borrowing `&StateSeries` or an `Arc<StateSeries>` for lightweight sharing.
255    /// The immutable specification allocation remains shared.
256    fn clone(&self) -> Self {
257        Self {
258            spec: self.spec.clone(),
259            states: self.states.clone(),
260        }
261    }
262}
263
264impl fmt::Debug for StateSeries {
265    /// Formats bounded structural context without traversing payload values.
266    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
267        formatter
268            .debug_struct("StateSeries")
269            .field("source", &self.spec.template_path())
270            .field("states", &self.len())
271            .field(
272                "first_iteration",
273                &self.first_state().map(|state| state.time().iteration()),
274            )
275            .field(
276                "last_iteration",
277                &self.last_state().map(|state| state.time().iteration()),
278            )
279            .finish_non_exhaustive()
280    }
281}
282
283impl<'a> IntoIterator for &'a StateSeries {
284    type Item = &'a SystemState;
285    type IntoIter = std::slice::Iter<'a, SystemState>;
286
287    /// Iterates over borrowed states without exposing mutable replacement.
288    fn into_iter(self) -> Self::IntoIter {
289        self.iter()
290    }
291}
292
293impl IntoIterator for StateSeries {
294    type Item = SystemState;
295    type IntoIter = std::vec::IntoIter<SystemState>;
296
297    /// Consumes the series and moves each owned state out in iteration order.
298    fn into_iter(self) -> Self::IntoIter {
299        self.states.into_iter()
300    }
301}
302
303/// An append failure that preserves ownership of the rejected state.
304///
305/// This follows the ownership behavior of standard-library channel send
306/// errors: callers never need to clone expensive scientific data before an
307/// operation that may reject it. The state is boxed internally so
308/// `Result<(), StateSeriesPushError>` remains small on the successful hot path. The box is
309/// allocated only after validation fails.
310#[must_use = "the rejected SystemState remains owned by this error until recovered or dropped"]
311pub struct StateSeriesPushError {
312    error: StateSeriesError,
313    state: Box<SystemState>,
314}
315
316impl StateSeriesPushError {
317    /// Creates a failure-path owner for one unchanged rejected state.
318    fn new(error: StateSeriesError, state: SystemState) -> Self {
319        Self {
320            error,
321            state: Box::new(state),
322        }
323    }
324
325    /// Returns the collection invariant that rejected the state.
326    pub fn error(&self) -> &StateSeriesError {
327        &self.error
328    }
329
330    /// Returns the unchanged rejected state by shared reference.
331    pub fn state(&self) -> &SystemState {
332        &self.state
333    }
334
335    /// Consumes the error and returns its reason and original state.
336    ///
337    /// Moving the state out of its failure-only outer box does not clone the
338    /// state or any scientific payload allocation. The tuple follows borrowed
339    /// inspection order: error first, then state.
340    pub fn into_parts(self) -> (StateSeriesError, SystemState) {
341        (self.error, *self.state)
342    }
343}
344
345impl fmt::Debug for StateSeriesPushError {
346    /// Formats the reason and structural state context without payload values.
347    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
348        formatter
349            .debug_struct("StateSeriesPushError")
350            .field("error", &self.error)
351            .field("state", &self.state)
352            .finish_non_exhaustive()
353    }
354}
355
356impl fmt::Display for StateSeriesPushError {
357    /// Delegates user-facing formatting to the collection invariant failure.
358    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
359        fmt::Display::fmt(&self.error, formatter)
360    }
361}
362
363impl Error for StateSeriesPushError {
364    /// Exposes the underlying collection error for standard source traversal.
365    fn source(&self) -> Option<&(dyn Error + 'static)> {
366        Some(&self.error)
367    }
368}