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