Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Advanced Task Features

In the earlier chapters we treated #[derive(Reflect)], impl Freezable, and type Resources<'r> = () as required boilerplate. This chapter explains what each of these does and when you’d want to customize them.

#[derive(Reflect)]

The Reflect derive macro enables runtime introspection on your task struct. Monitoring tools and simulation environments use it to inspect a task’s fields at runtime without knowing the concrete type at compile time.

#![allow(unused)]
fn main() {
#[derive(Reflect)]
pub struct MyController {
    kp: f64,
    ki: f64,
    accumulated_error: f64,
}
}

With Reflect derived, a monitoring UI could display kp, ki, and accumulated_error as live values while the robot is running.

In practice: always add #[derive(Reflect)] to your task structs. It enables monitoring and simulation tooling when you need it.

Freezable – State Serialization

The Freezable trait enables Copper’s deterministic replay system. The runtime periodically takes “snapshots” (keyframes) of every task’s internal state, much like keyframes in a video codec. During replay, it can jump to any snapshot instead of replaying from the very beginning.

Tasks with no state to freeze

For tasks that hold no internal state (or state that can be trivially reconstructed), the empty implementation is all you need:

#![allow(unused)]
fn main() {
impl Freezable for MySource {}
}

This tells Copper “there’s nothing to snapshot for this task.” This is what we’ve been using throughout the book, and it’s correct for all our tasks so far – they don’t carry any state between cycles.

Stateful tasks

If your task maintains state that affects its behavior across cycles – for example, a PID controller accumulating error, a Kalman filter maintaining a covariance matrix, or a counter tracking message sequence numbers – you should implement the freeze and thaw methods.

The Freezable trait uses bincode’s Encoder and Decoder for serialization:

#![allow(unused)]
fn main() {
use cu29::prelude::*;
use cu29::bincode::enc::Encoder;
use cu29::bincode::de::Decoder;
use cu29::bincode::error::{EncodeError, DecodeError};

#[derive(Reflect)]
pub struct PidController {
    kp: f64,
    ki: f64,
    kd: f64,
    accumulated_error: f64,
    previous_error: f64,
}

impl Freezable for PidController {
    fn freeze<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        // Serialize the fields that change at runtime
        cu29::bincode::Encode::encode(&self.accumulated_error, encoder)?;
        cu29::bincode::Encode::encode(&self.previous_error, encoder)?;
        Ok(())
    }

    fn thaw<D: Decoder>(&mut self, decoder: &mut D) -> Result<(), DecodeError> {
        self.accumulated_error = cu29::bincode::Decode::decode(decoder)?;
        self.previous_error = cu29::bincode::Decode::decode(decoder)?;
        Ok(())
    }
}
}

freeze serializes the task’s mutable state using bincode’s Encode trait. thaw deserializes it back using Decode. The runtime calls these automatically at keyframe boundaries.

Rule of thumb: Only serialize fields that change during process(). Configuration fields like kp, ki, kd are set once in new() and don’t need to be frozen – they’ll be reconstructed from copperconfig.ron during replay.

When does this matter?

If you never use Copper’s replay features, the empty impl Freezable is fine for every task. But if you plan to record and replay robot runs (one of Copper’s strongest features), implementing Freezable correctly means the replay system can seek to any point in the log efficiently rather than replaying from the start.

Think of it like a video file: without keyframes, you’d have to decode from the beginning every time you want to seek. With keyframes (state snapshots), you can jump to any point and resume from there. Freezable is how Copper creates those keyframes for your task’s internal state.

A transform that can process independent cycles

v1.3 An image conversion or a fixed arithmetic transform often depends only on its current input and immutable settings. Such work can use CuStatelessTask: its per-cycle callbacks borrow &self, allowing an execution plan to overlap calls for different CopperLists. Use it when each cycle can be processed independently. A controller whose next output depends on an accumulated error belongs in CuTask, with that error included in its frozen state.

Try this in the single-crate project from Writing Tasks. The source still produces MyPayload { value: 42 } and the sink still receives MyPayload.

1. Replace the processing task

In src/tasks.rs, replace the MyTask struct and its trait implementations with this complete block. Keep the file’s existing imports, payload, source, and sink:

