cu29-runtime 1.0.0

Copper Runtime Runtime crate. Copper is an engine for robotics.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
//! This module contains all the main definition of the traits you need to implement
//! or interact with to create a Copper task.

use crate::config::ComponentConfig;
use crate::context::CuContext;
use crate::reflect::{GetTypeRegistration, Reflect, TypePath, TypeRegistry};
#[cfg(feature = "reflect")]
use bevy_reflect;
use bincode::de::{Decode, Decoder};
use bincode::enc::{Encode, Encoder};
use bincode::error::{DecodeError, EncodeError};
use compact_str::{CompactString, ToCompactString};
use core::any::{TypeId, type_name};
use cu29_clock::{PartialCuTimeRange, Tov};
use cu29_traits::{
    COMPACT_STRING_CAPACITY, CuCompactString, CuError, CuMsgMetadataTrait, CuMsgOrigin, CuResult,
    ErasedCuStampedData, Metadata,
};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

use alloc::format;
use core::fmt::{Debug, Display, Formatter, Result as FmtResult};

/// The state of a task.
// Everything that is stateful in copper for zero copy constraints need to be restricted to this trait.
#[cfg(feature = "reflect")]
pub trait CuMsgPayload:
    Default
    + Debug
    + Clone
    + Encode
    + Decode<()>
    + Serialize
    + DeserializeOwned
    + Reflect
    + TypePath
    + Sized
{
}

#[cfg(not(feature = "reflect"))]
pub trait CuMsgPayload:
    Default + Debug + Clone + Encode + Decode<()> + Serialize + DeserializeOwned + Reflect + Sized
{
}

pub trait CuMsgPack {}

// Also anything that follows this contract can be a payload (blanket implementation)
#[cfg(feature = "reflect")]
impl<T> CuMsgPayload for T where
    T: Default
        + Debug
        + Clone
        + Encode
        + Decode<()>
        + Serialize
        + DeserializeOwned
        + Reflect
        + TypePath
        + Sized
{
}

#[cfg(not(feature = "reflect"))]
impl<T> CuMsgPayload for T where
    T: Default
        + Debug
        + Clone
        + Encode
        + Decode<()>
        + Serialize
        + DeserializeOwned
        + Reflect
        + Sized
{
}

macro_rules! impl_cu_msg_pack {
    ($($name:ident),+) => {
        impl<'cl, $($name),+> CuMsgPack for ($(&CuMsg<$name>,)+)
        where
            $($name: CuMsgPayload),+
        {}
    };
}

macro_rules! impl_cu_msg_pack_up_to {
    ($first:ident, $second:ident $(, $rest:ident)* $(,)?) => {
        impl_cu_msg_pack!($first, $second);
        impl_cu_msg_pack_up_to!(@accumulate ($first, $second); $($rest),*);
    };
    (@accumulate ($($acc:ident),+);) => {};
    (@accumulate ($($acc:ident),+); $next:ident $(, $rest:ident)*) => {
        impl_cu_msg_pack!($($acc),+, $next);
        impl_cu_msg_pack_up_to!(@accumulate ($($acc),+, $next); $($rest),*);
    };
}

impl<T: CuMsgPayload> CuMsgPack for CuMsg<T> {}
impl<T: CuMsgPayload> CuMsgPack for &CuMsg<T> {}
impl<T: CuMsgPayload> CuMsgPack for (&CuMsg<T>,) {}
impl CuMsgPack for () {}

// Apply the macro to generate implementations for tuple sizes up to 12.
impl_cu_msg_pack_up_to!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);

// A convenience macro to get from a payload or a list of payloads to a proper CuMsg or CuMsgPack
// declaration for your tasks used for input messages.
#[macro_export]
macro_rules! input_msg {
    ($lt:lifetime, $first:ty, $($rest:ty),+) => {
        ( & $lt CuMsg<$first>, $( & $lt CuMsg<$rest> ),+ )
    };
    ($ty:ty) => {
        CuMsg<$ty>
    };
}

// A convenience macro to get from a payload to a proper CuMsg used as output.
#[macro_export]
macro_rules! output_msg {
    ($lt:lifetime, $first:ty, $($rest:ty),+) => {
        ( CuMsg<$first>, $( CuMsg<$rest> ),+ )
    };
    ($first:ty, $($rest:ty),+) => {
        ( CuMsg<$first>, $( CuMsg<$rest> ),+ )
    };
    ($ty:ty) => {
        CuMsg<$ty>
    };
}

