Skip to main content

scientific_workflow/state/
state.rs

1//! Fixed-layout, heterogeneous values at one state time.
2//!
3//! [`SystemState`] is the public typed access boundary over the private
4//! [`StateValue`] erasure layer. Every state owns its
5//! payloads, while all states derived from one [`SystemStateSchema`] share immutable
6//! field metadata and name lookup tables.
7//!
8//! # Layout invariant
9//!
10//! The slot vector always has exactly one entry per field declared by the
11//! specification. A slot may be empty, but fields cannot be added, removed, or
12//! reordered after template loading. The first successful initialization binds a
13//! slot to that payload's concrete Rust type. Taking or clearing the payload
14//! retains this type contract, and [`SystemState::clone_structure_without_payloads`] carries all contracts
15//! into the derived blank state without cloning payloads.
16//!
17//! # Ownership and cloning
18//!
19//! `initialize_payload` and `insert_payload` consume payloads without cloning
20//! them. Initial insertion returns `None`, replacement returns ownership of the
21//! previous same-typed payload, and rejection returns ownership of the
22//! unchanged incoming payload through [`PayloadInsertError`]. `take_payload`
23//! moves a stored payload back to the caller. These operations preserve the
24//! backing allocations of ordinary scientific owners such as `Vec<T>` and
25//! tensor containers.
26//!
27//! Explicitly cloning a `SystemState` is different: it shares the immutable
28//! specification and invokes `Clone` for every populated payload. Each payload
29//! type determines whether its backing storage is copied or shared. Independent
30//! scientific branches require clone semantics that isolate later mutations.
31//! Persistence should borrow a live state during synchronous serialization.
32//!
33//! # Mutation
34//!
35//! The owning simulation can replace, borrow mutably, extract, or clear every
36//! payload. [`SystemState::borrow_payloads`] and [`SystemState::borrow_payloads_mut`] grant
37//! coordinated access to distinct heterogeneous fields through type and name
38//! tuples, allowing one validated borrow to surround an entire scientific
39//! kernel. It can advance time transactionally through
40//! [`SystemState::advance_time`]; specialized lifecycle code can replace a complete
41//! coordinate through [`SystemState::replace_time`].
42//!
43//! # Type safety
44//!
45//! Typed access uses Rust's exact runtime [`TypeId`]. A type
46//! mismatch reports both type names. `take` validates the retained slot type
47//! before removing its owner, so an incorrect request cannot temporarily empty
48//! or discard scientific data.
49//!
50//! # Serialization capability
51//!
52//! New payloads must implement Serde [`Serialize`]. A crate-private accessor
53//! exposes that existing implementation as a borrowed erased trait object for
54//! the storage encoder. `SystemState` itself does not select JSON, frame
55//! records, or perform IO.
56
57use std::any::{Any, TypeId, type_name};
58use std::fmt;
59
60use serde::Serialize;
61
62use super::error::{PayloadInsertError, StateError};
63use super::schema::SystemStateSchema;
64use super::time::StateTime;
65use super::value::StateValue;
66
67/// A heterogeneous collection of payloads describing one system time point.
68///
69/// Fields are declared by a JSON-derived [`SystemStateSchema`]. Values are addressed
70/// by those field names but stored in compact optional slots. The type-erased
71/// representation remains private; callers always insert, borrow, mutate, and
72/// extract concrete Rust types. An owned state is `Send` but not `Sync`; shared
73/// cross-thread ownership requires an external synchronization boundary.
74pub struct SystemState {
75    spec: SystemStateSchema,
76    time: StateTime,
77    slots: Vec<StateSlot>,
78}
79
80/// One fixed state field's retained type contract and optional payload.
81///
82/// A JSON template creates an unbound slot. The first accepted payload records
83/// its exact runtime type independently from the optional owner, allowing an
84/// emptied slot and every state derived from it to reject accidental retyping.
85/// This structure is private because callers interact only with concrete types
86/// through [`SystemState`].
87#[derive(Clone)]
88struct StateSlot {
89    definition: Option<ValueType>,
90    value: Option<StateValue>,
91}
92
93impl StateSlot {
94    /// Creates a payload-empty slot without a concrete type contract.
95    const fn unbound() -> Self {
96        Self {
97            definition: None,
98            value: None,
99        }
100    }
101
102    /// Creates a payload-empty slot retaining this slot's type contract.
103    const fn empty_like(&self) -> Self {
104        Self {
105            definition: self.definition,
106            value: None,
107        }
108    }
109}
110
111/// Copyable runtime identity retained after a slot's payload is removed.
112#[derive(Clone, Copy)]
113struct ValueType {
114    id: TypeId,
115    name: &'static str,
116}
117
118impl ValueType {
119    /// Captures the exact runtime identity and diagnostic name of `T`.
120    fn of<T>() -> Self
121    where
122        T: Any,
123    {
124        Self {
125            id: TypeId::of::<T>(),
126            name: type_name::<T>(),
127        }
128    }
129
130    /// Reports whether this definition names the exact concrete type `T`.
131    fn is<T>(self) -> bool
132    where
133        T: Any,
134    {
135        self.id == TypeId::of::<T>()
136    }
137}
138
139impl SystemState {
140    /// Creates an empty state from a validated specification.
141    ///
142    /// This constructor is crate-private so an external caller cannot create a
143    /// state without first loading a template. [`SystemStateSchema::create_empty_state`] is the
144    /// public initial construction path.
145    pub(crate) fn new(spec: SystemStateSchema, time: StateTime) -> Self {
146        let slots = (0..spec.len()).map(|_| StateSlot::unbound()).collect();
147        Self { spec, time, slots }
148    }
149
150    /// Returns this state's temporal coordinate.
151    pub const fn time(&self) -> StateTime {
152        self.time
153    }
154
155    /// Advances the iteration by one after one completed execution-unit step.
156    ///
157    /// Passing `None` increments only the authoritative iteration and
158    /// preserves the current optional physical coordinate. Passing
159    /// `Some(delta)` additionally requires an existing physical coordinate,
160    /// a finite `delta`, and a finite sum. Negative and zero finite deltas are
161    /// valid because iteration—not physical time—defines record ordering.
162    ///
163    /// On success, the new [`StateTime`] is stored and returned. All validation
164    /// occurs before assignment, so every error leaves the original time point
165    /// unchanged.
166    ///
167    /// # Errors
168    ///
169    /// Returns:
170    ///
171    /// - [`StateError::IterationOverflow`] when the current iteration is
172    ///   `u64::MAX`;
173    /// - [`StateError::MissingPhysicalTime`] when a delta is supplied but the
174    ///   current state has no physical coordinate;
175    /// - [`StateError::InvalidPhysicalAdvance`] when the delta or resulting
176    ///   coordinate is not finite.
177    pub fn advance_time(
178        &mut self,
179        physical_time_increment: Option<f64>,
180    ) -> Result<StateTime, StateError> {
181        let next = self.time.checked_advance(physical_time_increment)?;
182        self.time = next;
183        Ok(next)
184    }
185
186    /// Returns the shared immutable field specification.
187    pub const fn schema(&self) -> &SystemStateSchema {
188        &self.spec
189    }
190
191    /// Reports whether a declared field currently contains a payload.
192    ///
193    /// # Errors
194    ///
195    /// Returns [`StateError::UnknownField`] when `key` was not declared by the
196    /// JSON template.
197    pub fn contains_payload(&self, key: &str) -> Result<bool, StateError> {
198        let index = self.spec.index_of(key)?;
199        Ok(self.slots[index].value.is_some())
200    }
201
202    /// Initializes one declared field and establishes its concrete Rust type.
203    ///
204    /// This is the assembly-oriented operation: it succeeds exactly once per
205    /// field and never silently replaces a value. Every failure preserves the
206    /// unchanged incoming payload in [`PayloadInsertError`].
207    pub fn initialize_payload<T>(
208        &mut self,
209        key: &str,
210        payload: T,
211    ) -> Result<(), PayloadInsertError<T>>
212    where
213        T: Serialize + Clone + Send + 'static,
214    {
215        let index = match self.spec.index_of(key) {
216            Ok(index) => index,
217            Err(error) => return Err(PayloadInsertError::new(error, payload)),
218        };
219        let slot = &mut self.slots[index];
220        if slot.definition.is_some() {
221            return Err(PayloadInsertError::new(
222                StateError::PayloadAlreadyInitialized {
223                    field: key.to_owned(),
224                },
225                payload,
226            ));
227        }
228        slot.definition = Some(ValueType::of::<T>());
229        slot.value = Some(StateValue::new(payload));
230        Ok(())
231    }
232
233    /// Sets or replaces a payload while preserving ownership on every outcome.
234    ///
235    /// `payload` moves into this operation and is never cloned:
236    ///
237    /// - a never-populated declared slot binds itself to `T`, receives the
238    ///   payload, and returns `Ok(None)`;
239    /// - a slot bound to exactly `T` receives it and returns the displaced
240    ///   payload as `Ok(Some(previous))`, or `Ok(None)` when currently empty;
241    /// - an undeclared key returns `Err(PayloadInsertError<T>)` containing the unchanged
242    ///   incoming payload;
243    /// - a slot bound to another concrete type remains unchanged and returns
244    ///   the incoming payload in `PayloadInsertError<T>`, even when its payload is empty.
245    ///
246    /// Returning a previous payload is deliberate assignment behavior. A
247    /// caller that does not need that owner should discard it explicitly:
248    ///
249    /// ```no_run
250    /// # use scientific_workflow::state::{SystemStateSchema, StateTime};
251    /// # fn example(spec: &SystemStateSchema) -> Result<(), Box<dyn std::error::Error>> {
252    /// let mut state = spec.create_empty_state(StateTime::from_iteration(0));
253    /// drop(state.insert_payload("population", vec![1_u64, 2, 3])?);
254    /// # Ok(())
255    /// # }
256    /// ```
257    ///
258    /// Type-contract validation occurs before the slot is changed.
259    /// Consequently, rejection cannot discard or temporarily remove an
260    /// existing scientific value, and `take` or `clear` cannot reopen a field
261    /// for a different type.
262    ///
263    /// # Errors
264    ///
265    /// Returns [`PayloadInsertError`] containing:
266    ///
267    /// - [`StateError::UnknownField`] when `key` is undeclared;
268    /// - [`StateError::TypeMismatch`] when the slot is bound to a different
269    ///   concrete Rust type.
270    ///
271    /// In both cases [`PayloadInsertError::into_parts`] recovers the unchanged incoming
272    /// `T` without cloning it.
273    pub fn insert_payload<T>(
274        &mut self,
275        key: &str,
276        payload: T,
277    ) -> Result<Option<T>, PayloadInsertError<T>>
278    where
279        T: Serialize + Clone + Send + 'static,
280    {
281        let index = match self.spec.index_of(key) {
282            Ok(index) => index,
283            Err(error) => return Err(PayloadInsertError::new(error, payload)),
284        };
285
286        let slot = &mut self.slots[index];
287        match slot.definition {
288            Some(definition) if !definition.is::<T>() => {
289                return Err(PayloadInsertError::new(
290                    StateError::TypeMismatch {
291                        field: key.to_owned(),
292                        expected: type_name::<T>(),
293                        actual: definition.name,
294                    },
295                    payload,
296                ));
297            }
298            Some(_) => {}
299            None => slot.definition = Some(ValueType::of::<T>()),
300        }
301
302        let previous = slot.value.replace(StateValue::new(payload));
303        match previous {
304            None => Ok(None),
305            Some(previous) => match previous.downcast::<T>() {
306                Ok(previous) => Ok(Some(previous)),
307                Err(_) => unreachable!("a type-bound StateValue failed its consuming downcast"),
308            },
309        }
310    }
311
312    /// Borrows a populated field as the exact Rust type `T`.
313    ///
314    /// # Errors
315    ///
316    /// Returns [`StateError::UnknownField`] for an undeclared key,
317    /// [`StateError::MissingPayload`] for an empty slot, or
318    /// [`StateError::TypeMismatch`] when the stored concrete type differs from
319    /// `T`.
320    pub fn payload<T>(&self, key: &str) -> Result<&T, StateError>
321    where
322        T: Any,
323    {
324        let index = self.spec.index_of(key)?;
325        self.validate_slot::<T>(index, key)?;
326        Ok(self.slots[index]
327            .value
328            .as_ref()
329            .and_then(StateValue::downcast_ref::<T>)
330            .expect("a validated state slot must contain its bound concrete type"))
331    }
332
333    /// Mutably borrows a populated field as the exact Rust type `T`.
334    ///
335    /// Mutation occurs in place and does not clone the payload.
336    ///
337    /// # Errors
338    ///
339    /// Returns [`StateError::UnknownField`] for an undeclared key,
340    /// [`StateError::MissingPayload`] for an empty slot, or
341    /// [`StateError::TypeMismatch`] when the stored concrete type differs from
342    /// `T`.
343    pub fn payload_mut<T>(&mut self, key: &str) -> Result<&mut T, StateError>
344    where
345        T: Any,
346    {
347        let index = self.spec.index_of(key)?;
348        self.validate_slot::<T>(index, key)?;
349        Ok(self.slots[index]
350            .value
351            .as_mut()
352            .and_then(StateValue::downcast_mut::<T>)
353            .expect("a validated state slot must contain its bound concrete type"))
354    }
355
356    /// Borrows several distinct populated fields as concrete immutable types.
357    ///
358    /// `Q` is a tuple of expected payload types, while `keys` is the equally
359    /// sized tuple of field names. Tuple positions correspond exactly. The
360    /// supported arities are two through eight; single-field callers should use
361    /// [`SystemState::payload`]. The sealed tuple implementation is internal and
362    /// requires no user-defined selector, query object, or macro invocation.
363    ///
364    /// # Errors
365    ///
366    /// Validation first resolves field names and rejects repeated fields, then
367    /// checks retained types and payload presence in tuple order. Every check
368    /// completes before references are returned. The method reports an unknown
369    /// field, repeated field, retained type mismatch, or missing payload through
370    /// [`StateError`]. An error leaves every slot unchanged.
371    pub fn borrow_payloads<'state, Q>(
372        &'state self,
373        keys: Q::Keys<'_>,
374    ) -> Result<Q::Refs<'state>, StateError>
375    where
376        Q: PayloadTuple,
377    {
378        Q::borrow(self, keys)
379    }
380
381    /// Borrows several distinct populated fields as concrete mutable types.
382    ///
383    /// `Q` is a tuple of expected payload types, while `keys` is the equally
384    /// sized tuple of field names. All names, duplicate indices, retained type
385    /// contracts, and payload presence are validated before any mutable
386    /// reference is produced. Payloads remain owned by this state and are not
387    /// cloned, moved, serialized, locked, or temporarily removed.
388    ///
389    /// One call should normally surround a complete coupled kernel or sweep so
390    /// name lookup and dynamic type validation occur once outside its inner
391    /// loop. Supported arities are two through eight; single-field callers
392    /// should use [`SystemState::payload_mut`].
393    ///
394    /// # Errors
395    ///
396    /// Returns the same deterministic validation errors as
397    /// [`SystemState::borrow_payloads`]. A failure leaves the state unchanged and grants
398    /// no partial borrow.
399    pub fn borrow_payloads_mut<'state, Q>(
400        &'state mut self,
401        keys: Q::Keys<'_>,
402    ) -> Result<Q::RefsMut<'state>, StateError>
403    where
404        Q: PayloadTuple,
405    {
406        Q::borrow_mut(self, keys)
407    }
408
409    /// Removes and returns the payload from a declared field.
410    ///
411    /// A successful call moves the original concrete `T` out of its internal
412    /// box and leaves the field slot empty while retaining its type contract.
413    /// It does not invoke `Clone`. Type and presence validation occurs before
414    /// the payload owner is removed.
415    ///
416    /// # Errors
417    ///
418    /// Returns [`StateError::UnknownField`] for an undeclared key,
419    /// [`StateError::MissingPayload`] for an empty slot, or
420    /// [`StateError::TypeMismatch`] when the stored concrete type differs from
421    /// `T`.
422    pub fn take_payload<T>(&mut self, key: &str) -> Result<T, StateError>
423    where
424        T: Any + Send,
425    {
426        let index = self.spec.index_of(key)?;
427        self.validate_slot::<T>(index, key)?;
428        let value = self.slots[index]
429            .value
430            .take()
431            .expect("a validated state slot must contain a payload");
432        match value.downcast::<T>() {
433            Ok(payload) => Ok(payload),
434            Err(_) => unreachable!("a type-bound StateValue failed its consuming downcast"),
435        }
436    }
437
438    /// Returns a populated erased value for a typed immutable accessor.
439    fn value(&self, key: &str) -> Result<&StateValue, StateError> {
440        let index = self.spec.index_of(key)?;
441        self.slots[index]
442            .value
443            .as_ref()
444            .ok_or_else(|| StateError::MissingPayload {
445                field: key.to_owned(),
446            })
447    }
448
449    /// Validates one resolved slot against an expected concrete type and value.
450    fn validate_slot<T>(&self, index: usize, key: &str) -> Result<(), StateError>
451    where
452        T: Any,
453    {
454        let slot = &self.slots[index];
455        if let Some(definition) = slot.definition
456            && !definition.is::<T>()
457        {
458            return Err(StateError::TypeMismatch {
459                field: key.to_owned(),
460                expected: type_name::<T>(),
461                actual: definition.name,
462            });
463        }
464
465        if slot.value.is_none() {
466            return Err(StateError::MissingPayload {
467                field: key.to_owned(),
468            });
469        }
470        Ok(())
471    }
472
473    /// Resolves and validates a fixed-size tuple of distinct field names.
474    fn resolve_distinct<const N: usize>(&self, keys: [&str; N]) -> Result<[usize; N], StateError> {
475        let mut indices = [0; N];
476        for (position, key) in keys.iter().enumerate() {
477            let index = self.spec.index_of(key)?;
478            if indices[..position].contains(&index) {
479                return Err(StateError::RepeatedPayloadBorrow {
480                    field: (*key).to_owned(),
481                });
482            }
483            indices[position] = index;
484        }
485        Ok(indices)
486    }
487
488    /// Safely separates already validated distinct slot indices.
489    fn disjoint_slots_mut<const N: usize>(&mut self, indices: [usize; N]) -> [&mut StateSlot; N] {
490        let mut positions: [(usize, usize); N] =
491            std::array::from_fn(|position| (position, indices[position]));
492        positions.sort_unstable_by_key(|(_, index)| *index);
493
494        let mut remaining = self.slots.as_mut_slice();
495        let mut base = 0;
496        let mut selected: [Option<&mut StateSlot>; N] = std::array::from_fn(|_| None);
497        for (original_position, index) in positions {
498            let relative = index - base;
499            let (_, at_index) = remaining.split_at_mut(relative);
500            let (slot, tail) = at_index
501                .split_first_mut()
502                .expect("resolved state slot index must be in bounds");
503            selected[original_position] = Some(slot);
504            remaining = tail;
505            base = index + 1;
506        }
507
508        selected
509            .map(|slot| slot.expect("one disjoint slot must be returned for every requested index"))
510    }
511}
512
513/// Crate-visible observation port for borrowing populated payloads as Serde values.
514pub(crate) trait StateObservationAccess {
515    /// Borrows one populated payload without cloning, encoding, or exposing its wrapper.
516    fn serializable_payload(&self, key: &str) -> Result<&dyn erased_serde::Serialize, StateError>;
517}
518
519impl StateObservationAccess for SystemState {
520    fn serializable_payload(&self, key: &str) -> Result<&dyn erased_serde::Serialize, StateError> {
521        Ok(self.value(key)?.serializable())
522    }
523}
524
525impl SystemState {
526    /// Creates an empty state sharing schema and retained payload type contracts.
527    pub fn clone_structure_without_payloads(&self, time: StateTime) -> SystemState {
528        SystemState {
529            spec: self.spec.clone(),
530            time,
531            slots: self.slots.iter().map(StateSlot::empty_like).collect(),
532        }
533    }
534
535    /// Replaces the complete temporal coordinate and returns the previous one.
536    pub fn replace_time(&mut self, time: StateTime) -> StateTime {
537        std::mem::replace(&mut self.time, time)
538    }
539
540    /// Returns the number of fields that currently contain payloads.
541    pub fn populated_field_count(&self) -> usize {
542        self.slots
543            .iter()
544            .filter(|slot| slot.value.is_some())
545            .count()
546    }
547
548    /// Reports whether a populated field contains exactly `T`.
549    pub fn payload_has_type<T: Any>(&self, key: &str) -> Result<bool, StateError> {
550        let index = self.spec.index_of(key)?;
551        Ok(self.slots[index]
552            .value
553            .as_ref()
554            .is_some_and(StateValue::is::<T>))
555    }
556
557    /// Drops one payload while retaining its field type contract.
558    pub fn clear_payload(&mut self, key: &str) -> Result<bool, StateError> {
559        let index = self.spec.index_of(key)?;
560        Ok(self.slots[index].value.take().is_some())
561    }
562
563    /// Drops all payloads while retaining schema, time, and type contracts.
564    pub fn clear_all_payloads(&mut self) {
565        self.slots.iter_mut().for_each(|slot| slot.value = None);
566    }
567}
568
569/// Sealing boundary for the internally generated tuple implementations.
570mod tuple_sealed {
571    /// Prevents downstream crates from implementing the hidden tuple contract.
572    pub trait Sealed {}
573}
574
575/// Internal type-level mapping used by [`SystemState::borrow_payloads`] and
576/// [`SystemState::borrow_payloads_mut`].
577///
578/// This trait must be public because it appears in those generic methods'
579/// signatures, but it is sealed and hidden from generated documentation.
580/// Applications select an implementation simply by
581/// writing a supported tuple type such as `(Position, Velocity)`.
582#[doc(hidden)]
583pub trait PayloadTuple: tuple_sealed::Sealed {
584    /// Equally sized tuple of borrowed field names.
585    type Keys<'key>;
586
587    /// Equally sized tuple of immutable concrete payload references.
588    type Refs<'state>
589    where
590        Self: 'state;
591
592    /// Equally sized tuple of mutable concrete payload references.
593    type RefsMut<'state>
594    where
595        Self: 'state;
596
597    /// Resolves and immutably borrows one supported field tuple.
598    #[doc(hidden)]
599    fn borrow<'state, 'key>(
600        state: &'state SystemState,
601        keys: Self::Keys<'key>,
602    ) -> Result<Self::Refs<'state>, StateError>;
603
604    /// Resolves and mutably borrows one supported field tuple.
605    #[doc(hidden)]
606    fn borrow_mut<'state, 'key>(
607        state: &'state mut SystemState,
608        keys: Self::Keys<'key>,
609    ) -> Result<Self::RefsMut<'state>, StateError>;
610}
611
612/// Substitutes one repeated generic identifier with a common tuple element.
613macro_rules! substitute_type {
614    ($_generic:ident => $replacement:ty) => {
615        $replacement
616    };
617}
618
619/// Generates the sealed heterogeneous borrow contract for one tuple arity.
620///
621/// Public callers see only `SystemState::borrow_payloads[_mut]`; this macro centralizes
622/// validation order, exact downcasts, and tuple construction so every supported
623/// arity has identical semantics.
624macro_rules! impl_state_tuple {
625    ($(($type:ident, $key:ident, $slot:ident, $index:tt)),+ $(,)?) => {
626        impl<$($type),+> tuple_sealed::Sealed for ($($type,)+)
627        where
628            $($type: Any,)+
629        {
630        }
631
632        impl<$($type),+> PayloadTuple for ($($type,)+)
633        where
634            $($type: Any,)+
635        {
636            type Keys<'key> = ($(substitute_type!($type => &'key str),)+);
637            type Refs<'state> = ($(&'state $type,)+) where Self: 'state;
638            type RefsMut<'state> = ($(&'state mut $type,)+) where Self: 'state;
639
640            fn borrow<'state, 'key>(
641                state: &'state SystemState,
642                keys: Self::Keys<'key>,
643            ) -> Result<Self::Refs<'state>, StateError> {
644                let ($($key,)+) = keys;
645                let indices = state.resolve_distinct([$($key,)+])?;
646                $(state.validate_slot::<$type>(indices[$index], $key)?;)+
647
648                Ok(($(
649                    state.slots[indices[$index]]
650                        .value
651                        .as_ref()
652                        .and_then(StateValue::downcast_ref::<$type>)
653                        .expect("a preflighted state slot must contain its bound concrete type"),
654                )+))
655            }
656
657            fn borrow_mut<'state, 'key>(
658                state: &'state mut SystemState,
659                keys: Self::Keys<'key>,
660            ) -> Result<Self::RefsMut<'state>, StateError> {
661                let ($($key,)+) = keys;
662                let indices = state.resolve_distinct([$($key,)+])?;
663                $(state.validate_slot::<$type>(indices[$index], $key)?;)+
664                let [$($slot,)+] = state.disjoint_slots_mut(indices);
665
666                Ok(($(
667                    $slot
668                        .value
669                        .as_mut()
670                        .and_then(StateValue::downcast_mut::<$type>)
671                        .expect("a preflighted state slot must contain its bound concrete type"),
672                )+))
673            }
674        }
675    };
676}
677
678impl_state_tuple!((A, key_a, slot_a, 0), (B, key_b, slot_b, 1));
679impl_state_tuple!(
680    (A, key_a, slot_a, 0),
681    (B, key_b, slot_b, 1),
682    (C, key_c, slot_c, 2),
683);
684impl_state_tuple!(
685    (A, key_a, slot_a, 0),
686    (B, key_b, slot_b, 1),
687    (C, key_c, slot_c, 2),
688    (D, key_d, slot_d, 3),
689);
690impl_state_tuple!(
691    (A, key_a, slot_a, 0),
692    (B, key_b, slot_b, 1),
693    (C, key_c, slot_c, 2),
694    (D, key_d, slot_d, 3),
695    (E, key_e, slot_e, 4),
696);
697impl_state_tuple!(
698    (A, key_a, slot_a, 0),
699    (B, key_b, slot_b, 1),
700    (C, key_c, slot_c, 2),
701    (D, key_d, slot_d, 3),
702    (E, key_e, slot_e, 4),
703    (F, key_f, slot_f, 5),
704);
705impl_state_tuple!(
706    (A, key_a, slot_a, 0),
707    (B, key_b, slot_b, 1),
708    (C, key_c, slot_c, 2),
709    (D, key_d, slot_d, 3),
710    (E, key_e, slot_e, 4),
711    (F, key_f, slot_f, 5),
712    (G, key_g, slot_g, 6),
713);
714impl_state_tuple!(
715    (A, key_a, slot_a, 0),
716    (B, key_b, slot_b, 1),
717    (C, key_c, slot_c, 2),
718    (D, key_d, slot_d, 3),
719    (E, key_e, slot_e, 4),
720    (F, key_f, slot_f, 5),
721    (G, key_g, slot_g, 6),
722    (H, key_h, slot_h, 7),
723);
724
725impl Clone for SystemState {
726    /// Shares the schema and invokes each populated payload's `Clone`.
727    ///
728    /// Payload-defined cloning may copy or share backing storage. This method
729    /// does not guarantee independent mutable scientific values.
730    fn clone(&self) -> Self {
731        Self {
732            spec: self.spec.clone(),
733            time: self.time,
734            slots: self.slots.clone(),
735        }
736    }
737}
738
739impl fmt::Debug for SystemState {
740    /// Formats structural metadata without formatting scientific payloads.
741    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
742        formatter
743            .debug_struct("SystemState")
744            .field("time", &self.time)
745            .field("source", &self.spec.template_path())
746            .field("fields", &self.slots.len())
747            .field(
748                "loaded",
749                &self
750                    .slots
751                    .iter()
752                    .filter(|slot| slot.value.is_some())
753                    .count(),
754            )
755            .finish_non_exhaustive()
756    }
757}