#![allow(unused)]
fn main() {
#[derive(Reflect)]
pub struct MyTask {}

impl Freezable for MyTask {}

impl CuStatelessTask for MyTask {
    type Resources<'r> = ();
    type Input<'m> = input_msg!(MyPayload);
    type Output<'m> = output_msg!(MyPayload);

    fn new(_config: Option<&ComponentConfig>, _resources: Self::Resources<'_>) -> CuResult<Self> {
        Ok(Self {})
    }

    fn process(
        &self,
        ctx: &CuContext,
        input: &Self::Input<'_>,
        output: &mut Self::Output<'_>,
    ) -> CuResult<()> {
        if let Some(payload) = input.payload() {
            output.set_payload(MyPayload { value: payload.value * 2 });
            output.tov = input.tov;
            debug!(ctx, "Doubled input: {}", payload.value * 2);
        } else {
            output.clear_payload();
        }
        Ok(())
    }
}
}

The arithmetic uses only the current input. output remains mutable because it belongs to this CopperList; the task instance is shared through &self.

2. Declare the task kind

Replace the t-0 entry in copperconfig.ron with:

(
    id: "t-0",
    type: "tasks::MyTask",
    kind: stateless_task,
),

Keep the existing src -> t-0 -> sink connections. The explicit kind tells Copper to call CuStatelessTask rather than CuTask; it cannot infer this choice from the connections.

3. Run and observe the transform

From the project root:

cargo run

The task reports Doubled input: 84, and the sink reports Sink Received message: 84. Stop the app with Ctrl-C. You have changed the transform’s execution contract while keeping its message type and graph wiring. The serial plan is sufficient for this exercise; overlapping execution requires a plan that schedules independent occurrences concurrently.

Choosing the contract

CuStatelessTask requires Send + Sync. preprocess, process, and postprocess all use &self; construction, start, stop, and restoring a keyframe remain exclusive operations. Immutable calibration or configuration can live in the struct. An empty Freezable implementation is appropriate when there is no changing state to restore.

Any interior mutability or shared resource must preserve the same output when calls overlap. A lock makes access safe but does not make order-dependent algorithm state deterministic. Use CuTask for that state. Stateless nodes cannot use background or anytime-task configuration.

Resources – Hardware Injection

The type Resources<'r> associated type declares what hardware or system resources a task needs. Resources represent physical endpoints – serial ports, GPIO controllers, SPI buses, cameras – or shared services bound through a resource bundle.

Worker thread pools are configured separately, in the runtime section of the config – see Thread Pools, Affinity, and Real-Time Scheduling.

No resources

Most tasks in a simple project don’t need external resources:

#![allow(unused)]
fn main() {
type Resources<'r> = ();
}

This means “give me nothing.” The _resources parameter in new() is just (). This is what we’ve used throughout the book.

The problem resources solve

On a real robot, a sensor driver needs access to a hardware peripheral – say, a serial port or an SPI bus. Where does that handle come from? You have a few options:

  1. Create it inside new() – Works, but what if two tasks need the same bus? Or if the hardware needs platform-specific initialization that your task shouldn’t know about?

  2. Pass it as a global – Not great for testing, portability, or safety.

  3. Have the runtime inject it – This is what Resources does. You declare what you need, and the runtime provides it.

How it works

Resources involve three pieces:

1. A resource provider (called a “bundle”) is declared in copperconfig.ron:

resources: [
    (
        id: "board",
        provider: "crate::resources::BoardBundle",
        config: { "uart_device": "/dev/ttyUSB0" },
    ),
],

The bundle is a Rust type that knows how to create the actual hardware handles (open the serial port, initialize GPIO, etc.).

2. Tasks declare which resources they need in copperconfig.ron:

(
    id: "imu",
    type: "tasks::ImuDriver",
    resources: { "serial": "board.uart0" },
),

This says: “the imu task needs a resource it calls serial, and it should be bound to the uart0 resource from the board bundle.”

3. The task declares a Resources type in its Rust implementation that knows how to pull the bound resources from the runtime’s resource manager:

#![allow(unused)]
fn main() {
impl CuSrcTask for ImuDriver {
    type Resources<'r> = ImuResources<'r>;
    type Output<'m> = output_msg!(ImuPayload);

    fn new(
        config: Option<&ComponentConfig>,
        resources: Self::Resources<'_>,
    ) -> CuResult<Self> {
        // resources.serial is the hardware handle, injected by the runtime
        Ok(Self { port: resources.serial })
    }
    // ...
}
}

Why this design?

Resources keep your tasks portable. An IMU driver doesn’t need to know which serial port to open – that’s a deployment detail. On one robot it might be /dev/ttyUSB0, on another it might be a different bus entirely. By moving the hardware binding to the configuration, the same task code works on different platforms without changes.