/// Helper trait used by codegen when Copper needs to treat a task output as a
/// single message slot without relying on config-declared output edges.
pub trait CuSingleOutputMsg {
    type Payload: CuMsgPayload;
}

impl<T: CuMsgPayload> CuSingleOutputMsg for CuMsg<T> {
    type Payload = T;
}

/// CuMsgMetadata is a structure that contains metadata common to all CuStampedDataSet.
#[derive(Debug, Clone, bincode::Encode, bincode::Decode, Serialize, Deserialize, Reflect)]
#[reflect(opaque, from_reflect = false, no_field_bounds)]
pub struct CuMsgMetadata {
    /// The time range used for the processing of this message
    pub process_time: PartialCuTimeRange,
    /// A small string for real time feedback purposes.
    /// This is useful for to display on the field when the tasks are operating correctly.
    pub status_txt: CuCompactString,
    /// Remote Copper provenance captured on receive, when available.
    pub origin: Option<CuMsgOrigin>,
}

impl Metadata for CuMsgMetadata {}

impl CuMsgMetadata {
    pub fn set_status(&mut self, status: impl ToCompactString) {
        self.status_txt = CuCompactString(status.to_compact_string());
    }

    pub fn set_origin(&mut self, origin: CuMsgOrigin) {
        self.origin = Some(origin);
    }

    pub fn clear_origin(&mut self) {
        self.origin = None;
    }
}

impl CuMsgMetadataTrait for CuMsgMetadata {
    fn process_time(&self) -> PartialCuTimeRange {
        self.process_time
    }

    fn status_txt(&self) -> &CuCompactString {
        &self.status_txt
    }

    fn origin(&self) -> Option<&CuMsgOrigin> {
        self.origin.as_ref()
    }
}

impl Display for CuMsgMetadata {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(
            f,
            "process_time start: {}, process_time end: {}",
            self.process_time.start, self.process_time.end
        )
    }
}

/// CuMsg is the envelope holding the msg payload and the metadata between tasks.
#[derive(Default, Debug, Clone, bincode::Decode, Serialize, Deserialize, Reflect)]
#[reflect(opaque, from_reflect = false, no_field_bounds)]
#[serde(bound(
    serialize = "T: Serialize, M: Serialize",
    deserialize = "T: DeserializeOwned, M: DeserializeOwned"
))]
pub struct CuStampedData<T, M>
where
    T: CuMsgPayload,
    M: Metadata,
{
    /// This payload is the actual data exchanged between tasks.
    payload: Option<T>,

    /// The time of validity of the message.
    /// It can be undefined (None), one measure point or a range of measures (TimeRange).
    pub tov: Tov,

    /// This metadata is the data that is common to all messages.
    pub metadata: M,
}

impl<T, M> Encode for CuStampedData<T, M>
where
    T: CuMsgPayload,
    M: Metadata,
{
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        // NOTE: the `HandleContent` policy decision (TouchedOnly / None) is NOT made
        // here. It can't be: this impl is generic over `T`, so method resolution at
        // the `payload_should_log()` call site would always pick the trait blanket
        // default (true) — autoref-specialization only works at concrete-type sites.
        // The codegen-emitted per-slot encoder in cu29_derive consults the policy at
        // the concrete payload type and routes to `encode_metadata_only` when the
        // bytes should be skipped. This generic impl just writes the full payload.
        match &self.payload {
            None => {
                0u8.encode(encoder)?;
            }
            Some(payload) => {
                1u8.encode(encoder)?;
                let encoded_start = cu29_traits::observed_encode_bytes();
                let handle_start = crate::monitoring::current_payload_handle_bytes();
                payload.encode(encoder)?;
                let encoded_bytes =
                    cu29_traits::observed_encode_bytes().saturating_sub(encoded_start);
                let handle_bytes =
                    crate::monitoring::current_payload_handle_bytes().saturating_sub(handle_start);
                crate::monitoring::record_current_slot_payload_io_stats(
                    core::mem::size_of::<T>(),
                    encoded_bytes,
                    handle_bytes,
                );
            }
        }
        self.tov.encode(encoder)?;
        self.metadata.encode(encoder)?;
        Ok(())
    }
}

