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