orchestrator/test: a pure device model for boot-sequence tests A managed device as seen from its reset line: hold reset and it is down, release it and one boot attempt starts. A script of Behaviours (Hang, Boots, BootsThenFails) says what each attempt does, indexed by how many times reset has been released, so the device owns its behaviour and the system under test never tells it how to act. It is a pure state machine with injected time and no dependencies: no pins, no clock, no kernel, no heap. The delay counts from the release, a reset mid-boot restarts it, and asserting reset drops ready. Transitions are stamped with the moment they were due, not the moment a late caller noticed, so tests check exact timing and an event loop can sleep until next_event_at. A small queue keeps ready edges so a pulse between two polls is not lost; overflow is counted, not hidden. It lives beside the orchestrator's other test doubles in services/orchestrator/test and has a README documenting its seams, invariants and host-test target. All arithmetic saturates and the script lookup avoids casts, per the review checklist. Nineteen host tests. Two deliberate breakages (boot one tick late, a reset that forgets to record the drop) each fail several of them. ./pw presubmit passes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
diff --git a/services/orchestrator/test/device_model/BUILD.bazel b/services/orchestrator/test/device_model/BUILD.bazel new file mode 100644 index 0000000..584a1a4 --- /dev/null +++ b/services/orchestrator/test/device_model/BUILD.bazel
@@ -0,0 +1,26 @@ +# Licensed under the Apache-2.0 license +# SPDX-License-Identifier: Apache-2.0 + +load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") + +# A managed device that boots, hangs or dies on a script: a pure state machine +# with injected time and no dependencies, so it runs on a host and behind any +# carrier (pins, IPC). +rust_library( + name = "device_model", + srcs = [ + "src/behaviour.rs", + "src/lib.rs", + "src/model.rs", + "src/tests.rs", + ], + crate_name = "openprot_device_model", + edition = "2024", + visibility = ["//visibility:public"], +) + +rust_test( + name = "device_model_test", + crate = ":device_model", + edition = "2024", +)
diff --git a/services/orchestrator/test/device_model/README.md b/services/orchestrator/test/device_model/README.md new file mode 100644 index 0000000..2aa66b8 --- /dev/null +++ b/services/orchestrator/test/device_model/README.md
@@ -0,0 +1,59 @@ +<!-- Licensed under the Apache-2.0 license --> +<!-- SPDX-License-Identifier: Apache-2.0 --> + +# device model (`openprot_device_model`) + +A managed device as seen from its reset line, for tests. Hold reset and the +device is down; release it and one boot attempt starts. A script says what each +attempt does. It is a pure state machine: `#![no_std]`, no dependencies, no +kernel code, no clock, no heap. + +Tests of the orchestrator's boot walk and recovery need a stand-in device. For +the test to mean anything the **device decides its own behaviour**. If the code +under test also tells the device how to act, it can shape the world it is judged +against, and a bug in it (a double release, say) can quietly change the script +instead of failing. + +## Public seams + +- `DeviceModel::new(script)` builds a device from a `&[Behaviour]`. It starts + with reset asserted. +- `Behaviour` is what one boot attempt does: `Hang` (never ready), + `Boots { after_millis }` (ready after a delay, stays up), or + `BootsThenFails { after_millis, up_millis }` (ready, then drops and stays down + until the next reset). +- `set_reset(asserted, now_millis)` drives the reset line. +- `poll(now_millis)` advances time and returns the `Phase` + (`Held`, `Booting`, `Ready`, `Hung`, `Down`). `ready()` is the ready level. +- `next_event_at()` is when the next change is due, so an event loop can sleep + until then. +- `take_transition()` drains ready changes as `Transition { at_millis, ready }`, + so a pulse that rose and fell between two polls is not lost. + +The model does not know what carries these signals. A board adapter can map them +to pins; a simulation can map them to IPC messages. + +## Invariants + +- **The delay counts from the release.** A reset mid-boot throws the attempt + away, and the next release starts a fresh one. +- **Asserting reset always wins.** It drops ready and returns the device to + `Held` from any phase. Repeating a reset level changes nothing. +- **The script is indexed by release.** The `n`th release follows the `n`th + entry, the last entry repeats, and an empty script hangs. +- **Changes are stamped with when they were due,** not when a late caller + noticed them, and a late poll applies every change that fell due, in order. +- **Nothing panics.** Time and counters saturate; a clock that goes backwards + simply leaves nothing due. The transition queue holds 4 entries; overflow is + counted in `dropped()`, not hidden. + +## Host tests + +```sh +bazel test //services/orchestrator/test/device_model:device_model_test +``` + +The tests run on a host with no kernel. They check boot timing, late polls, a +reset mid-boot, pulses between polls, script indexing, boot-then-fail, +`next_event_at` in every phase, queue overflow and reuse, a clock that goes +backwards, and a delay that would overflow.
diff --git a/services/orchestrator/test/device_model/src/behaviour.rs b/services/orchestrator/test/device_model/src/behaviour.rs new file mode 100644 index 0000000..82fd6fe --- /dev/null +++ b/services/orchestrator/test/device_model/src/behaviour.rs
@@ -0,0 +1,55 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! What a device does on one boot attempt, and where it is in doing it. + +/// What one boot attempt does. A script is a list of these, one per release +/// of reset; the last entry repeats once the script runs out. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Behaviour { + /// Never raises ready. The orchestrator finds out by its deadline + /// expiring, which is the only way it ever finds out. + Hang, + /// Raises ready `after_millis` after the release and stays up. A boot + /// that is late rather than healthy is this variant with a delay past + /// the window the orchestrator will wait: late is a property of the + /// deadline, not of the device. + Boots { + /// Milliseconds from release to ready. + after_millis: u64, + }, + /// Boots, then dies: raises ready `after_millis` after the release, + /// drops it `up_millis` later, and stays down until reset is asserted + /// and released again. A device that took an update and never came back, + /// or one that fell over after reporting in. + BootsThenFails { + /// Milliseconds from release to ready. + after_millis: u64, + /// Milliseconds the device stays ready before it fails. + up_millis: u64, + }, +} + +/// Where the device is. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Phase { + /// Reset is asserted. Ready is low. + Held, + /// Reset is released and the boot delay has not elapsed. + Booting, + /// Ready is high. + Ready, + /// Reset is released and this attempt will never report ready. + Hung, + /// The device was ready and failed. Ready is low until the next reset. + Down, +} + +/// A change of the ready level, stamped with when it was due. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Transition { + /// When the change happened, on the caller's clock. + pub at_millis: u64, + /// The level it changed to: `true` is ready. + pub ready: bool, +}
diff --git a/services/orchestrator/test/device_model/src/lib.rs b/services/orchestrator/test/device_model/src/lib.rs new file mode 100644 index 0000000..8f36988 --- /dev/null +++ b/services/orchestrator/test/device_model/src/lib.rs
@@ -0,0 +1,50 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! A managed device that boots, hangs, or dies on a script, for tests. +//! +//! The orchestrator drives a device's reset line and watches whether it comes +//! up. This models what sits on the other end of that line, and nothing else. +//! It is a pure state machine: no pins, no clock, no kernel, no dependencies. +//! +//! # What it models +//! +//! - **Reset is the input, ready is the output.** Holding reset keeps the +//! device down and its ready level low. Releasing reset starts one boot +//! attempt. +//! - **The device owns its behaviour.** A [`Behaviour`] script says what each +//! boot attempt does, by how many times reset has been released. The system +//! under test never tells the device how to act, so it cannot shape the +//! world it is being judged against. +//! - **Hardware semantics.** The boot delay counts from the release, a reset +//! mid-boot restarts it, and asserting reset drops the ready level. +//! +//! # Time +//! +//! Time is an argument, in milliseconds on the caller's clock. A transition +//! is stamped with the moment it was *due*, not the moment a late caller +//! noticed it, so a test can check exact timing however coarse its polling, +//! and an event loop can sleep until [`DeviceModel::next_event_at`] and wake +//! on the dot. +//! +//! # Observing it +//! +//! The ready level is [`DeviceModel::ready`]. A caller that wants edges, such +//! as a service that forwards "device booted" as a message, drains +//! [`DeviceModel::take_transition`], which does not lose a pulse that rose +//! and fell between two polls. +//! +//! The model does not know what carries these signals. A board adapter can +//! map them to pins; a simulation can map them to IPC messages. + +#![no_std] +#![forbid(unsafe_code)] + +mod behaviour; +mod model; + +pub use behaviour::{Behaviour, Phase, Transition}; +pub use model::DeviceModel; + +#[cfg(test)] +mod tests;
diff --git a/services/orchestrator/test/device_model/src/model.rs b/services/orchestrator/test/device_model/src/model.rs new file mode 100644 index 0000000..37ffa10 --- /dev/null +++ b/services/orchestrator/test/device_model/src/model.rs
@@ -0,0 +1,193 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +//! The state machine. + +use crate::behaviour::{Behaviour, Phase, Transition}; + +/// Transitions held for [`DeviceModel::take_transition`]. A caller drains +/// them every wake, so a handful is enough; more are counted, not kept. +const QUEUE: usize = 4; +// The queue indices are taken modulo `QUEUE`, so it must not be zero. +const _: () = assert!(QUEUE > 0); + +/// The device on the other end of a reset line. +/// +/// Starts with reset asserted, so a device the caller has not released yet is +/// down, the fail-safe state of a managed reset line. +pub struct DeviceModel<'a> { + script: &'a [Behaviour], + releases: u32, + current: Behaviour, + phase: Phase, + /// When the next phase change is due, if one is. + next_at: Option<u64>, + queue: [Option<Transition>; QUEUE], + head: usize, + len: usize, + dropped: u32, +} + +impl<'a> DeviceModel<'a> { + /// A device that follows `script`, one entry per release of reset. An + /// empty script is a device that always hangs. + pub const fn new(script: &'a [Behaviour]) -> Self { + Self { + script, + releases: 0, + current: Behaviour::Hang, + phase: Phase::Held, + next_at: None, + queue: [None; QUEUE], + head: 0, + len: 0, + dropped: 0, + } + } + + /// Where the device is as of the last call. + pub fn phase(&self) -> Phase { + self.phase + } + + /// The ready level. + pub fn ready(&self) -> bool { + self.phase == Phase::Ready + } + + /// How many times reset has been released. + pub fn releases(&self) -> u32 { + self.releases + } + + /// When the next phase change is due, if one is, so an event loop can + /// sleep until then. + pub fn next_event_at(&self) -> Option<u64> { + self.next_at + } + + /// Transitions lost because the queue was full when they happened. + pub fn dropped(&self) -> u32 { + self.dropped + } + + /// Drive the reset line. `asserted` holds the device in reset; `false` + /// releases it and starts the next boot attempt. + /// + /// Repeating the level the line already has changes nothing, so a caller + /// may set it every wake. Releasing while not held is ignored, and + /// asserting always wins: it drops ready, cancels a boot in progress, and + /// brings the device back to [`Phase::Held`] from any phase. + pub fn set_reset(&mut self, asserted: bool, now_millis: u64) { + // Bring the device up to date first, so a change that fell due before + // this moment is seen to happen before the reset does. + self.advance(now_millis); + if asserted { + if self.phase == Phase::Ready { + self.push(Transition { + at_millis: now_millis, + ready: false, + }); + } + self.phase = Phase::Held; + self.next_at = None; + } else if self.phase == Phase::Held { + self.start(now_millis); + } + } + + /// Advance to `now_millis` and report where the device is. Never waits. + pub fn poll(&mut self, now_millis: u64) -> Phase { + self.advance(now_millis); + self.phase + } + + /// The oldest change of the ready level not yet taken, if any. + pub fn take_transition(&mut self) -> Option<Transition> { + if self.len == 0 { + return None; + } + let taken = self.queue.get_mut(self.head).and_then(Option::take); + self.head = self.head.saturating_add(1) % QUEUE; + self.len = self.len.saturating_sub(1); + taken + } + + /// What the `n`th release does: the `n`th script entry, the last one + /// once the script runs out, or a hang for an empty script. + fn behaviour_for(&self, n: u32) -> Behaviour { + // A release count too large for `usize` (not possible on the targets + // this builds for) falls back to the last entry like any other + // count past the end of the script. + usize::try_from(n) + .ok() + .and_then(|i| self.script.get(i)) + .or_else(|| self.script.last()) + .copied() + .unwrap_or(Behaviour::Hang) + } + + /// Begin a boot attempt at `now_millis`. + fn start(&mut self, now_millis: u64) { + let n = self.releases; + self.releases = self.releases.saturating_add(1); + self.current = self.behaviour_for(n); + match self.current { + Behaviour::Hang => { + self.phase = Phase::Hung; + self.next_at = None; + } + Behaviour::Boots { after_millis } | Behaviour::BootsThenFails { after_millis, .. } => { + self.phase = Phase::Booting; + self.next_at = Some(now_millis.saturating_add(after_millis)); + } + } + } + + /// Apply every change due at or before `now_millis`, in order, each + /// stamped with the moment it was due. + fn advance(&mut self, now_millis: u64) { + while let Some(at) = self.next_at { + if now_millis < at { + break; + } + match self.phase { + Phase::Booting => { + self.phase = Phase::Ready; + self.push(Transition { + at_millis: at, + ready: true, + }); + self.next_at = match self.current { + Behaviour::BootsThenFails { up_millis, .. } => { + Some(at.saturating_add(up_millis)) + } + _ => None, + }; + } + Phase::Ready => { + self.phase = Phase::Down; + self.push(Transition { + at_millis: at, + ready: false, + }); + self.next_at = None; + } + // Nothing is due in the other phases. + _ => self.next_at = None, + } + } + } + + fn push(&mut self, transition: Transition) { + if self.len == QUEUE { + self.dropped = self.dropped.saturating_add(1); + return; + } + let at = self.head.saturating_add(self.len) % QUEUE; + if let Some(slot) = self.queue.get_mut(at) { + *slot = Some(transition); + self.len = self.len.saturating_add(1); + } + } +}
diff --git a/services/orchestrator/test/device_model/src/tests.rs b/services/orchestrator/test/device_model/src/tests.rs new file mode 100644 index 0000000..b25dd4c --- /dev/null +++ b/services/orchestrator/test/device_model/src/tests.rs
@@ -0,0 +1,312 @@ +// Licensed under the Apache-2.0 license +// SPDX-License-Identifier: Apache-2.0 + +use crate::*; + +// Macros, not functions: a script is borrowed for the device's lifetime, and +// only a plain literal is promoted to `'static`, not a function call. +macro_rules! boots { + ($after:expr) => { + Behaviour::Boots { + after_millis: $after, + } + }; +} + +macro_rules! dies { + ($after:expr, $up:expr) => { + Behaviour::BootsThenFails { + after_millis: $after, + up_millis: $up, + } + }; +} + +fn up(at_millis: u64) -> Transition { + Transition { + at_millis, + ready: true, + } +} + +fn down(at_millis: u64) -> Transition { + Transition { + at_millis, + ready: false, + } +} + +#[test] +fn a_new_device_is_held_and_not_ready() { + let mut d = DeviceModel::new(&[boots!(10)]); + + assert_eq!(d.phase(), Phase::Held); + assert!(!d.ready()); + assert_eq!(d.releases(), 0); + assert_eq!(d.next_event_at(), None); + assert_eq!(d.take_transition(), None); + // Polling does not release it. + assert_eq!(d.poll(1_000), Phase::Held); +} + +#[test] +fn it_boots_after_the_delay_counted_from_the_release() { + let mut d = DeviceModel::new(&[boots!(50)]); + d.set_reset(false, 100); + + assert_eq!(d.poll(100), Phase::Booting); + assert_eq!(d.next_event_at(), Some(150)); + assert_eq!(d.poll(149), Phase::Booting); + assert!(!d.ready()); + + assert_eq!(d.poll(150), Phase::Ready); + assert!(d.ready()); + assert_eq!(d.take_transition(), Some(up(150))); + assert_eq!(d.next_event_at(), None); +} + +// The caller's polling is coarse; the boot still happened at its due time. +#[test] +fn a_late_poll_stamps_the_due_time_not_the_poll_time() { + let mut d = DeviceModel::new(&[boots!(50)]); + d.set_reset(false, 0); + + assert_eq!(d.poll(1_000), Phase::Ready); + assert_eq!(d.take_transition(), Some(up(50))); +} + +#[test] +fn a_zero_delay_is_ready_at_the_release() { + let mut d = DeviceModel::new(&[boots!(0)]); + d.set_reset(false, 10); + + assert_eq!(d.poll(10), Phase::Ready); + assert_eq!(d.take_transition(), Some(up(10))); +} + +#[test] +fn a_hanging_device_never_reports_ready() { + let mut d = DeviceModel::new(&[Behaviour::Hang]); + d.set_reset(false, 0); + + assert_eq!(d.poll(u64::MAX), Phase::Hung); + assert!(!d.ready()); + assert_eq!(d.next_event_at(), None); + assert_eq!(d.take_transition(), None); +} + +// Reset mid-boot throws the attempt away: the delay starts over from the +// next release. +#[test] +fn a_reset_mid_boot_restarts_the_delay() { + let mut d = DeviceModel::new(&[boots!(50)]); + d.set_reset(false, 0); + d.set_reset(true, 30); + + assert_eq!(d.poll(60), Phase::Held); + assert!(!d.ready()); + + d.set_reset(false, 40); + assert_eq!(d.releases(), 2); + assert_eq!(d.poll(89), Phase::Booting); + assert_eq!(d.poll(90), Phase::Ready); + // The first attempt never reported, so there is exactly one rise. + assert_eq!(d.take_transition(), Some(up(90))); + assert_eq!(d.take_transition(), None); +} + +#[test] +fn asserting_reset_drops_ready() { + let mut d = DeviceModel::new(&[boots!(10)]); + d.set_reset(false, 0); + d.poll(10); + assert_eq!(d.take_transition(), Some(up(10))); + + d.set_reset(true, 25); + + assert_eq!(d.phase(), Phase::Held); + assert!(!d.ready()); + assert_eq!(d.take_transition(), Some(down(25))); +} + +// A pulse that rose and fell between two polls is still there to be drained. +#[test] +fn a_pulse_between_polls_is_not_lost() { + let mut d = DeviceModel::new(&[boots!(10)]); + d.set_reset(false, 0); + + // The caller never polled while the device was up. + d.set_reset(true, 15); + + assert!(!d.ready()); + assert_eq!(d.take_transition(), Some(up(10))); + assert_eq!(d.take_transition(), Some(down(15))); +} + +// Each release is a new attempt; the script says what each one does. +#[test] +fn the_script_is_indexed_by_release_and_the_last_entry_repeats() { + let mut d = DeviceModel::new(&[Behaviour::Hang, boots!(20)]); + + d.set_reset(false, 0); + assert_eq!(d.poll(1_000), Phase::Hung, "first release hangs"); + + d.set_reset(true, 5); + d.set_reset(false, 10); + assert_eq!(d.poll(29), Phase::Booting); + assert_eq!(d.poll(30), Phase::Ready, "second release boots"); + + d.set_reset(true, 40); + d.set_reset(false, 50); + assert_eq!(d.poll(70), Phase::Ready, "third repeats the last entry"); + assert_eq!(d.releases(), 3); +} + +#[test] +fn a_device_can_boot_and_then_die() { + let mut d = DeviceModel::new(&[dies!(20, 30)]); + d.set_reset(false, 0); + + assert_eq!(d.poll(20), Phase::Ready); + assert_eq!(d.next_event_at(), Some(50)); + assert_eq!(d.poll(49), Phase::Ready); + + assert_eq!(d.poll(50), Phase::Down); + assert!(!d.ready()); + assert_eq!(d.next_event_at(), None); + assert_eq!(d.take_transition(), Some(up(20))); + assert_eq!(d.take_transition(), Some(down(50))); +} + +#[test] +fn a_late_poll_applies_both_changes_in_order() { + let mut d = DeviceModel::new(&[dies!(20, 30)]); + d.set_reset(false, 0); + + assert_eq!(d.poll(1_000), Phase::Down); + assert_eq!(d.take_transition(), Some(up(20))); + assert_eq!(d.take_transition(), Some(down(50))); +} + +#[test] +fn a_dead_device_comes_back_only_through_reset() { + let mut d = DeviceModel::new(&[dies!(10, 10), boots!(10)]); + d.set_reset(false, 0); + assert_eq!(d.poll(100), Phase::Down); + + // Nothing but a reset brings it back. + assert_eq!(d.poll(10_000), Phase::Down); + + d.set_reset(true, 200); + d.set_reset(false, 210); + assert_eq!(d.poll(220), Phase::Ready); + assert_eq!(d.poll(1_000_000), Phase::Ready, "the second entry stays up"); +} + +#[test] +fn next_event_at_follows_the_phase() { + let mut d = DeviceModel::new(&[dies!(10, 5), Behaviour::Hang, boots!(1)]); + assert_eq!(d.next_event_at(), None, "held"); + + d.set_reset(false, 0); + assert_eq!(d.next_event_at(), Some(10), "booting"); + d.poll(10); + assert_eq!(d.next_event_at(), Some(15), "ready, about to fail"); + d.poll(15); + assert_eq!(d.next_event_at(), None, "down"); + + d.set_reset(true, 20); + d.set_reset(false, 20); + assert_eq!(d.next_event_at(), None, "hung"); + + d.set_reset(true, 30); + d.set_reset(false, 30); + d.poll(31); + assert_eq!(d.phase(), Phase::Ready); + assert_eq!(d.next_event_at(), None, "ready and stable"); +} + +// A caller may set the line every wake; only a real edge counts. +#[test] +fn repeating_a_level_changes_nothing() { + let mut d = DeviceModel::new(&[boots!(10)]); + + d.set_reset(true, 0); + d.set_reset(true, 1); + assert_eq!(d.releases(), 0); + + d.set_reset(false, 2); + d.set_reset(false, 3); + d.set_reset(false, 4); + assert_eq!(d.releases(), 1, "released once"); + assert_eq!( + d.poll(12), + Phase::Ready, + "the delay still runs from the first release" + ); +} + +#[test] +fn an_empty_script_hangs() { + let mut d = DeviceModel::new(&[]); + d.set_reset(false, 0); + + assert_eq!(d.poll(1_000), Phase::Hung); +} + +#[test] +fn transitions_beyond_the_queue_are_counted_not_kept() { + let mut d = DeviceModel::new(&[dies!(1, 1)]); + // Three boot-then-die cycles, never drained: six transitions, room for four. + for cycle in 0..3u64 { + let t = cycle * 100; + d.set_reset(true, t); + d.set_reset(false, t); + d.poll(t + 50); + } + + assert_eq!(d.dropped(), 2); + assert_eq!(d.take_transition(), Some(up(1))); + assert_eq!(d.take_transition(), Some(down(2))); + assert_eq!(d.take_transition(), Some(up(101))); + assert_eq!(d.take_transition(), Some(down(102))); + assert_eq!(d.take_transition(), None); +} + +#[test] +fn the_queue_is_usable_again_once_drained() { + let mut d = DeviceModel::new(&[dies!(1, 1)]); + for cycle in 0..3u64 { + let t = cycle * 100; + d.set_reset(true, t); + d.set_reset(false, t); + d.poll(t + 50); + } + while d.take_transition().is_some() {} + + d.set_reset(true, 1_000); + d.set_reset(false, 1_000); + d.poll(1_050); + + assert_eq!(d.take_transition(), Some(up(1_001))); + assert_eq!(d.take_transition(), Some(down(1_002))); +} + +#[test] +fn a_clock_that_goes_backwards_does_not_panic() { + let mut d = DeviceModel::new(&[boots!(50)]); + d.set_reset(false, 100); + + assert_eq!(d.poll(40), Phase::Booting, "earlier than the release"); + d.set_reset(true, 10); + assert_eq!(d.phase(), Phase::Held); +} + +#[test] +fn a_huge_delay_saturates_instead_of_overflowing() { + let mut d = DeviceModel::new(&[boots!(u64::MAX)]); + d.set_reset(false, 100); + + assert_eq!(d.next_event_at(), Some(u64::MAX)); + assert_eq!(d.poll(u64::MAX - 1), Phase::Booting); +}