/// Write a metadata-only record for a stamped message: presence tag = 0u8 (no payload),
/// followed by `tov` and `metadata`. Wire-compatible with the existing decode path —
/// a reader sees `payload: None` for the frame, same as if the source had been
/// disabled entirely, but the surrounding timestamp/status are preserved.
///
/// Codegen emits a call to this helper when a slot's producing task is configured with
/// `HandleContent::None` or `HandleContent::TouchedOnly` and the handle wasn't touched.
pub fn encode_metadata_only<T, M, E>(
    msg: &CuStampedData<T, M>,
    encoder: &mut E,
) -> Result<(), EncodeError>
where
    T: CuMsgPayload,
    M: Metadata,
    E: Encoder,
{
    0u8.encode(encoder)?;
    msg.tov.encode(encoder)?;
    msg.metadata.encode(encoder)?;
    Ok(())
}

impl Default for CuMsgMetadata {
    fn default() -> Self {
        CuMsgMetadata {
            process_time: PartialCuTimeRange::default(),
            status_txt: CuCompactString(CompactString::with_capacity(COMPACT_STRING_CAPACITY)),
            origin: None,
        }
    }
}

impl<T, M> CuStampedData<T, M>
where
    T: CuMsgPayload,
    M: Metadata,
{
    pub(crate) fn from_parts(payload: Option<T>, tov: Tov, metadata: M) -> Self {
        CuStampedData {
            payload,
            tov,
            metadata,
        }
    }

    pub fn new(payload: Option<T>) -> Self {
        Self::from_parts(payload, Tov::default(), M::default())
    }
    pub fn payload(&self) -> Option<&T> {
        self.payload.as_ref()
    }

    pub fn set_payload(&mut self, payload: T) {
        self.payload = Some(payload);
    }

    pub fn clear_payload(&mut self) {
        self.payload = None;
    }

    pub fn payload_mut(&mut self) -> &mut Option<T> {
        &mut self.payload
    }
}

impl<T, M> ErasedCuStampedData for CuStampedData<T, M>
where
    T: CuMsgPayload,
    M: CuMsgMetadataTrait + Metadata,
{
    fn payload(&self) -> Option<&dyn erased_serde::Serialize> {
        self.payload
            .as_ref()
            .map(|p| p as &dyn erased_serde::Serialize)
    }

    #[cfg(feature = "reflect")]
    fn payload_reflect(&self) -> Option<&dyn cu29_traits::Reflect> {
        self.payload
            .as_ref()
            .map(|p| p as &dyn cu29_traits::Reflect)
    }

    fn tov(&self) -> Tov {
        self.tov
    }

    fn metadata(&self) -> &dyn CuMsgMetadataTrait {
        &self.metadata
    }
}

/// This is the robotics message type for Copper with the correct Metadata type
/// that will be used by the runtime.
pub type CuMsg<T> = CuStampedData<T, CuMsgMetadata>;

impl<T: CuMsgPayload> CuStampedData<T, CuMsgMetadata> {
    /// Reinterprets the payload type carried by this message.
    ///
    /// # Safety
    ///
    /// The caller must guarantee that the message really contains a payload of type `U`. Failing
    /// to do so is undefined behaviour.
    pub unsafe fn assume_payload<U: CuMsgPayload>(&self) -> &CuMsg<U> {
        // SAFETY: Caller guarantees that the underlying payload is of type U.
        unsafe { &*(self as *const CuMsg<T> as *const CuMsg<U>) }
    }

    /// Mutable variant of [`assume_payload`](Self::assume_payload).
    ///
    /// # Safety
    ///
    /// The caller must guarantee that mutating the returned message is sound for the actual
    /// payload type stored in the buffer.
    pub unsafe fn assume_payload_mut<U: CuMsgPayload>(&mut self) -> &mut CuMsg<U> {
        // SAFETY: Caller guarantees that the underlying payload is of type U.
        unsafe { &mut *(self as *mut CuMsg<T> as *mut CuMsg<U>) }
    }
}

