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