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