impl<T: CuMsgPayload + 'static> CuStampedData<T, CuMsgMetadata> {
    fn downcast_err<U: CuMsgPayload + 'static>() -> CuError {
        CuError::from(format!(
            "CuMsg payload mismatch: {} cannot be reinterpreted as {}",
            type_name::<T>(),
            type_name::<U>()
        ))
    }

    /// Attempts to view this message as carrying payload `U`.
    pub fn downcast_ref<U: CuMsgPayload + 'static>(&self) -> CuResult<&CuMsg<U>> {
        if TypeId::of::<T>() == TypeId::of::<U>() {
            // SAFETY: We just proved that T == U.
            Ok(unsafe { self.assume_payload::<U>() })
        } else {
            Err(Self::downcast_err::<U>())
        }
    }

    /// Mutable variant of [`downcast_ref`](Self::downcast_ref).
    pub fn downcast_mut<U: CuMsgPayload + 'static>(&mut self) -> CuResult<&mut CuMsg<U>> {
        if TypeId::of::<T>() == TypeId::of::<U>() {
            // SAFETY: We just proved that T == U.
            Ok(unsafe { self.assume_payload_mut::<U>() })
        } else {
            Err(Self::downcast_err::<U>())
        }
    }
}

/// The internal state of a task needs to be serializable
/// so the framework can take a snapshot of the task graph.
pub trait Freezable {
    /// This method is called by the framework when it wants to save the task state.
    /// The default implementation is to encode nothing (stateless).
    /// If you have a state, you need to implement this method.
    fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        Encode::encode(&(), encoder) // default is stateless
    }

    /// This method is called by the framework when it wants to restore the task to a specific state.
    /// Here it is similar to Decode but the framework will give you a new instance of the task (the new method will be called)
    fn thaw<D: Decoder>(&mut self, _decoder: &mut D) -> Result<(), DecodeError> {
        Ok(())
    }
}

/// Bincode Adapter for Freezable tasks
/// This allows the use of the bincode API directly to freeze and thaw tasks.
pub struct BincodeAdapter<'a, T: Freezable + ?Sized>(pub &'a T);

impl<'a, T: Freezable + ?Sized> Encode for BincodeAdapter<'a, T> {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        self.0.freeze(encoder)
    }
}

/// A Src Task is a task that only produces messages. For example drivers for sensors are Src Tasks.
/// They are in push mode from the runtime.
/// To set the frequency of the pulls and align them to any hw, see the runtime configuration.
/// Note: A source has the privilege to have a clock passed to it vs a frozen clock.
pub trait CuSrcTask: Freezable + Reflect {
    type Output<'m>: CuMsgPayload;
    /// Resources required by the task.
    type Resources<'r>;

    /// Registers the reflected type used as this task's debug-state contract.
    ///
    /// The default exposes the task struct itself. Override this when the task
    /// contains ignored, third-party, hardware, or otherwise non-inspectable
    /// internals and should expose a purpose-built debug-state view instead.
    fn register_debug_state_types(registry: &mut TypeRegistry)
    where
        Self: GetTypeRegistration + Sized,
    {
        registry.register::<Self>();
    }

    /// Returns the reflected type path used as this task's debug-state schema.
    fn debug_state_type_path() -> &'static str
    where
        Self: TypePath + Sized,
    {
        Self::type_path()
    }

    /// Borrows this task's current debug-state view.
    ///
    /// Override this together with [`debug_state_type_path`](Self::debug_state_type_path)
    /// when the debug state is a projected view rather than the task struct.
    fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
    where
        Self: Sized,
    {
        f(self)
    }

    /// Here you need to initialize everything your task will need for the duration of its lifetime.
    /// The config allows you to access the configuration of the task.
    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
    where
        Self: Sized;

    /// Start is called between the creation of the task and the first call to pre/process.
    fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// This is a method called by the runtime before "process". This is a kind of best effort,
    /// as soon as possible call to give a chance for the task to do some work before to prepare
    /// to make "process" as short as possible.
    fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Process is the most critical execution of the task.
    /// The goal will be to produce the output message as soon as possible.
    /// Use preprocess to prepare the task to make this method as short as possible.
    fn process<'o>(&mut self, ctx: &CuContext, new_msg: &mut Self::Output<'o>) -> CuResult<()>;

    /// This is a method called by the runtime after "process". It is best effort a chance for
    /// the task to update some state after process is out of the way.
    /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
    fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Called to stop the task. It signals that the *process method won't be called until start is called again.
    fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }
}

/// This is the most generic Task of copper. It is a "transform" task deriving an output from an input.
pub trait CuTask: Freezable + Reflect {
    type Input<'m>: CuMsgPack;
    type Output<'m>: CuMsgPayload;
    /// Resources required by the task.
    type Resources<'r>;

