Skip to main content

scientific_workflow/state/
error.rs

1//! Errors produced while defining and manipulating states.
2//!
3//! This module keeps the SystemState error surface in one place so template
4//! loading, layout validation, time advancement, and typed payload access
5//! report failures consistently. The variants are deliberately specific
6//! enough for callers to inspect programmatically while their display messages
7//! retain the field, path, or time context needed for logs.
8//!
9//! # Error sources
10//!
11//! Filesystem and JSON failures preserve their original errors through
12//! [`std::error::Error::source`]. Semantic template failures and state-access
13//! failures do not wrap another error because they are detected directly by
14//! this crate. Checked time-advance failures likewise retain their complete
15//! numeric context directly in [`StateError`].
16//!
17//! # Performance
18//!
19//! These errors are constructed only on failure paths. Owned paths and field
20//! names are retained to make an error independent of the state or template
21//! that produced it; successful state access does not allocate error context.
22//!
23//! # Ownership-preserving insertion failures
24//!
25//! [`PayloadInsertError`] is generic because it returns ownership of a payload that
26//! [`SystemState::insert_payload`](super::state::SystemState::insert_payload) could not accept. Its
27//! diagnostics deliberately omit the payload value, so scientific data does
28//! not need to implement [`Debug`](std::fmt::Debug) and is never traversed or
29//! copied merely to format an error.
30
31use std::error::Error;
32use std::fmt;
33use std::io;
34use std::path::PathBuf;
35
36use thiserror::Error;
37
38/// A failure encountered while defining, accessing, or advancing a state.
39///
40/// `StateError` is non-exhaustive because later workflow features may add
41/// validation failures without forcing downstream crates to update exhaustive
42/// matches. Callers should match variants of interest and retain a fallback
43/// arm.
44#[derive(Debug, Error)]
45#[non_exhaustive]
46pub enum StateError {
47    /// A JSON state template could not be read from the filesystem.
48    #[error("failed to read state template `{path}`")]
49    TemplateRead {
50        /// Path passed to the template loader.
51        path: PathBuf,
52        /// Underlying filesystem error.
53        #[source]
54        source: io::Error,
55    },
56
57    /// A state template was readable but did not contain valid JSON.
58    #[error("failed to parse state template `{path}` as JSON")]
59    TemplateParse {
60        /// Path of the malformed template.
61        path: PathBuf,
62        /// Underlying JSON syntax or data-model error.
63        #[source]
64        source: serde_json::Error,
65    },
66
67    /// A field definition used an empty or whitespace-only name.
68    #[error("state template field at index {index} has an empty name")]
69    EmptyFieldName {
70        /// Zero-based position of the invalid field in template order.
71        index: usize,
72    },
73
74    /// Two field definitions used the same name.
75    #[error("state template declares duplicate field `{field}`")]
76    DuplicateField {
77        /// Repeated field name.
78        field: String,
79    },
80
81    /// An operation addressed a key that is absent from the template layout.
82    #[error("state template does not declare field `{field}`")]
83    UnknownField {
84        /// Requested field name.
85        field: String,
86    },
87
88    /// One coordinated borrow requested the same resolved field more than once.
89    ///
90    /// Mutable aliases to one payload would violate Rust's exclusivity rules.
91    /// Immutable coordinated borrows reject the same input as well so
92    /// `SystemState::borrow_payloads` and `SystemState::borrow_payloads_mut` retain identical,
93    /// predictable request validation.
94    #[error("coordinated state borrow repeats field `{field}`")]
95    RepeatedPayloadBorrow {
96        /// Field name at the first repeated tuple position.
97        field: String,
98    },
99
100    /// An operation required a payload from a declared but currently empty
101    /// field.
102    #[error("state field `{field}` does not contain a payload")]
103    MissingPayload {
104        /// Declared field whose slot is empty.
105        field: String,
106    },
107
108    /// A typed operation requested a different Rust type from the retained
109    /// field contract.
110    #[error(
111        "state field `{field}` is bound to `{actual}`, but the operation requested `{expected}`"
112    )]
113    TypeMismatch {
114        /// Field on which the typed operation was attempted.
115        field: String,
116        /// Rust type requested by the caller.
117        expected: &'static str,
118        /// Rust type bound to the field during state assembly.
119        actual: &'static str,
120    },
121
122    /// Initial assembly attempted to bind an already initialized field.
123    ///
124    /// Use [`SystemState::insert_payload`](super::state::SystemState::insert_payload)
125    /// when replacement is deliberate. The incoming payload remains available
126    /// through [`PayloadInsertError`].
127    #[error("state field `{field}` has already been initialized")]
128    PayloadAlreadyInitialized {
129        /// Field whose retained type contract was already established.
130        field: String,
131    },
132
133    /// Incrementing the authoritative iteration would overflow `u64`.
134    ///
135    /// `SystemState::advance_time` will detect this condition before mutating the
136    /// state, so the original time point remains unchanged.
137    #[error("cannot advance state iteration {iteration}: the next iteration exceeds u64::MAX")]
138    IterationOverflow {
139        /// Current iteration that cannot be incremented.
140        iteration: u64,
141    },
142
143    /// A physical-time delta was requested for a state without a physical
144    /// coordinate.
145    ///
146    /// Absence is not interpreted as zero: callers must establish a known
147    /// origin explicitly before advancing physical time.
148    #[error(
149        "cannot advance physical time at iteration {iteration}: no physical coordinate is present"
150    )]
151    MissingPhysicalTime {
152        /// Iteration at which physical advancement was requested.
153        iteration: u64,
154    },
155
156    /// A physical-time delta or its sum with the current coordinate is not
157    /// finite.
158    ///
159    /// Both operands are retained for diagnosis. This variant covers a
160    /// non-finite input delta and finite operands whose addition overflows to
161    /// infinity. The state remains unchanged.
162    #[error(
163        "cannot advance physical time {current} by {delta}: the delta and resulting coordinate must be finite"
164    )]
165    InvalidPhysicalAdvance {
166        /// Current finite physical coordinate.
167        current: f64,
168        /// Requested delta, which may itself be non-finite.
169        delta: f64,
170    },
171}
172
173/// A failure produced while maintaining or mutating an in-memory state series.
174#[derive(Debug, Error)]
175#[non_exhaustive]
176pub enum StateSeriesError {
177    /// The rejected state does not share the series' canonical schema instance.
178    #[error("state at iteration {iteration} does not share the series schema")]
179    SchemaMismatch {
180        /// Iteration carried by the rejected state.
181        iteration: u64,
182    },
183
184    /// The rejected state would violate strictly increasing iteration order.
185    #[error("state iteration {next} must be greater than the previous iteration {previous}")]
186    NonIncreasingIteration {
187        /// Iteration of the series' current final state.
188        previous: u64,
189        /// Iteration carried by the rejected state.
190        next: u64,
191    },
192
193    /// A mutable analysis request selected no stored state.
194    #[error("state-series position {position} is out of bounds for length {len}")]
195    PositionOutOfBounds {
196        /// Zero-based series position requested by the caller.
197        position: usize,
198        /// Number of states stored when the request was evaluated.
199        len: usize,
200    },
201
202    /// Typed mutable access failed inside the selected state.
203    #[error("cannot access state-series position {position}: {source}")]
204    PayloadAccess {
205        /// Zero-based position of the selected state.
206        position: usize,
207        /// Original typed state access failure.
208        #[source]
209        source: StateError,
210    },
211}
212
213/// A failed [`SystemState::insert_payload`](super::state::SystemState::insert_payload) operation that
214/// retains ownership of the unchanged incoming payload.
215///
216/// A set operation can fail before moving `payload` into a state because the
217/// requested field is undeclared or because its assembly-retained type contract
218/// names a different concrete Rust type. The latter remains true even when the
219/// field is temporarily empty after `take` or `clear`. Returning only
220/// [`StateError`] in those cases would drop the caller's payload while unwinding
221/// the failed call. `PayloadInsertError` instead keeps the rejection reason and original
222/// `T` together, following the ownership-preserving pattern of channel send
223/// errors.
224///
225/// The payload remains private so diagnostics cannot accidentally expose or
226/// traverse large scientific data. Borrow it through [`PayloadInsertError::payload`] or
227/// recover ownership of both components through [`PayloadInsertError::into_parts`].
228/// Neither operation invokes [`Clone`].
229///
230/// # Formatting
231///
232/// [`Display`](fmt::Display) delegates to the contained [`StateError`]. The
233/// bounded [`Debug`](fmt::Debug) representation includes only that error and
234/// the compile-time Rust type name of `T`; it never requires `T: Debug` or
235/// formats the payload value.
236#[must_use = "the rejected payload remains owned by this error until it is recovered or dropped"]
237pub struct PayloadInsertError<T> {
238    error: StateError,
239    payload: T,
240}
241
242impl<T> PayloadInsertError<T> {
243    /// Creates an ownership-preserving set rejection.
244    ///
245    /// This constructor is crate-private because only SystemState validation
246    /// may determine that a payload was rejected. Public callers receive a
247    /// `PayloadInsertError<T>` from [`SystemState::insert_payload`](super::state::SystemState::insert_payload)
248    /// and recover its contents through the accessors below.
249    pub(crate) const fn new(error: StateError, payload: T) -> Self {
250        Self { error, payload }
251    }
252
253    /// Returns the state-validation error that rejected the payload.
254    ///
255    /// Borrowing the reason leaves the incoming payload owned by this error,
256    /// allowing callers to inspect the failure before deciding how to recover
257    /// or dispose of the scientific data.
258    pub const fn error(&self) -> &StateError {
259        &self.error
260    }
261
262    /// Returns the unchanged rejected payload by shared reference.
263    ///
264    /// The returned reference points to the same concrete `T` moved into
265    /// [`SystemState::insert_payload`](super::state::SystemState::insert_payload). No payload clone,
266    /// serialization, downcast, or backing-buffer copy occurs.
267    pub const fn payload(&self) -> &T {
268        &self.payload
269    }
270
271    /// Consumes the rejection and returns its reason and original payload.
272    ///
273    /// The tuple is ordered as `(StateError, T)`, matching the borrowed
274    /// [`PayloadInsertError::error`] then [`PayloadInsertError::payload`] inspection order. The
275    /// payload moves directly out of the error and retains its original owned
276    /// allocations.
277    pub fn into_parts(self) -> (StateError, T) {
278        (self.error, self.payload)
279    }
280}
281
282impl<T> fmt::Debug for PayloadInsertError<T> {
283    /// Formats bounded diagnostic context without requiring or inspecting
284    /// `T: Debug`.
285    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
286        formatter
287            .debug_struct("PayloadInsertError")
288            .field("error", &self.error)
289            .field("payload_type", &std::any::type_name::<T>())
290            .finish_non_exhaustive()
291    }
292}
293
294impl<T> fmt::Display for PayloadInsertError<T> {
295    /// Delegates the user-facing message to the state-validation reason.
296    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
297        fmt::Display::fmt(&self.error, formatter)
298    }
299}
300
301impl<T> Error for PayloadInsertError<T> {
302    /// Exposes the contained [`StateError`] for standard error-chain traversal.
303    fn source(&self) -> Option<&(dyn Error + 'static)> {
304        Some(&self.error)
305    }
306}