Skip to main content

cu29_runtime/
simulation.rs

1//! # `cu29::simulation` Module
2//!
3//! The `cu29::simulation` module provides an interface to simulate tasks in Copper-based systems.
4//! It offers structures, traits, and enums that enable hooking into the lifecycle of tasks, adapting
5//! their behavior, and integrating them with simulated hardware environments.
6//!
7//! ## Overview
8//!
9//! This module is specifically designed to manage the lifecycle of tasks during simulation, allowing
10//! users to override specific simulation steps and simulate sensor data or hardware interaction using
11//! placeholders for real drivers. It includes the following components:
12//!
13//! - **`CuTaskCallbackState`**: Represents the lifecycle states of tasks during simulation.
14//! - **`SimOverride`**: Defines how the simulator should handle specific task callbacks, either
15//!   executing the logic in the simulator or deferring to the real implementation.
16//!
17//! ## Hooking Simulation Events
18//!
19//! You can control and simulate task behavior using a callback mechanism. A task in the Copper framework
20//! has a lifecycle, and for each stage of the lifecycle, a corresponding callback state is passed to
21//! the simulation. This allows you to inject custom logic for each task stage.
22//!
23//! ### `CuTaskCallbackState` Enum
24//!
25//! The `CuTaskCallbackState` enum represents different stages in the lifecycle of a Copper task during a simulation:
26//!
27//! - **`New(Option<ComponentConfig>)`**: Triggered when a task is created. Use this state to adapt the simulation
28//!   to a specific component configuration if needed.
29//! - **`Start`**: Triggered when a task starts. This state allows you to initialize or set up any necessary data
30//!   before the task processes any input.
31//! - **`Preprocess`**: Called before the main processing step. Useful for preparing or validating data.
32//! - **`Process(I, O)`**: The core processing state, where you can handle the input (`I`) and output (`O`) of
33//!   the task. For source tasks, `I` is `CuMsg<()>`, and for sink tasks, `O` is `CuMsg<()>`.
34//! - **`Postprocess`**: Called after the main processing step. Allows for cleanup or final adjustments.
35//! - **`Stop`**: Triggered when a task is stopped. Use this to finalize any data or state before task termination.
36//!
37//! ### Example Usage: Callback
38//!
39//! You can combine the expressiveness of the enum matching to intercept and override the task lifecycle for the simulation.
40//!
41//! ```rust,ignore
42//! let mut sim_callback = move |step: SimStep<'_>| -> SimOverride {
43//!     match step {
44//!         // Handle the creation of source tasks, potentially adapting the simulation based on configuration
45//!         SimStep::SourceTask(CuTaskCallbackState::New(Some(config))) => {
46//!             println!("Creating Source Task with configuration: {:?}", config);
47//!             // You can adapt the simulation using the configuration here
48//!             SimOverride::ExecuteByRuntime
49//!         }
50//!         SimStep::SourceTask(CuTaskCallbackState::New(None)) => {
51//!             println!("Creating Source Task without configuration.");
52//!             SimOverride::ExecuteByRuntime
53//!         }
54//!         // Handle the processing step for sink tasks, simulating the response
55//!         SimStep::SinkTask(CuTaskCallbackState::Process(input, output)) => {
56//!             println!("Processing Sink Task...");
57//!             println!("Received input: {:?}", input);
58//!
59//!             // Simulate a response by setting the output payload
60//!             output.set_payload(your_simulated_response());
61//!             println!("Set simulated output for Sink Task.");
62//!
63//!             SimOverride::ExecutedBySim
64//!         }
65//!         // Generic handling for other phases like Start, Preprocess, Postprocess, or Stop
66//!         SimStep::SourceTask(CuTaskCallbackState::Start)
67//!         | SimStep::SinkTask(CuTaskCallbackState::Start) => {
68//!             println!("Task started.");
69//!             SimOverride::ExecuteByRuntime
70//!         }
71//!         SimStep::SourceTask(CuTaskCallbackState::Stop)
72//!         | SimStep::SinkTask(CuTaskCallbackState::Stop) => {
73//!             println!("Task stopped.");
74//!             SimOverride::ExecuteByRuntime
75//!         }
76//!         // Default fallback for any unhandled cases
77//!         _ => {
78//!             println!("Unhandled simulation step: {:?}", step);
79//!             SimOverride::ExecuteByRuntime
80//!         }
81//!     }
82//! };
83//! ```
84//!
85//! In this example, `example_callback` is a function that matches against the current step in the simulation and
86//! determines if the simulation should handle it (`SimOverride::ExecutedBySim`) or defer to the runtime's real
87//! implementation (`SimOverride::ExecuteByRuntime`).
88//!
89//! ## Task Simulation with `CuSimSrcTask` and `CuSimSinkTask`
90//!
91//! The module provides placeholder tasks for source and sink tasks, which do not interact with real hardware but
92//! instead simulate the presence of it.
93//!
94//! - **`CuSimSrcTask<T>`**: A placeholder for a source task that simulates a sensor or data acquisition hardware.
95//!   This task provides the ability to simulate incoming data without requiring actual hardware initialization.
96//!
97//! - **`CuSimSinkTask<T>`**: A placeholder for a sink task that simulates sending data to hardware. It serves as a
98//!   mock for hardware actuators or output devices during simulations.
99//!
100//! ## Controlling Simulation Flow: `SimOverride` Enum
101//!
102//! The `SimOverride` enum is used to control how the simulator should proceed at each step. This allows
103//! for fine-grained control of task behavior in the simulation context:
104//!
105//! - **`ExecutedBySim`**: Indicates that the simulator has handled the task logic, and the real implementation
106//!   should be skipped.
107//! - **`ExecuteByRuntime`**: Indicates that the real implementation should proceed as normal.
108//!
109//! ## Recorded Replay Helpers
110//!
111//! Simulation-enabled generated runtimes expose two recorded replay callbacks:
112//!
113//! - `recorded_replay_step` is exact-output replay. It copies recorded outputs
114//!   from a CopperList and skips the runtime implementation for deterministic
115//!   log reproduction.
116//! - `recorded_debug_replay_step` is debugger state replay. It injects recorded
117//!   external inputs, suppresses external side effects, and lets regular Copper
118//!   tasks execute so restored keyframe state advances to the inspected CL.
119//!
120
121use crate::config::ComponentConfig;
122use crate::context::CuContext;
123use crate::copperlist::CopperList;
124use crate::cubridge::{
125    BridgeChannel, BridgeChannelConfig, BridgeChannelInfo, BridgeChannelSet, CuBridge,
126};
127use crate::cutask::CuMsgPack;
128
129use crate::cutask::{CuMsg, CuMsgPayload, CuSinkTask, CuSrcTask, Freezable};
130use crate::reflect::{Reflect, TypePath};
131use crate::{input_msg, output_msg};
132use bincode::de::Decoder;
133use bincode::enc::Encoder;
134use bincode::error::{DecodeError, EncodeError};
135use bincode::{Decode, Encode};
136use core::marker::PhantomData;
137use cu29_clock::CuTime;
138use cu29_traits::{CopperListTuple, CuResult, ErasedCuStampedDataSet};
139
140/// Returns the earliest recorded `process_time.start` found in a CopperList.
141///
142/// This is the default timestamp used by exact-output replay when no matching
143/// recorded keyframe is being injected for the current CL.
144pub fn recorded_copperlist_timestamp<P: CopperListTuple>(
145    copperlist: &CopperList<P>,
146) -> Option<CuTime> {
147    <CopperList<P> as ErasedCuStampedDataSet>::cumsgs(copperlist)
148        .into_iter()
149        .filter_map(|msg| Option::<CuTime>::from(msg.metadata().process_time().start))
150        .min()
151}
152
153/// This is the state that will be passed to the simulation support to hook
154/// into the lifecycle of the tasks.
155pub enum CuTaskCallbackState<I, O> {
156    /// Callbacked when a task is created.
157    /// It gives you the opportunity to adapt the sim to the given config.
158    New(Option<ComponentConfig>),
159    /// Callbacked when a task is started.
160    Start,
161    /// Callbacked when a task is getting called on pre-process.
162    Preprocess,
163    /// Callbacked when a task is getting called on process.
164    /// I and O are the input and output messages of the task.
165    /// if this is a source task, I will be CuMsg<()>
166    /// if this is a sink task, O will be CuMsg<()>
167    Process(I, O),
168    /// Callbacked when a task is getting called on post-process.
169    Postprocess,
170    /// Callbacked when a task is stopped.
171    Stop,
172}
173
174/// This is the answer the simulator can give to control the simulation flow.
175#[derive(PartialEq)]
176pub enum SimOverride {
177    /// The callback took care of the logic on the simulation side and the actual
178    /// implementation needs to be skipped.
179    ExecutedBySim,
180    /// The actual implementation needs to be executed.
181    ExecuteByRuntime,
182    /// Emulated the behavior of an erroring task (same as return Err(..) in the normal tasks methods).
183    Errored(String),
184}
185
186/// Lifecycle callbacks for bridges when running in simulation.
187///
188/// These mirror the CuBridge trait hooks so a simulator can choose to
189/// bypass the real implementation (e.g. to avoid opening hardware) or
190/// inject faults.
191pub enum CuBridgeLifecycleState {
192    /// The bridge is about to be constructed. Gives access to config.
193    New(Option<ComponentConfig>),
194    /// The bridge is starting.
195    Start,
196    /// Called before the I/O cycle.
197    Preprocess,
198    /// Called after the I/O cycle.
199    Postprocess,
200    /// The bridge is stopping.
201    Stop,
202}
203
204/// This is a placeholder task for a source task for the simulations.
205/// It basically does nothing in place of a real driver so it won't try to initialize any hardware.
206#[derive(Reflect)]
207#[reflect(no_field_bounds, from_reflect = false, type_path = false)]
208pub struct CuSimSrcTask<T> {
209    #[reflect(ignore)]
210    boo: PhantomData<fn() -> T>,
211    state: bool,
212}
213
214impl<T: 'static> TypePath for CuSimSrcTask<T> {
215    fn type_path() -> &'static str {
216        "cu29_runtime::simulation::CuSimSrcTask"
217    }
218
219    fn short_type_path() -> &'static str {
220        "CuSimSrcTask"
221    }
222
223    fn type_ident() -> Option<&'static str> {
224        Some("CuSimSrcTask")
225    }
226
227    fn crate_name() -> Option<&'static str> {
228        Some("cu29_runtime")
229    }
230
231    fn module_path() -> Option<&'static str> {
232        Some("simulation")
233    }
234}
235
236impl<T> Freezable for CuSimSrcTask<T> {
237    fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
238        Encode::encode(&self.state, encoder)
239    }
240
241    fn thaw<D: Decoder>(&mut self, decoder: &mut D) -> Result<(), DecodeError> {
242        self.state = Decode::decode(decoder)?;
243        Ok(())
244    }
245}
246
247impl<T: CuMsgPayload + 'static> CuSrcTask for CuSimSrcTask<T> {
248    type Resources<'r> = ();
249    type Output<'m> = output_msg!(T);
250
251    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
252    where
253        Self: Sized,
254    {
255        // Default to true to mirror typical source initial state; deterministic across runs.
256        Ok(Self {
257            boo: PhantomData,
258            state: true,
259        })
260    }
261
262    fn process(&mut self, _ctx: &CuContext, _new_msg: &mut Self::Output<'_>) -> CuResult<()> {
263        unimplemented!(
264            "A placeholder for sim was called for a source, you need answer SimOverride to ExecutedBySim for the Process step."
265        )
266    }
267}
268
269impl<T> CuSimSrcTask<T> {
270    /// Placeholder hook for simulation-driven sources.
271    ///
272    /// In the sim placeholder we don't advance any internal state because the
273    /// simulator is responsible for providing deterministic outputs and state
274    /// snapshots are carried by the real task (when run_in_sim = true).
275    /// Keeping this as a no-op avoids baking any fake behavior into keyframes.
276    pub fn sim_tick(&mut self) {}
277}
278
279/// Helper to map a payload type (or tuple of payload types) to the corresponding `input_msg!` form.
280pub trait CuSimSinkInput {
281    type With<'m>: CuMsgPack
282    where
283        Self: 'm;
284}
285
286macro_rules! impl_sim_sink_input_tuple {
287    ($name:ident) => {
288        impl<$name: CuMsgPayload> CuSimSinkInput for ($name,) {
289            type With<'m> = CuMsg<$name> where Self: 'm;
290        }
291    };
292    ($($name:ident),+) => {
293        impl<$($name: CuMsgPayload),+> CuSimSinkInput for ($($name,)+) {
294            type With<'m> = input_msg!('m, $($name),+) where Self: 'm;
295        }
296    };
297}
298
299macro_rules! impl_sim_sink_input_up_to {
300    ($first:ident $(, $rest:ident)* $(,)?) => {
301        impl_sim_sink_input_tuple!($first);
302        impl_sim_sink_input_up_to!(@accumulate ($first); $($rest),*);
303    };
304    (@accumulate ($($acc:ident),+);) => {};
305    (@accumulate ($($acc:ident),+); $next:ident $(, $rest:ident)*) => {
306        impl_sim_sink_input_tuple!($($acc),+, $next);
307        impl_sim_sink_input_up_to!(@accumulate ($($acc),+, $next); $($rest),*);
308    };
309}
310
311impl_sim_sink_input_up_to!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
312
313/// This is a placeholder task for a sink task for the simulations.
314/// It basically does nothing in place of a real driver so it won't try to initialize any hardware.
315#[derive(Reflect)]
316#[reflect(no_field_bounds, from_reflect = false, type_path = false)]
317pub struct CuSimSinkTask<I> {
318    #[reflect(ignore)]
319    boo: PhantomData<fn() -> I>,
320}
321
322impl<I: 'static> TypePath for CuSimSinkTask<I> {
323    fn type_path() -> &'static str {
324        "cu29_runtime::simulation::CuSimSinkTask"
325    }
326
327    fn short_type_path() -> &'static str {
328        "CuSimSinkTask"
329    }
330
331    fn type_ident() -> Option<&'static str> {
332        Some("CuSimSinkTask")
333    }
334
335    fn crate_name() -> Option<&'static str> {
336        Some("cu29_runtime")
337    }
338
339    fn module_path() -> Option<&'static str> {
340        Some("simulation")
341    }
342}
343
344impl<I> Freezable for CuSimSinkTask<I> {}
345
346impl<I: CuSimSinkInput + 'static> CuSinkTask for CuSimSinkTask<I> {
347    type Resources<'r> = ();
348    type Input<'m> = <I as CuSimSinkInput>::With<'m>;
349
350    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
351    where
352        Self: Sized,
353    {
354        Ok(Self { boo: PhantomData })
355    }
356
357    fn process(&mut self, _ctx: &CuContext, _input: &Self::Input<'_>) -> CuResult<()> {
358        unimplemented!(
359            "A placeholder for sim was called for a sink, you need answer SimOverride to ExecutedBySim for the Process step."
360        )
361    }
362}
363
364/// Empty channel-id enum used when a simulated bridge has no channel on one side.
365#[derive(Copy, Clone, Debug, Eq, PartialEq)]
366pub enum CuNoBridgeChannelId {}
367
368/// Empty channel set used when a simulated bridge has no channel on one side.
369pub struct CuNoBridgeChannels;
370
371impl BridgeChannelSet for CuNoBridgeChannels {
372    type Id = CuNoBridgeChannelId;
373
374    const STATIC_CHANNELS: &'static [&'static dyn BridgeChannelInfo<Self::Id>] = &[];
375}
376
377/// Placeholder bridge used in simulation when a bridge is configured with
378/// `run_in_sim: false`.
379///
380/// This bridge is parameterized directly by the Tx/Rx channel sets generated
381/// from configuration, so the original bridge type does not need to compile in
382/// simulation mode.
383#[derive(Reflect)]
384#[reflect(no_field_bounds, from_reflect = false, type_path = false)]
385pub struct CuSimBridge<Tx: BridgeChannelSet + 'static, Rx: BridgeChannelSet + 'static> {
386    #[reflect(ignore)]
387    boo: PhantomData<fn() -> (Tx, Rx)>,
388}
389
390impl<Tx: BridgeChannelSet + 'static, Rx: BridgeChannelSet + 'static> TypePath
391    for CuSimBridge<Tx, Rx>
392{
393    fn type_path() -> &'static str {
394        "cu29_runtime::simulation::CuSimBridge"
395    }
396
397    fn short_type_path() -> &'static str {
398        "CuSimBridge"
399    }
400
401    fn type_ident() -> Option<&'static str> {
402        Some("CuSimBridge")
403    }
404
405    fn crate_name() -> Option<&'static str> {
406        Some("cu29_runtime")
407    }
408
409    fn module_path() -> Option<&'static str> {
410        Some("simulation")
411    }
412}
413
414impl<Tx: BridgeChannelSet + 'static, Rx: BridgeChannelSet + 'static> Freezable
415    for CuSimBridge<Tx, Rx>
416{
417}
418
419impl<Tx: BridgeChannelSet + 'static, Rx: BridgeChannelSet + 'static> CuBridge
420    for CuSimBridge<Tx, Rx>
421{
422    type Tx = Tx;
423    type Rx = Rx;
424    type Resources<'r> = ();
425
426    fn new(
427        _config: Option<&ComponentConfig>,
428        _tx_channels: &[BridgeChannelConfig<<Self::Tx as BridgeChannelSet>::Id>],
429        _rx_channels: &[BridgeChannelConfig<<Self::Rx as BridgeChannelSet>::Id>],
430        _resources: Self::Resources<'_>,
431    ) -> CuResult<Self>
432    where
433        Self: Sized,
434    {
435        Ok(Self { boo: PhantomData })
436    }
437
438    fn send<'a, Payload>(
439        &mut self,
440        _ctx: &CuContext,
441        _channel: &'static BridgeChannel<<Self::Tx as BridgeChannelSet>::Id, Payload>,
442        _msg: &CuMsg<Payload>,
443    ) -> CuResult<()>
444    where
445        Payload: CuMsgPayload + 'a,
446    {
447        Ok(())
448    }
449
450    fn receive<'a, Payload>(
451        &mut self,
452        _ctx: &CuContext,
453        _channel: &'static BridgeChannel<<Self::Rx as BridgeChannelSet>::Id, Payload>,
454        _msg: &mut CuMsg<Payload>,
455    ) -> CuResult<()>
456    where
457        Payload: CuMsgPayload + 'a,
458    {
459        Ok(())
460    }
461}