    /// Registers the reflected type used as this task's debug-state contract.
    ///
    /// The default exposes the task struct itself. Override this when the task
    /// contains ignored, third-party, hardware, or otherwise non-inspectable
    /// internals and should expose a purpose-built debug-state view instead.
    fn register_debug_state_types(registry: &mut TypeRegistry)
    where
        Self: GetTypeRegistration + Sized,
    {
        registry.register::<Self>();
    }

    /// Returns the reflected type path used as this task's debug-state schema.
    fn debug_state_type_path() -> &'static str
    where
        Self: TypePath + Sized,
    {
        Self::type_path()
    }

    /// Borrows this task's current debug-state view.
    ///
    /// Override this together with [`debug_state_type_path`](Self::debug_state_type_path)
    /// when the debug state is a projected view rather than the task struct.
    fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
    where
        Self: Sized,
    {
        f(self)
    }

    /// Here you need to initialize everything your task will need for the duration of its lifetime.
    /// The config allows you to access the configuration of the task.
    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
    where
        Self: Sized;

    /// Start is called between the creation of the task and the first call to pre/process.
    fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// This is a method called by the runtime before "process". This is a kind of best effort,
    /// as soon as possible call to give a chance for the task to do some work before to prepare
    /// to make "process" as short as possible.
    fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Process is the most critical execution of the task.
    /// The goal will be to produce the output message as soon as possible.
    /// Use preprocess to prepare the task to make this method as short as possible.
    fn process<'i, 'o>(
        &mut self,
        _ctx: &CuContext,
        input: &Self::Input<'i>,
        output: &mut Self::Output<'o>,
    ) -> CuResult<()>;

    /// This is a method called by the runtime after "process". It is best effort a chance for
    /// the task to update some state after process is out of the way.
    /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
    fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Called to stop the task. It signals that the *process method won't be called until start is called again.
    fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }
}

/// A Sink Task is a task that only consumes messages. For example drivers for actuators are Sink Tasks.
pub trait CuSinkTask: Freezable + Reflect {
    type Input<'m>: CuMsgPack;
    /// Resources required by the task.
    type Resources<'r>;

    /// Registers the reflected type used as this task's debug-state contract.
    ///
    /// The default exposes the task struct itself. Override this when the task
    /// contains ignored, third-party, hardware, or otherwise non-inspectable
    /// internals and should expose a purpose-built debug-state view instead.
    fn register_debug_state_types(registry: &mut TypeRegistry)
    where
        Self: GetTypeRegistration + Sized,
    {
        registry.register::<Self>();
    }

    /// Returns the reflected type path used as this task's debug-state schema.
    fn debug_state_type_path() -> &'static str
    where
        Self: TypePath + Sized,
    {
        Self::type_path()
    }

    /// Borrows this task's current debug-state view.
    ///
    /// Override this together with [`debug_state_type_path`](Self::debug_state_type_path)
    /// when the debug state is a projected view rather than the task struct.
    fn with_debug_state<R>(&self, f: impl FnOnce(&dyn Reflect) -> R) -> R
    where
        Self: Sized,
    {
        f(self)
    }

    /// Here you need to initialize everything your task will need for the duration of its lifetime.
    /// The config allows you to access the configuration of the task.
    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self>
    where
        Self: Sized;

    /// Start is called between the creation of the task and the first call to pre/process.
    fn start(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// This is a method called by the runtime before "process". This is a kind of best effort,
    /// as soon as possible call to give a chance for the task to do some work before to prepare
    /// to make "process" as short as possible.
    fn preprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Process is the most critical execution of the task.
    /// The goal will be to produce the output message as soon as possible.
    /// Use preprocess to prepare the task to make this method as short as possible.
    fn process<'i>(&mut self, _ctx: &CuContext, input: &Self::Input<'i>) -> CuResult<()>;

    /// This is a method called by the runtime after "process". It is best effort a chance for
    /// the task to update some state after process is out of the way.
    /// It can be use for example to maintain statistics etc. that are not time-critical for the robot.
    fn postprocess(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }

    /// Called to stop the task. It signals that the *process method won't be called until start is called again.
    fn stop(&mut self, _ctx: &CuContext) -> CuResult<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bincode::{config, decode_from_slice, encode_to_vec};