Resources can also be shared. A shared bus (like I2C) can be bound to multiple tasks. The resource manager handles the ownership semantics: exclusive resources are moved to a single task, shared resources are behind an Arc and each consumer receives a cloned handle.

v1.1 The same pattern applies to GPU services. With the cu29/cuda feature, a bundle can own a shared CUDA context and CuCudaPool, while tasks pass CuHandle<CudaSliceWrapper<T>> through the graph. Keep CUDA streams task-local unless a component explicitly defines shared-stream ordering. CUDA handles are process-local, so their producing nodes should use logging: (handle_content: none); they cannot currently be reconstructed during replay. CuHandle::storage_id can confirm that two stages saw the same pooled allocation rather than a replacement copy.

When do you need resources?

For the projects in this book, type Resources<'r> = () is all you need. Resources become important when you:

  • Write drivers that talk to real hardware (serial, SPI, GPIO, USB)
  • Need multiple tasks to share a hardware bus
  • Want the same task to work across different boards without code changes
  • Want to swap real hardware for mocks in testing

The examples/cu_resources_test/ in the copper-rs repository is a complete working example that demonstrates bundles, shared resources, owned resources, and mission-specific resource bindings.

Composing resource bundles

v1.2 A hardware handle sometimes needs several layers before a task can use it: a UART becomes a configured radio, and the radio becomes a framed telemetry transport. A resource bundle can consume another bundle’s output, so each layer owns its startup and configuration while tasks receive the finished handle.

Inspect a complete radio application

The HC-12 component contains a complete example of this composition. From the root of the copper-rs checkout used for this book, run its software checks:

cd components/res/cu_hc12
just

The tests exercise radio startup with simulated serial, pin, and delay resources; no radio hardware is needed. For the application wiring, read examples/echo.ron and examples/echo.rs in this component. The RON configuration declares three bundles:

  • board exports a nonblocking UART and its adapter’s RTS pin.
  • timing exports a startup delay.
  • radio consumes those three resources and exports the configured HC-12 serial handle. The byte bridge takes that handle and echoes received bytes.

In that existing radio declaration, the input bindings are:

resources: {
    "serial": "board.serial0",
    "set": "board.serial0_rts",
    "delay": "timing.delay",
},

The left side names an input required by the consuming provider; the right side names an output from another bundle. Copper constructs providers in dependency order. Cycles, missing providers, inactive mission providers, and unknown binding names fail compilation. Concrete resource types and exclusive ownership are checked at startup. Changing these input bindings requires a rebuild.

Run with two radios

On Unix, connect two HC-12 radios through USB-to-TTL adapters whose compatible 3.3 V active-low RTS# outputs connect to SET, with common grounds. Both UARTs must match their modules’ saved baud rate (factory default: 9600, 8N1). The example enables the Linux resource provider’s serial-rts feature. Its serial0_rts: true configuration exports the owned SET-pin handle and disables hardware flow control.

From the same component directory, replace these device paths with the two adapters on your machine, then run:

just pair /dev/ttyUSB0 /dev/ttyUSB1

The program uses the baud rate and channel from examples/echo.ron, configures both radios, and verifies 1-, 31-, 128-, and 256-byte transfers in each direction. A mismatch or a five-second timeout fails the check. Run it while both radios are idle. To echo on just one end of a pair instead, edit the device and channel in examples/echo.ron, then run just echo.

Adapt the layers

A composing provider declares its inputs with resources!, exposes their names through ResourceBundle::INPUT_NAMES, and retrieves them with bundle.inputs::<Inputs>(manager)? in its build method. Consume owned inputs or clone shared handles, then register the wrapped output. See the HC-12 provider for a complete implementation.

For telemetry, a SerialLogStreamTxResources<Radio> bundle can consume radio.serial and export telemetry.tx for a LogStream destination. This replaces the byte bridge as the radio’s owner. Follow the component’s LogStream setup for concrete type aliases, feature setup, and a conservative link budget. Resource composition establishes startup dependencies; it does not add per-cycle task-message edges.

Summary

FeaturePurposeWhen to customize
#[derive(Reflect)]Runtime introspection for monitoring/simulationAlways use the derive; the feature flag controls cost
impl FreezableState snapshots for deterministic replayImplement freeze/thaw for stateful tasks
type Resources<'r>Hardware/service dependency injectionDeclare resource types when your task needs hardware handles

For most of the projects you’ll build while learning Copper, the defaults are fine: #[derive(Reflect)] on the struct, empty impl Freezable, and type Resources<'r> = (). These become important as you move from prototyping to deploying on real hardware with real replay requirements.