    #[test]
    fn test_cucompactstr_encode_decode() {
        let cstr = CuCompactString(CompactString::from("hello"));
        let config = config::standard();
        let encoded = encode_to_vec(&cstr, config).expect("Encoding failed");
        let (decoded, _): (CuCompactString, usize) =
            decode_from_slice(&encoded, config).expect("Decoding failed");
        assert_eq!(cstr.0, decoded.0);
    }

    /// Test wrapper proving that a composite payload can forward `payload_should_log`
    /// to an inner [`CuHandle`] via an inherent method — exactly the pattern real
    /// composite payloads like `CuImage` will use.
    ///
    /// Gated on the default (non-bevy_reflect) feature configuration where
    /// `Reflect` is auto-impl'd for any `'static`, so the wrapper satisfies
    /// `CuMsgPayload` without needing `#[derive(Reflect)]`.
    #[cfg(not(feature = "reflect"))]
    #[derive(Debug, Clone, bincode::Encode, bincode::Decode, Serialize, Deserialize)]
    struct TestHandlePayload {
        handle: crate::pool::CuHandle<Vec<u8>>,
    }

    #[cfg(not(feature = "reflect"))]
    impl Default for TestHandlePayload {
        fn default() -> Self {
            Self {
                handle: crate::pool::CuHandle::new_detached(Vec::new()),
            }
        }
    }

    #[cfg(not(feature = "reflect"))]
    impl TestHandlePayload {
        // Inherent specialization arm: real composite payloads (e.g. CuImage) provide
        // an identical method that forwards to their inner CuHandle.
        fn payload_should_log(&self) -> bool {
            self.handle.payload_should_log()
        }
    }

    /// Encoding a CuMsg whose payload wraps a CuHandle in `TouchedOnly` mode must:
    /// * skip the payload bytes when no consumer marked the handle touched, and
    /// * include them once `mark_touched` was called.
    /// The wire shape stays compatible with the existing `Option<T>` decode path
    /// (presence tag is 0u8 for skip, 1u8 + payload otherwise).
    #[cfg(not(feature = "reflect"))]
    #[test]
    fn test_encode_skips_payload_for_untouched_handle() {
        use crate::pool::{CuHandle, HandleContent};
        let cfg = config::standard();

        let untouched = TestHandlePayload {
            handle: CuHandle::new_detached_with_mode(
                vec![0xAA, 0xBB, 0xCC, 0xDD],
                HandleContent::TouchedOnly,
            ),
        };
        let msg_skip: CuMsg<TestHandlePayload> = CuMsg::new(Some(untouched));
        let skip_bytes = encode_to_vec(&msg_skip, cfg).expect("encode");

        let touched_payload = TestHandlePayload {
            handle: CuHandle::new_detached_with_mode(
                vec![0xAA, 0xBB, 0xCC, 0xDD],
                HandleContent::TouchedOnly,
            ),
        };
        touched_payload.handle.mark_touched();
        let msg_keep: CuMsg<TestHandlePayload> = CuMsg::new(Some(touched_payload));
        let keep_bytes = encode_to_vec(&msg_keep, cfg).expect("encode");

        assert_eq!(
            skip_bytes[0], 0u8,
            "first byte must be the no-payload presence tag for an untouched TouchedOnly handle"
        );
        assert_eq!(
            keep_bytes[0], 1u8,
            "first byte must be the payload-present tag once the handle was touched"
        );
        assert!(
            keep_bytes.len() > skip_bytes.len(),
            "touched encoding ({} bytes) must include payload content; skip is {} bytes",
            keep_bytes.len(),
            skip_bytes.len()
        );
    }

    /// `HandleContent::All` (the default for every existing source) must never drop
    /// payload bytes — regardless of whether the handle was touched.
    #[cfg(not(feature = "reflect"))]
    #[test]
    fn test_encode_keeps_payload_for_default_mode() {
        use crate::pool::{CuHandle, HandleContent};
        let cfg = config::standard();

        let payload = TestHandlePayload {
            handle: CuHandle::new_detached_with_mode(vec![1, 2, 3], HandleContent::All),
        };
        let msg: CuMsg<TestHandlePayload> = CuMsg::new(Some(payload));
        let bytes = encode_to_vec(&msg, cfg).expect("encode");
        assert_eq!(
            bytes[0], 1u8,
            "default (HandleContent::All) must keep emitting the payload"
        );
    }
}