Skip to main content

nros_node/executor/
monitor.rs

1//! On-target contract monitors.
2//!
3//! The baked shape mirrors the per-node `qos_overrides` table: codegen emits a
4//! `&'static [MonitorSpec]` table (plus one `static PubMonitorCell` per
5//! contracted publisher) from the SystemModel's contract layer; the entry
6//! installs it on the executor before entity creation. An uncontracted
7//! image bakes an empty table — every path below dead-code-eliminates.
8//!
9//! Publish counting is an atomic bump on the publisher handle (no clock,
10//! no lock on the hot path); the rate check runs on spin ticks over a
11//! ~[`RATE_CHECK_INTERVAL_US`] window and pushes violations into a small
12//! ring the entry glue drains into the `nros-diagnostics` reporter.
13//!
14//! W3b.5 adds three more rules on the same drain:
15//! - `max-age-runtime` — subscriber take-age (epoch_now - header.stamp
16//!   peeked from the raw CDR buffer at `RosMessage::STAMP_OFFSET`,
17//!   recorded into a [`SubMonitorCell`] on the take path).
18//! - `max-latency-runtime` — node-path (take → publish) latency: the
19//!   dispatch elapsed time is attributed to every monitored publisher
20//!   whose counter advanced during that dispatch (an upper bound on
21//!   take → publish, measured on the executor's monotonic clock). The span
22//!   is callback entry to exit, for every dispatch kind: a timer callback
23//!   is timed whether it fires in the drains or in the trigger-miss sweep,
24//!   and a service call it makes is inside the span. The
25//!   timer's release jitter (a late start) is not part of it; that is
26//!   `release-jitter-runtime`.
27//! - `deadline-miss-runtime` — a dispatched callback ran past its bound
28//!   SchedContext's `deadline_us`; what ELSE happens is the sched task's
29//!   [`DeadlineAction`](super::sched_context::DeadlineAction).
30//!
31//! The route rule sits beside it:
32//! - `route-latency-runtime` -- a node path whose trigger is an INPUT is
33//!   budgeted from the TAKE of that input to its output, and on a node that
34//!   reads its input on a timer tick that span includes the wait for the next
35//!   tick. `max-latency-runtime` times one dispatch and cannot see the wait,
36//!   so a route made of a long tick wait and a slow dispatch could exceed its
37//!   budget while every callback passed. The executor stamps the dispatch that
38//!   takes the trigger input (the earliest take not yet answered) and, at the
39//!   end of a dispatch that published one of the path's outputs, judges
40//!   take-to-dispatch-end against the path's `max_latency_ms`
41//!   (`route_take`, `route_judge`). Record only: the rule has no action.
42//!
43//! One more rule runs on the same drain, and it is the other half of
44//! what the contract's `on_violation` lowers to:
45//! - `silence-runtime` -- a contracted subscription that took NOTHING for a
46//!   whole `max_age_ms` window (`check_silence`). A violation is either "the
47//!   callback ran too long", which is the deadline action, or "the input
48//!   stopped coming", which is this; the four rules above can only see the
49//!   first kind.
50
51use core::sync::atomic::Ordering;
52// portable-atomic: RMW ops (fetch_add/fetch_max/swap) exist even on
53// riscv32imc / Cortex-M0+ that lack native CAS (same choice as
54// `SporadicState` / `AtomicSporadicState` in sched_context.rs).
55use portable_atomic::AtomicU32;
56
57/// One contracted publisher's counters. Baked as a `static` by codegen
58/// (or declared by the fixture); the publisher handle bumps `count` on
59/// every publish, the executor reads deltas on spin ticks.
60#[derive(Debug, Default)]
61pub struct PubMonitorCell {
62    pub count: AtomicU32,
63    /// W3b.5 — max observed take→publish latency (µs) in the current
64    /// check window. Written by the dispatch loop (fetch_max), drained
65    /// (swap 0) by the latency check.
66    pub max_latency_us: AtomicU32,
67    /// Age of the stamp this publisher last put ON THE WIRE, in
68    /// microseconds: epoch_now - outgoing header.stamp.
69    ///
70    /// Distinct from `max_latency_us`, which times this node's own
71    /// take→publish work. This says how old the DATA is that the node just
72    /// published, which is the quantity a chain is made of.
73    ///
74    /// It exists to answer a question `max-age-runtime` cannot. That rule
75    /// measures epoch_now - stamp on the TAKE path, so if every node in a
76    /// chain propagates the original stamp -- the usual ROS convention, each
77    /// node copying its input's stamp to its output -- the age at the final
78    /// consumer already IS the end-to-end latency. If any node re-stamps
79    /// with `now`, the clock silently resets and the same number becomes
80    /// single-hop age instead. Same units, same magnitude, no warning.
81    ///
82    /// A publish age near zero on a node that consumes input is the
83    /// signature of re-stamping. Recording it here is what lets a chain's
84    /// provenance be checked at all, rather than assumed.
85    ///
86    /// `0` = never observed, matching the other cells: the type has no
87    /// `STAMP_OFFSET`, or no epoch source is installed.
88    pub last_publish_stamp_age_us: AtomicU32,
89    /// The route rule's state for this output
90    /// ([`MonitorSpec::route_trigger`]): the trigger subscription's executor
91    /// slot + 1 in the low 16 bits (0 = no subscription bound, set when the
92    /// subscription registers), [`ROUTE_VIOLATED`] and [`ROUTE_PENDING`] above.
93    pub route: AtomicU32,
94    /// When the earliest take not yet answered by a publish of
95    /// this output happened, executor clock in microseconds (wrapping). Valid
96    /// while [`ROUTE_PENDING`] is set in `route`.
97    pub route_take_us: AtomicU32,
98}
99
100/// `PubMonitorCell::route`: a take of the trigger input is
101/// waiting for this output.
102pub const ROUTE_PENDING: u32 = 1 << 31;
103/// `PubMonitorCell::route`: the last judged route was over its
104/// budget (report once until one is within it, as the latency rule does).
105pub const ROUTE_VIOLATED: u32 = 1 << 30;
106/// `PubMonitorCell::route`: the bound slot + 1.
107pub const ROUTE_SLOT_MASK: u32 = 0xffff;
108
109impl PubMonitorCell {
110    pub const fn new() -> Self {
111        Self {
112            count: AtomicU32::new(0),
113            max_latency_us: AtomicU32::new(0),
114            last_publish_stamp_age_us: AtomicU32::new(0),
115            route: AtomicU32::new(0),
116            route_take_us: AtomicU32::new(0),
117        }
118    }
119}
120
121/// One contracted subscriber's take-age accumulator (W3b.5). The take
122/// path records epoch_now - header.stamp per message (fetch_max); the
123/// age check drains it (swap 0) per window.
124#[derive(Debug, Default)]
125pub struct SubMonitorCell {
126    /// Max observed take-age (ms) in the current check window.
127    pub max_age_ms: AtomicU32,
128    /// Observations recorded since the last check, drained
129    /// (swap 0) by `check_age`. The age itself cannot answer "did anything
130    /// arrive": a window with no take and a window whose only take was
131    /// perfectly fresh both leave `max_age_ms` at 0.
132    pub takes: AtomicU32,
133    /// The executor slot + 1 whose readiness is this
134    /// endpoint's arrival evidence, set when the contract's `deadline` is
135    /// judged here rather than by the backend ([`admit_contract_deadline`]).
136    /// 0 = not armed: the backend judges the deadline, or none is declared.
137    pub deadline_slot: AtomicU32,
138    /// Spins on which the armed slot had data, drained by
139    /// `check_age`. Counted for ANY message type, stamped or not, because a
140    /// deadline is a promise about arrival and says nothing about stamps.
141    pub arrivals: AtomicU32,
142}
143
144impl SubMonitorCell {
145    pub const fn new() -> Self {
146        Self {
147            max_age_ms: AtomicU32::new(0),
148            takes: AtomicU32::new(0),
149            deadline_slot: AtomicU32::new(0),
150            arrivals: AtomicU32::new(0),
151        }
152    }
153
154    /// Take-path hook: record one message's age. `stamp_us` is the
155    /// peeked `header.stamp` as µs since the UNIX epoch, `epoch_now_us`
156    /// the receive-side wall clock. A stamp from the future clamps to 0.
157    ///
158    /// Also the silence rule's only evidence that this
159    /// endpoint is being fed. It counts what the AGE rule can see, which is
160    /// stamped takes on a type that carries a stamp: a contracted endpoint
161    /// whose messages carry no readable stamp records nothing here and is
162    /// reported silent. That is the intended verdict rather than a gap --
163    /// its `max_age_ms` cannot be judged either, and an unjudgeable promise
164    /// reported as met is the silent class this phase exists to remove.
165    pub fn observe(&self, stamp_us: u64, epoch_now_us: u64) {
166        let age_ms = (epoch_now_us.saturating_sub(stamp_us) / 1_000).min(u32::MAX as u64) as u32;
167        self.max_age_ms.fetch_max(age_ms, Ordering::Relaxed);
168        self.takes.fetch_add(1, Ordering::Relaxed);
169    }
170
171    /// A stamped take on an image with NO epoch source: the
172    /// stamp was read (the type carries one and it is a real time), so the
173    /// take is the silence rule's evidence exactly as [`Self::observe`]'s is,
174    /// but its age cannot be computed against a clock that is not on the
175    /// stamp's epoch, so `max_age_ms` is left alone and `max-age-runtime`
176    /// judges nothing on such an image. An unstamped take is still not
177    /// evidence: nothing here counts arrivals.
178    pub fn observe_unaged(&self) {
179        self.takes.fetch_add(1, Ordering::Relaxed);
180    }
181}
182
183/// Peek `Time { i32 sec; u32 nanosec }` little-endian at `offset` in a
184/// raw CDR receive buffer (encapsulation header included) and return µs
185/// since the UNIX epoch. `None` when the buffer is too short or the
186/// stamp is pre-epoch/zero (unstamped messages never fire age monitors).
187/// Record the age of the stamp a publisher just put on the wire.
188///
189/// Called from the publish path with the encoded CDR still in hand, using the
190/// same `STAMP_OFFSET` peek the take path uses. A no-op when the type carries
191/// no stamp, when no epoch source is installed, or when the publisher is
192/// uncontracted -- the same three ways `observe_age` folds away.
193///
194/// Stores rather than accumulates: this is "how old was the last thing
195/// published", a state, not a window maximum. A chain check wants the current
196/// value, and a max would be pinned forever by one stale message at startup.
197#[inline]
198pub fn observe_publish_stamp(cell: &PubMonitorCell, raw: &[u8], offset: usize, now_us: u64) {
199    if let Some(stamp_us) = peek_stamp_us(raw, offset) {
200        let age = now_us.saturating_sub(stamp_us).min(u32::MAX as u64) as u32;
201        cell.last_publish_stamp_age_us.store(age, Ordering::Relaxed);
202    }
203}
204
205pub fn peek_stamp_us(raw: &[u8], offset: usize) -> Option<u64> {
206    let sec_b = raw.get(offset..offset + 4)?;
207    let nsec_b = raw.get(offset + 4..offset + 8)?;
208    let sec = i32::from_le_bytes([sec_b[0], sec_b[1], sec_b[2], sec_b[3]]);
209    let nsec = u32::from_le_bytes([nsec_b[0], nsec_b[1], nsec_b[2], nsec_b[3]]);
210    if sec <= 0 {
211        return None;
212    }
213    Some(sec as u64 * 1_000_000 + nsec as u64 / 1_000)
214}
215
216/// One monitored publisher endpoint.
217#[derive(Debug, Clone, Copy)]
218pub struct MonitorSpec {
219    /// Topic name EXACTLY as the node passes it to `create_publisher`
220    /// (the SystemModel's wiring carries the same resolved name).
221    pub topic: &'static str,
222    /// Endpoint ref for violation reports (`<node FQN>/<endpoint>` — the
223    /// SystemModel contract key).
224    pub fqn: &'static str,
225    /// Declared publisher guarantee, in milli-Hz (fixed point: Hz × 1000).
226    /// 0 = no rate contract on this endpoint.
227    pub min_rate_hz_milli: u32,
228    /// W3b.5 — node-path budget (ms) for paths whose OUTPUT is this
229    /// endpoint (`contracts.node_paths[..].max_latency_ms`). 0 = no
230    /// latency contract.
231    pub max_latency_ms: u32,
232    /// The topic of the INPUT that triggers a node path whose
233    /// output is this endpoint (`contracts.node_paths[..].input`, resolved to
234    /// its wiring topic EXACTLY as the node passes it to
235    /// `create_subscription`), or `""` for none. A subscription on this topic
236    /// registered on the same executor is the route's trigger.
237    pub route_trigger: &'static str,
238    /// That path's budget (ms), from the take of the trigger to
239    /// this output (`route-latency-runtime`). 0 = no route contract.
240    pub route_max_latency_ms: u32,
241    /// The route's SUPERVISED deadline (ms) from the take of the
242    /// trigger: a take still unanswered at `take + route_deadline_ms` is
243    /// reported (`route-deadline-runtime`) and the executor's reaction hook is
244    /// called, without waiting for an output that may never come. 0 = the
245    /// route is not supervised (only the completion verdict above judges it).
246    /// Needs `route_trigger`; ignored without it.
247    pub route_deadline_ms: u32,
248    /// The reaction the hook is asked to start when the deadline
249    /// passes: an id codegen assigns to the contract's `reaction` path
250    /// (1-based; [`REACTION_NONE`] = none named). Opaque to the executor.
251    pub reaction_id: u16,
252    /// Which mechanism the contract chose to supervise this
253    /// route: [`MECHANISM_EXECUTOR`] (this check, in the spin loop) or
254    /// [`MECHANISM_TIMER`] (an independent timer the port arms from
255    /// `Executor::route_next_due_us`). The executor checks the deadline either
256    /// way and passes the mechanism to the hook.
257    pub mechanism: u8,
258    /// The endpoint's counter cell.
259    pub cell: &'static PubMonitorCell,
260}
261
262/// [`MonitorSpec::reaction_id`]: no reaction named.
263pub const REACTION_NONE: u16 = 0;
264/// [`MonitorSpec::mechanism`]: checked in the executor's spin
265/// loop. Catches a slow route, not a callback that never returns.
266pub const MECHANISM_EXECUTOR: u8 = 0;
267/// [`MonitorSpec::mechanism`]: an independent timer outside the
268/// executor (the port's), which also catches a stuck callback.
269pub const MECHANISM_TIMER: u8 = 1;
270
271/// What the reaction hook receives when a supervised route
272/// passes its deadline. `repr(C)`: the C ABI hands the same struct through.
273#[repr(C)]
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
275pub struct ReactionEvent {
276    /// [`MonitorSpec::reaction_id`] of the row (or, for `hazard-detected`,
277    /// [`HazardSpec::reaction_id`] of the hazard).
278    pub reaction_id: u32,
279    /// Index of the row in the installed monitor table (for
280    /// `hazard-detected`, of the hazard in the installed hazard table).
281    pub row: u32,
282    /// [`rule_code`] of the verdict (`route-deadline-runtime`).
283    pub rule_code: u32,
284    /// Time from the take to the check, ms.
285    pub measured_ms: u32,
286    /// The deadline, ms.
287    pub declared_ms: u32,
288    /// [`MonitorSpec::mechanism`] of the row.
289    pub mechanism: u8,
290    /// The executor's monotonic µs when the
291    /// verdict fired (for `hazard-detected`, the detection tick: where the
292    /// hazard's rung routes start, so a hook can time its own reaction from
293    /// the same instant). 0 when the executor has no clock.
294    pub fired_at_us: u64,
295}
296
297/// The reaction hook: called on the spin thread, inside
298/// `spin_once`, once per missed route deadline. It must not block; it starts
299/// the fallback (or hands it to another thread) and returns. `ctx` is what
300/// was registered with the hook.
301pub type ReactionHookFn =
302    unsafe extern "C" fn(event: *const ReactionEvent, ctx: *mut core::ffi::c_void);
303
304/// One monitored subscriber endpoint (W3b.5 age contracts). Separate
305/// table from [`MonitorSpec`] — sub contracts key different endpoints
306/// and need no publish counter.
307#[derive(Debug, Clone, Copy)]
308pub struct AgeMonitorSpec {
309    /// Topic name EXACTLY as the node passes it to `create_subscription`.
310    pub topic: &'static str,
311    /// Endpoint ref for violation reports (the SystemModel contract key).
312    pub fqn: &'static str,
313    /// Declared max take-age (ms). 0 = no age contract.
314    pub max_age_ms: u32,
315    /// The contract's `deadline` for this endpoint, in the
316    /// wire's milliseconds. 0 = none declared. Judged HERE only when the
317    /// subscription's backend cannot judge it (see
318    /// [`admit_contract_deadline`]); otherwise the backend's own deadline
319    /// event is the detector and this row carries the number unread.
320    pub deadline_ms: u32,
321    /// The endpoint's age accumulator.
322    pub cell: &'static SubMonitorCell,
323}
324
325/// What a subscription's creation does about its contract
326/// `deadline`, decided from the backend's OWN answer
327/// (`Session::supported_qos_policies`) at the moment it is created.
328///
329/// The served set is a run-time fact -- a C backend answers through the
330/// vtable -- so it is asked here rather than restated in a build
331/// table that could disagree with it. Three outcomes:
332///
333/// * the backend honours `DEADLINE` and the profile carries the deadline: the
334///   backend judges it, nothing is armed;
335/// * the backend does not honour `DEADLINE`: a profile deadline EQUAL to the
336///   contract's is stripped (it came from the contract, and refusing it at
337///   create would turn a judgeable promise into a boot failure), and the row
338///   is armed so the silence rule judges it;
339/// * the profile never carried the deadline (a registration path that does
340///   not fold the launch overrides): the backend cannot judge what it was
341///   never told, so the row is armed too.
342///
343/// A profile deadline that DIFFERS from the contract's is the caller's own
344/// request and is left alone, so a backend that cannot serve it still refuses
345/// it by name. Returns the profile to create with and the row to arm.
346pub fn admit_contract_deadline(
347    mut qos: nros_rmw::QoSProfile,
348    served: nros_rmw::QoSPolicyMask,
349    ages: &'static [AgeMonitorSpec],
350    topic: &str,
351) -> (nros_rmw::QoSProfile, Option<&'static AgeMonitorSpec>) {
352    let Some(spec) = ages.iter().find(|a| a.topic == topic && a.deadline_ms > 0) else {
353        return (qos, None);
354    };
355    let serves = served.0 & nros_rmw::QoSPolicyMask::DEADLINE.0 != 0;
356    if serves && qos.deadline_ms != 0 {
357        return (qos, None);
358    }
359    if !serves && qos.deadline_ms == spec.deadline_ms {
360        qos.deadline_ms = 0;
361    }
362    (qos, Some(spec))
363}
364
365/// phase-462 W5b -- a released subscription's slot stops being any row's
366/// arrival evidence; its slot may be claimed by an unrelated entry next.
367pub(crate) fn deadline_unbind(ages: &[AgeMonitorSpec], slot: usize) {
368    for spec in ages {
369        let _ = spec.cell.deadline_slot.compare_exchange(
370            slot as u32 + 1,
371            0,
372            Ordering::Relaxed,
373            Ordering::Relaxed,
374        );
375    }
376}
377
378/// phase-462 W5b -- credit one arrival to every armed row whose slot is in
379/// `ready` (the executor's readiness bits for this spin).
380///
381/// Readiness, not dispatch, is the evidence, because it is the one point every
382/// entry passes on the spin thread: an os-priority entry is dispatched on a
383/// worker thread that holds no executor state, and a cooperative one only when
384/// its trigger passes.
385pub(crate) fn credit_arrivals(ages: &[AgeMonitorSpec], ready: super::slot_mask::SlotMask) {
386    for spec in ages {
387        let slot = spec.cell.deadline_slot.load(Ordering::Relaxed);
388        if slot != 0 && ready.test(slot as usize - 1) {
389            spec.cell.arrivals.fetch_add(1, Ordering::Relaxed);
390        }
391    }
392}
393
394/// phase-436 E4 — how often the stack-headroom rule may query the port, in µs.
395///
396/// On a painted Zephyr stack the query walks every UNUSED byte from the stack
397/// base (`z_stack_space_get`), so querying on every spin put that scan inside
398/// the control loop. The high-water mark only grows, so a throttled check sees
399/// the same low mark and only sees it later. Since E5 the query is also capped
400/// at the declared minimum (`stack_unused_bytes_upto`), so it reads at most
401/// that many bytes.
402pub(crate) const STACK_HEADROOM_CHECK_INTERVAL_US: u64 = 1_000_000;
403
404/// The same limit for a build with no clock: once per this many spins.
405pub(crate) const STACK_HEADROOM_CHECK_SPIN_STRIDE: u32 = 1_000;
406
407/// Whether the stack-headroom query is due.
408///
409/// `last_check_us` is `None` until the first check, which is immediate, so a
410/// bound set at boot is checked on the first spin. After that a clocked build
411/// waits one full interval and a clockless build one full stride of spins.
412pub(crate) fn stack_headroom_check_due(
413    now_us: Option<u64>,
414    last_check_us: Option<u64>,
415    spins_since_check: u32,
416) -> bool {
417    match (last_check_us, now_us) {
418        (None, _) => true,
419        (Some(last), Some(now)) => now.saturating_sub(last) >= STACK_HEADROOM_CHECK_INTERVAL_US,
420        (Some(_), None) => spins_since_check >= STACK_HEADROOM_CHECK_SPIN_STRIDE,
421    }
422}
423
424/// Rate-check window (µs). Matches play_launch's ~5 s time-based trigger
425/// so both runtimes converge on comparable cadence.
426pub const RATE_CHECK_INTERVAL_US: u64 = 5_000_000;
427
428/// Max RATE/LATENCY-monitored endpoints per executor (inline table, no_std).
429///
430/// Generated, not a literal: the
431/// `NROS_EXECUTOR_MAX_MONITORS` knob, whose derived rung is the image's own
432/// `monitor_rows` count (the sizing descriptor's `[image] monitor_rows`), 8 when nothing
433/// states or derives it. A table longer than this is REFUSED at install
434/// ([`check_table_capacity`]), never truncated: the spin loop inspects only the
435/// first `MAX_MONITORS` specs, so a truncating install would boot with the rest
436/// of the contract silently unwatched.
437pub const MAX_MONITORS: usize = crate::config::MAX_MONITORS;
438/// Max AGE-monitored subscriptions per executor -- the second table, on its
439/// own knob (`NROS_EXECUTOR_MAX_AGE_MONITORS`, derived from `age_rows`) so an
440/// image with rate contracts and no age contracts pays for one table only.
441pub const MAX_AGE_MONITORS: usize = crate::config::MAX_AGE_MONITORS;
442
443/// A monitor table longer than the executor can watch.
444///
445/// Its `Display` NAMES THE KNOB to raise (refuse and name the
446/// remedy), so every installer that refuses reports the same words.
447#[derive(Debug, Clone, Copy, PartialEq, Eq)]
448pub struct MonitorTableFull {
449    /// `"NROS_EXECUTOR_MAX_MONITORS"` or `"NROS_EXECUTOR_MAX_AGE_MONITORS"`.
450    pub knob: &'static str,
451    /// Rows the table carries.
452    pub rows: usize,
453    /// Rows this build can watch (the knob's resolved value).
454    pub capacity: usize,
455}
456
457impl core::fmt::Display for MonitorTableFull {
458    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
459        write!(
460            f,
461            "monitor table has {} rows but this executor watches {}; raise {} \
462             (it derives from the contract's row count when nothing states it)",
463            self.rows, self.capacity, self.knob
464        )
465    }
466}
467
468/// A mode's variant table is not the base table's length,
469/// refused by [`super::Executor::set_mode_tables`].
470#[derive(Debug, Clone, Copy, PartialEq, Eq)]
471pub struct ModeTablesMismatch {
472    /// The mode id whose tables differ.
473    pub mode: u16,
474    /// `(the mode's, the base's)` rate/latency row count.
475    pub monitors: (usize, usize),
476    /// `(the mode's, the base's)` age row count.
477    pub ages: (usize, usize),
478    /// A deadline row naming a SchedContext this executor
479    /// does not have.
480    pub missing_sc: Option<u8>,
481}
482
483impl core::fmt::Display for ModeTablesMismatch {
484    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
485        if let Some(sc) = self.missing_sc {
486            return write!(
487                f,
488                "mode {} moves the deadline of sched context {sc}, which this executor does \
489                 not have: install the mode tables after the sched contexts (re-run the bake)",
490                self.mode
491            );
492        }
493        write!(
494            f,
495            "mode {} bakes {} rate/latency and {} age rows where the base has {} and {}: a \
496             mode is a variant of the base tables, row for row (re-run the bake)",
497            self.mode, self.monitors.0, self.ages.0, self.monitors.1, self.ages.1
498        )
499    }
500}
501
502/// Whether a table of `n_rows` rate/latency rows and `n_ages` age rows fits
503/// this build's executor. The rate table is judged first.
504pub fn check_table_capacity(n_rows: usize, n_ages: usize) -> Result<(), MonitorTableFull> {
505    check_capacity_against(n_rows, n_ages, MAX_MONITORS, MAX_AGE_MONITORS)
506}
507
508/// [`check_table_capacity`] against explicit capacities, so the refusal is
509/// testable at any knob value without rebuilding the crate.
510pub fn check_capacity_against(
511    n_rows: usize,
512    n_ages: usize,
513    max_rows: usize,
514    max_ages: usize,
515) -> Result<(), MonitorTableFull> {
516    if n_rows > max_rows {
517        return Err(MonitorTableFull {
518            knob: "NROS_EXECUTOR_MAX_MONITORS",
519            rows: n_rows,
520            capacity: max_rows,
521        });
522    }
523    if n_ages > max_ages {
524        return Err(MonitorTableFull {
525            knob: "NROS_EXECUTOR_MAX_AGE_MONITORS",
526            rows: n_ages,
527            capacity: max_ages,
528        });
529    }
530    Ok(())
531}
532/// Violation ring depth, per executor, and the slot count of the image-wide
533/// SWD record ([`ViolationRecord`]).
534///
535/// `NROS_EXECUTOR_MAX_VIOLATIONS` (Zephyr:
536/// `CONFIG_NROS_EXECUTOR_MAX_VIOLATIONS`), default 8. The ring keeps the
537/// LATEST this-many verdicts, so the depth bounds how much recent history a
538/// reader sees and never whether a late violation is kept at all.
539pub const MAX_VIOLATIONS: usize = crate::config::MAX_VIOLATIONS;
540
541/// A detected contract violation, in the play_launch rule-id vocabulary.
542#[derive(Debug, Clone)]
543pub struct Violation {
544    /// `"rate-hierarchy-runtime"` | `"max-age-runtime"` |
545    /// `"max-latency-runtime"` | `"deadline-miss-runtime"` |
546    /// `"stack-headroom-runtime"` | `"alive-supervision-runtime"` |
547    /// `"silence-runtime"` | `"route-latency-runtime"` |
548    /// `"route-deadline-runtime"` |
549    /// `"hazard-route-runtime"` |
550    /// `"hazard-level-runtime"`.
551    pub rule: &'static str,
552    /// Violating endpoint ref (from the spec's `fqn`; the SC name for
553    /// deadline misses).
554    pub fqn: &'static str,
555    /// Measured value. Unit is per-rule: milli-Hz for the rate rule, ms
556    /// for age/latency, µs for deadline misses, dropped activations for
557    /// the timer-overrun rule.
558    pub measured: u32,
559    /// Declared bound, same unit as `measured`.
560    pub declared: u32,
561    /// The NAME of the fallback level a
562    /// `hazard-level-runtime` report is about, as the model spells it (the
563    /// mode key / `degradation_levels[].level`); `""` for every other rule.
564    ///
565    /// A field, and not a lookup at rendering time, because everything that
566    /// renders a verdict for a person -- the log line, the drain-and-report
567    /// line, the `/diagnostics` message and the C/C++ drain -- receives the
568    /// `Violation` alone, and none of them holds the hazard table that would
569    /// resolve `measured` (the level's index) back to a name. The text is a
570    /// `'static` borrow of the baked `RungSpec::level`, so it costs a pointer
571    /// and a length and copies nothing. The trace markers and the SWD record
572    /// do NOT carry it: they keep their four words and seven-word slots, and a
573    /// reader resolves the index through the model, as it already resolves
574    /// `fqn` through its hash.
575    pub level: &'static str,
576}
577
578/// Every rule id the executor reports, in WIRE ORDER: a rule's
579/// numeric code is its index here plus one, and 0 means "not a rule this table
580/// knows".
581///
582/// The code is what a trace marker and the SWD record carry, because neither
583/// can carry a string. Append only: a capture or a RAM dump taken before a
584/// reorder would silently decode as the wrong rule, which is the class the
585/// callback-trace marker ids are frozen against (`callback_trace.rs`).
586pub const RULE_IDS: [&str; 17] = [
587    "rate-hierarchy-runtime",
588    "max-age-runtime",
589    "max-latency-runtime",
590    "deadline-miss-runtime",
591    "stack-headroom-runtime",
592    "alive-supervision-runtime",
593    "silence-runtime",
594    "timer-overrun-runtime",
595    "release-jitter-runtime",
596    // phase10-B3.
597    "route-latency-runtime",
598    // phase-503.
599    "route-deadline-runtime",
600    // phase-462 W3b -- the hazard observer, in play_launch's spelling (no
601    // `-runtime` suffix) so one log reader serves both sides of a bridge.
602    "hazard-detected",
603    "hazard-reaction",
604    "hazard-recovered",
605    // phase-462 W4c.
606    "mode-switch-runtime",
607    // play_launch phase 96 W4.2 (phase 85 D4) -- a hazard's rung route.
608    "hazard-route-runtime",
609    // phase-560 W8 (play_launch phase 102 M5 E7) -- the fallback level a
610    // hazard's ladder is on, at detection and on every fall.
611    "hazard-level-runtime",
612];
613
614/// The wire code of `rule` ([`RULE_IDS`] index + 1), or 0 for a rule the
615/// table does not know.
616pub fn rule_code(rule: &str) -> u32 {
617    RULE_IDS
618        .iter()
619        .position(|r| *r == rule)
620        .map(|i| i as u32 + 1)
621        .unwrap_or(0)
622}
623
624/// The rule a wire code names, or `None` for 0 / an unknown code.
625pub fn rule_name(code: u32) -> Option<&'static str> {
626    RULE_IDS.get((code as usize).checked_sub(1)?).copied()
627}
628
629/// 32-bit FNV-1a of an endpoint ref -- the identity a trace marker and the SWD
630/// record carry for `Violation::fqn` (a string neither can hold).
631///
632/// FNV-1a because a decoder can recompute it in one line from the model's
633/// endpoint list (`scripts/read-violation-record.py` does), with no table
634/// baked into the image.
635pub const fn fqn_hash(fqn: &str) -> u32 {
636    let b = fqn.as_bytes();
637    let mut h: u32 = 0x811c_9dc5;
638    let mut i = 0;
639    while i < b.len() {
640        h ^= b[i] as u32;
641        h = h.wrapping_mul(0x0100_0193);
642        i += 1;
643    }
644    h
645}
646
647/// Trace marker: a stored violation, `seq << 8 | rule code`.
648/// The id block continues `callback_trace`'s 16-20; ids 1-7 are the
649/// application's and are never used here.
650pub const MARKER_VIOLATION: u32 = 21;
651/// Trace marker: the endpoint ref's [`fqn_hash`].
652pub const MARKER_VIOLATION_FQN: u32 = 22;
653/// Trace marker: `measured`.
654pub const MARKER_VIOLATION_MEASURED: u32 = 23;
655/// Trace marker: `declared`.
656pub const MARKER_VIOLATION_DECLARED: u32 = 24;
657
658/// The four `(marker_id, arg)` events one stored violation
659/// becomes in a trace (`callback_trace` emits them, in this order, when the
660/// `trace-callbacks` feature is on and a sink is installed). `seq` is the
661/// executor's sequence number; its low 24 bits ride in the first event.
662pub fn violation_marker_words(seq: u32, v: &Violation) -> [(u32, u32); 4] {
663    [
664        (
665            MARKER_VIOLATION,
666            ((seq & 0x00ff_ffff) << 8) | (rule_code(v.rule) & 0xff),
667        ),
668        (MARKER_VIOLATION_FQN, fqn_hash(v.fqn)),
669        (MARKER_VIOLATION_MEASURED, v.measured),
670        (MARKER_VIOLATION_DECLARED, v.declared),
671    ]
672}
673
674/// `"NRVR"` -- nano-ros violation record.
675pub const RECORD_MAGIC: u32 = 0x4e52_5652;
676/// [`ViolationRecord`] layout version. Bump on any field change; a reader
677/// refuses a version it does not know (`scripts/read-violation-record.py`).
678pub const RECORD_VERSION: u32 = 1;
679/// `u32` words in one [`ViolationSlot`].
680pub const RECORD_SLOT_WORDS: u32 = 7;
681/// `u32` words in the [`ViolationRecord`] header, before the first slot.
682pub const RECORD_HEADER_WORDS: u32 = 10;
683
684/// One slot of the SWD record. Every field is a `u32` on every target, so the
685/// layout is the same on a 32-bit board and a 64-bit host.
686#[repr(C)]
687#[derive(Debug)]
688pub struct ViolationSlot {
689    /// 1-based sequence number of the violation in this slot, 0 = empty.
690    /// Written LAST (zeroed first), so a reader that sees a non-zero `seq`
691    /// twice around a read of the other words has a whole entry.
692    pub seq: AtomicU32,
693    /// [`rule_code`].
694    pub rule: AtomicU32,
695    /// [`fqn_hash`] of the endpoint ref.
696    pub fqn_hash: AtomicU32,
697    pub measured: AtomicU32,
698    pub declared: AtomicU32,
699    /// Address of the endpoint ref's bytes (exact on a 32-bit target, the low
700    /// half of it on a 64-bit host) and its length: the text is in the
701    /// image's rodata, so a reader with the ELF can print the name.
702    pub fqn_addr: AtomicU32,
703    pub fqn_len: AtomicU32,
704}
705
706impl ViolationSlot {
707    pub const fn new() -> Self {
708        Self {
709            seq: AtomicU32::new(0),
710            rule: AtomicU32::new(0),
711            fqn_hash: AtomicU32::new(0),
712            measured: AtomicU32::new(0),
713            declared: AtomicU32::new(0),
714            fqn_addr: AtomicU32::new(0),
715            fqn_len: AtomicU32::new(0),
716        }
717    }
718}
719
720impl Default for ViolationSlot {
721    fn default() -> Self {
722        Self::new()
723    }
724}
725
726/// The image-wide violation record a debugger reads by NAME,
727/// for a board whose console reaches nobody.
728///
729/// The executor's ring is carved out of executor storage (no symbol, and a
730/// drain empties it), so on one reference image it could only be found
731/// by scanning RAM for rule-id string pointers, and it held the FIRST eight
732/// verdicts since boot. This record is the black box beside it: a `#[repr(C)]`
733/// static, every word a `u32`, never drained, keeping the LATEST
734/// [`MAX_VIOLATIONS`] stored violations of every executor in the image, with
735/// the running total.
736///
737/// Layout (version [`RECORD_VERSION`], little-endian `u32` words):
738///
739/// | word | field | meaning |
740/// | --- | --- | --- |
741/// | 0 | `magic` | [`RECORD_MAGIC`] (`"NRVR"`) |
742/// | 1 | `version` | [`RECORD_VERSION`] |
743/// | 2 | `capacity` | slots (`NROS_EXECUTOR_MAX_VIOLATIONS`) |
744/// | 3 | `slot_words` | [`RECORD_SLOT_WORDS`] |
745/// | 4 | `total` | violations stored since boot (the last `seq`) |
746/// | 5 | `head` | slot the NEXT violation takes (`total % capacity`) |
747/// | 6 | `dropped` | entries overwritten (`total - capacity`, saturating) |
748/// | 7 | `suppressed_before_arm` | verdicts before the monitors armed, all executors |
749/// | 8 | `armed` | executors whose monitors armed (counted as each arms; at its first spin by default) |
750/// | 9 | `reserved` | 0 |
751/// | 10.. | `slots` | `capacity` x [`ViolationSlot`] |
752///
753/// The newest entry is in slot `(head + capacity - 1) % capacity`; reading
754/// `capacity` slots backwards from there gives newest to oldest, and a slot
755/// whose `seq` is 0 was never written.
756///
757/// Present only when the image asked for the boot report
758/// (`NROS_BOOT_REPORT=1`, Zephyr `CONFIG_NROS_BOOT_REPORT=y`) -- the same
759/// opt-in as the SWD boot record it sits beside, so an image that does not
760/// opt in is unchanged. Read it with `scripts/read-violation-record.py`.
761#[repr(C)]
762#[derive(Debug)]
763pub struct ViolationRecord<const N: usize> {
764    pub magic: AtomicU32,
765    pub version: AtomicU32,
766    pub capacity: AtomicU32,
767    pub slot_words: AtomicU32,
768    pub total: AtomicU32,
769    pub head: AtomicU32,
770    pub dropped: AtomicU32,
771    pub suppressed_before_arm: AtomicU32,
772    pub armed: AtomicU32,
773    pub reserved: AtomicU32,
774    pub slots: [ViolationSlot; N],
775}
776
777impl<const N: usize> ViolationRecord<N> {
778    /// A valid, empty record: the header is written at compile time, so a
779    /// record with `total == 0` reads as "no violation since boot" rather than
780    /// as uninitialised RAM.
781    pub const fn new() -> Self {
782        Self {
783            magic: AtomicU32::new(RECORD_MAGIC),
784            version: AtomicU32::new(RECORD_VERSION),
785            capacity: AtomicU32::new(N as u32),
786            slot_words: AtomicU32::new(RECORD_SLOT_WORDS),
787            total: AtomicU32::new(0),
788            head: AtomicU32::new(0),
789            dropped: AtomicU32::new(0),
790            suppressed_before_arm: AtomicU32::new(0),
791            armed: AtomicU32::new(0),
792            reserved: AtomicU32::new(0),
793            slots: [const { ViolationSlot::new() }; N],
794        }
795    }
796
797    /// Store one violation, overwriting the oldest when full. Returns its
798    /// 1-based sequence number.
799    ///
800    /// Lock-free and callable from any executor thread: the slot is claimed by
801    /// a `fetch_add` on `total`, so two executors never write one slot unless
802    /// `N` more violations land during one write.
803    pub fn store(&self, v: &Violation) -> u32 {
804        let seq = self.total.fetch_add(1, Ordering::AcqRel).wrapping_add(1);
805        if N == 0 {
806            return seq;
807        }
808        let slot = &self.slots[(seq as usize - 1) % N];
809        slot.seq.store(0, Ordering::Release);
810        slot.rule.store(rule_code(v.rule), Ordering::Relaxed);
811        slot.fqn_hash.store(fqn_hash(v.fqn), Ordering::Relaxed);
812        slot.measured.store(v.measured, Ordering::Relaxed);
813        slot.declared.store(v.declared, Ordering::Relaxed);
814        slot.fqn_addr
815            .store(v.fqn.as_ptr() as usize as u32, Ordering::Relaxed);
816        slot.fqn_len.store(v.fqn.len() as u32, Ordering::Relaxed);
817        slot.seq.store(seq, Ordering::Release);
818        self.head.store(seq % N as u32, Ordering::Relaxed);
819        self.dropped
820            .store(seq.saturating_sub(N as u32), Ordering::Relaxed);
821        seq
822    }
823
824    /// The stored entries, newest first, as `(seq, rule code, fqn hash,
825    /// measured, declared)`. For tests and on-target self-checks; a debugger
826    /// reads the words directly.
827    pub fn newest_first(&self, mut f: impl FnMut(u32, u32, u32, u32, u32)) {
828        let total = self.total.load(Ordering::Acquire);
829        let n = (total as usize).min(N);
830        for k in 0..n {
831            let seq = total - k as u32;
832            let slot = &self.slots[(seq as usize - 1) % N];
833            if slot.seq.load(Ordering::Acquire) != seq {
834                continue; // overwritten or mid-write
835            }
836            f(
837                seq,
838                slot.rule.load(Ordering::Relaxed),
839                slot.fqn_hash.load(Ordering::Relaxed),
840                slot.measured.load(Ordering::Relaxed),
841                slot.declared.load(Ordering::Relaxed),
842            );
843        }
844    }
845}
846
847impl<const N: usize> Default for ViolationRecord<N> {
848    fn default() -> Self {
849        Self::new()
850    }
851}
852
853/// THE record, by name: `nm zephyr.elf | grep
854/// NROS_VIOLATION_RECORD`. See [`ViolationRecord`] for the layout.
855#[cfg(nros_boot_report)]
856#[unsafe(no_mangle)]
857pub static NROS_VIOLATION_RECORD: ViolationRecord<MAX_VIOLATIONS> = ViolationRecord::new();
858
859/// phase-474 I2 -- application arm requests, image-wide. Each call of
860/// [`request_monitor_arming`] bumps it; an executor waiting for the
861/// application arms when it sees a value other than the one it was opened
862/// with, so a request made before an executor existed does not arm it.
863static ARM_REQUESTS: AtomicU32 = AtomicU32::new(0);
864
865/// The application says its start-up is over: arm the
866/// contract monitors of every executor in the image that waits for this
867/// (`NROS_MONITOR_ARM_ON_CALL`, or [`Executor::set_monitor_arming`]).
868///
869/// Callable from anywhere -- a node's callback, another thread -- because it
870/// only bumps an atomic; each executor arms at its next spin. On an executor
871/// that is already armed (the default: armed at the first spin) it does
872/// nothing. C: `rclc_monitors_arm()`; C++: `nros::arm_monitors()`.
873///
874/// [`Executor::set_monitor_arming`]: super::Executor::set_monitor_arming
875pub fn request_monitor_arming() {
876    ARM_REQUESTS.fetch_add(1, Ordering::AcqRel);
877}
878
879/// One contract MODE's variant of an executor's two monitor
880/// tables: the base tables' rows in the base's order, sharing the base's
881/// cells, with the mode's numbers.
882///
883/// Because the rows and cells are the base's, a publisher or subscription
884/// keeps the cell it bound at creation, and a hazard's guard keeps the row
885/// index it names; only the requirement each row is judged against changes.
886/// The bake guarantees that shape (`nros_orchestration_ir::mode_variants`);
887/// [`super::Executor::set_mode_tables`] refuses a table of another length.
888#[derive(Debug, Clone, Copy)]
889pub struct ModeTables {
890    /// The rate/latency table in this mode.
891    pub monitors: &'static [MonitorSpec],
892    /// The age table in this mode.
893    pub ages: &'static [AgeMonitorSpec],
894    /// The SchedContext deadlines this mode moves. Every
895    /// mode's table, the base's included, lists the SAME contexts, so entering
896    /// any mode leaves every moved deadline at that mode's value.
897    pub deadlines: &'static [ModeDeadline],
898    /// How long ENTERING this mode may take, ms: its reaction
899    /// path's `max_latency`. 0 = the contract states none.
900    pub switch_budget_ms: u32,
901    /// That reaction path's key, the `mode-switch-runtime`
902    /// report's endpoint ref ("" when there is none).
903    pub reaction: &'static str,
904}
905
906/// One SchedContext's deadline in one mode.
907///
908/// The deadline is the one sched task fact a switch can apply: the executor reads
909/// `SchedContext::deadline_us` each time it judges a dispatch. A priority is a
910/// thread's and a reservation is armed at boot, so the bake lists a mode that
911/// moves either instead of baking it.
912///
913/// `repr(C)`: the C ABI's `nros_cpp_mode_deadline_t` is the same two fields.
914#[repr(C)]
915#[derive(Debug, Clone, Copy, PartialEq, Eq)]
916pub struct ModeDeadline {
917    /// The SchedContext's id on this executor.
918    pub sc: u8,
919    /// The deadline in this mode, µs; 0 = none.
920    pub deadline_us: u32,
921}
922
923/// phase-462 W4c -- the `mode-switch-runtime` verdict for entering `t`: how
924/// long the request could have waited, against the mode's budget.
925///
926/// An executor enters a requested mode at its next spin, so a request
927/// waited at most the gap since the previous spin's check -- the measured
928/// value is that gap, an upper bound on the switch's own latency. `None` when
929/// the mode states no budget, the gap is within it, or there is no clock.
930pub(crate) fn check_mode_switch(t: &ModeTables, waited_ms: Option<u32>) -> Option<Violation> {
931    let waited = waited_ms?;
932    (t.switch_budget_ms != 0 && waited > t.switch_budget_ms).then_some(Violation {
933        rule: "mode-switch-runtime",
934        fqn: t.reaction,
935        measured: waited,
936        declared: t.switch_budget_ms,
937        level: "",
938    })
939}
940
941/// phase-462 W4 -- the mode the application asked for. A STATE, not an
942/// event: an executor opened after the request enters it at its first spin.
943static MODE_REQUEST: AtomicU32 = AtomicU32::new(0);
944
945/// Ask every executor to judge by mode `id`'s tables.
946///
947/// `id` is the baked mode id (`0` = the base contract, `1..` the contract's
948/// modes in key order; the entry names each as a constant). Like
949/// [`request_monitor_arming`] this only stores an atomic: each executor
950/// swaps its own tables at its next spin, so the switch is bounded by the
951/// slowest executor's spin period and never races a rule mid-judgement. An
952/// id an executor has no table for leaves it on the tables it has, and it
953/// says so once.
954pub fn request_mode(id: u16) {
955    MODE_REQUEST.store(u32::from(id), Ordering::Release);
956}
957
958/// The mode last asked for with [`request_mode`] (0 when never asked).
959#[must_use]
960pub fn requested_mode() -> u16 {
961    MODE_REQUEST.load(Ordering::Acquire) as u16
962}
963
964/// The current arm-request count (for an executor to remember at open).
965pub(crate) fn arm_requests() -> u32 {
966    ARM_REQUESTS.load(Ordering::Acquire)
967}
968
969/// When an executor's contract monitors start judging.
970///
971/// A verdict reached before arming is COUNTED
972/// ([`Executor::violations_suppressed_before_arm`], and the SWD record's
973/// `suppressed_before_arm`) but not stored, logged, sunk or traced: start-up
974/// -- registration, the first join, inputs that have not started yet -- looks
975/// like overruns, jitter and silence, and judging it as steady state filled
976/// the island's ring with eight start-up entries before any act ran.
977///
978/// The default is read from Kconfig / the build environment only
979/// (`NROS_MONITOR_ARM_ON_CALL`, `NROS_MONITOR_ARM_GRACE_MS`); the contract
980/// carries no key for it.
981///
982/// [`Executor::violations_suppressed_before_arm`]: super::Executor::violations_suppressed_before_arm
983#[derive(Debug, Clone, Copy, PartialEq, Eq)]
984pub struct MonitorArming {
985    /// Wait for [`request_monitor_arming`] / `Executor::arm_monitors`.
986    /// `false` (the default) arms at the first spin, today's behaviour.
987    pub on_call: bool,
988    /// Arm anyway this many ms after the first spin; 0 = no deadline. With
989    /// `on_call` it is the backstop for an application that never calls; on
990    /// its own it is a grace period for an application with no lifecycle.
991    pub grace_ms: u32,
992}
993
994impl MonitorArming {
995    /// The build's default (`NROS_MONITOR_ARM_ON_CALL`,
996    /// `NROS_MONITOR_ARM_GRACE_MS`).
997    pub const DEFAULT: Self = Self {
998        on_call: crate::config::MONITOR_ARM_ON_CALL,
999        grace_ms: crate::config::MONITOR_ARM_GRACE_MS,
1000    };
1001
1002    /// Armed from the start: no wait for a call and no grace period.
1003    pub const fn armed_at_first_spin(self) -> bool {
1004        !self.on_call && self.grace_ms == 0
1005    }
1006}
1007
1008/// Where an executor hands its violations when the image asked
1009/// it to (`Executor::set_violation_sink`).
1010///
1011/// A function and an opaque context rather than a closure, because the
1012/// executor is not generic and the reporter it reaches lives in a crate above
1013/// this one (`nros-cpp` publishes on `/diagnostics` through
1014/// `nros-diagnostics`). Called from inside the executor's spin (never from
1015/// inside a user callback) -- so the sink may publish.
1016///
1017/// Called OFF the judged dispatch, not at detection: a stored
1018/// verdict is queued ([`REPORT_QUEUE`] deep) and the queue is handed over at
1019/// the end of a spin whose next timer is further away than the last report
1020/// cost (or once a verdict has waited [`REPORT_DEFER_MAX_US`]). The sink gets
1021/// every pending verdict, oldest first, and returns how many of them it took
1022/// -- a PREFIX, so it may coalesce as many as fit one message and leave the
1023/// rest for the next slot. Returning 0 is a failure the sink has counted;
1024/// the executor then drops the oldest pending verdict so a report that can
1025/// never be sent cannot stall the queue (it stays in the ring and the record).
1026///
1027/// On one reference image the report at detection cost 15-20 ms of spin per
1028/// verdict over a 921,600-baud serial link, inside the tick being judged, and
1029/// that cost tripped `release-jitter-runtime` and `timer-overrun-runtime`:
1030/// one verdict bred more.
1031///
1032/// # Safety
1033/// The sink is called with the `ctx` it was installed with; whoever installs it
1034/// guarantees `ctx` is valid for every call until the sink is replaced or the
1035/// executor is dropped.
1036pub type ViolationSink = unsafe fn(ctx: *mut core::ffi::c_void, pending: &[Violation]) -> usize;
1037
1038/// How many stored verdicts wait for the sink. A verdict
1039/// stored while the queue is full evicts the oldest pending one, which is
1040/// counted (`ReportQueue::overflowed`); both stay in the ring and the SWD
1041/// record. Four is the `DiagnosticArray` status capacity of the generated
1042/// type, so one coalesced report never needs more.
1043pub const REPORT_QUEUE: usize = 4;
1044
1045/// The longest a pending verdict waits for a slot with slack
1046/// before it is reported anyway, in microseconds. Bounds the deferral on an
1047/// executor whose timers never leave a gap as long as the report costs.
1048pub const REPORT_DEFER_MAX_US: u64 = 1_000_000;
1049
1050/// phase-474 I7 -- verdicts stored but not yet handed to the sink, and what
1051/// the hand-over has cost. One struct so the executor size test can name it.
1052#[derive(Debug, Default)]
1053pub(crate) struct ReportQueue {
1054    /// Oldest first.
1055    pub(crate) pending: heapless::Vec<Violation, REPORT_QUEUE>,
1056    /// Monotonic us at which the oldest pending verdict was first seen by a
1057    /// flush, for [`REPORT_DEFER_MAX_US`].
1058    pub(crate) since_us: Option<u64>,
1059    /// What the last hand-over took, and the worst one, in us.
1060    pub(crate) last_cost_us: u32,
1061    pub(crate) max_cost_us: u32,
1062    /// Pending verdicts evicted by a newer one before any slot came (saturating).
1063    pub(crate) overflowed: u32,
1064    /// Verdicts the sink was handed and could not send (saturating).
1065    pub(crate) failed: u32,
1066    /// The reporter's own spin time since the last release-jitter sample: it
1067    /// is the monitor's cost, stated by `max_cost_us`, not lateness of the
1068    /// application's release, so the jitter rule does not charge it.
1069    pub(crate) debt_us: u64,
1070}
1071
1072/// phase-474 I1 -- everything an executor does with a detected violation, in
1073/// one place: the switches, the sink, the ring and its counters.
1074///
1075/// The ring keeps the LATEST [`MAX_VIOLATIONS`] verdicts: a push into a full
1076/// ring evicts the oldest and counts it in `dropped`. It used to refuse the
1077/// push instead, so a board whose start-up filled the ring stored nothing
1078/// after it (the Autoware Safety Island's W31 bring-up: 8 of 8 slots, all
1079/// start-up). `total` counts every verdict stored since boot, so
1080/// `total - dropped - ring.len()` is how many a drain has already taken.
1081pub(crate) struct ViolationChannel<'s> {
1082    /// Issue 0514 -- log each violation at detection.
1083    pub(crate) report: bool,
1084    /// phase-474 I1 -- drain the ring at the end of every spin and report each
1085    /// entry with its sequence number and the counters
1086    /// ([`Executor::set_violation_drain_report`]). Replaces the log at
1087    /// detection while on, so one verdict is one line.
1088    ///
1089    /// [`Executor::set_violation_drain_report`]: super::Executor::set_violation_drain_report
1090    pub(crate) drain_report: bool,
1091    /// Issue 1635 -- the image's reporter. The context is a `usize` so the
1092    /// executor keeps its auto traits; it is the installer's pointer.
1093    /// phase-474 I7 -- fed from `reports`, off the judged dispatch.
1094    pub(crate) sink: Option<(ViolationSink, usize)>,
1095    /// phase-474 I7 -- what waits for the sink.
1096    pub(crate) reports: ReportQueue,
1097    /// phase-409 -- CARVED, at `MAX_VIOLATIONS` (no `ExecutorSizing` knob:
1098    /// the build-time depth is the capability).
1099    pub(crate) ring: super::storage::CarvedVec<'s, Violation>,
1100    /// phase-474 I1/I2 -- the counters and the arming state.
1101    pub(crate) counts: ViolationCounts,
1102}
1103
1104/// phase-474 I1/I2 -- the scalars of a [`ViolationChannel`]: its counters and
1105/// its arming state. One struct so `the_executor_value_does_not_scale_with_the_knobs`
1106/// can name what they cost; none of them scales with a knob.
1107#[derive(Debug, Clone, Copy)]
1108pub(crate) struct ViolationCounts {
1109    /// Violations this executor stored since boot (wrapping). It is also the
1110    /// sequence number of the newest entry in `ring`: every stored verdict is
1111    /// pushed, so the ring holds `total - len + 1 ..= total`.
1112    pub(crate) total: u32,
1113    /// Issue 0514 / phase-474 I1 -- entries evicted from the full ring before
1114    /// any drain took them (saturating).
1115    pub(crate) dropped: u32,
1116    /// phase-474 I2 -- whether verdicts are stored. Until then they are only
1117    /// counted in `suppressed_before_arm`.
1118    pub(crate) armed: bool,
1119    /// phase-474 I2 -- verdicts reached before arming (saturating).
1120    pub(crate) suppressed_before_arm: u32,
1121    /// phase-474 I2 -- the arming policy ([`MonitorArming`]), kept as its two
1122    /// fields so the flags pack beside the ones above.
1123    pub(crate) arm_on_call: bool,
1124    pub(crate) arm_grace_ms: u32,
1125    /// phase-474 I2 -- whether the executor has spun, and the monotonic ms
1126    /// (wrapping `u32`) of its first spin, which the grace deadline counts
1127    /// from.
1128    pub(crate) spun: bool,
1129    pub(crate) first_spin_ms: u32,
1130    /// phase-474 I2 -- [`arm_requests`] when the executor opened; a different
1131    /// value later is the application's call.
1132    pub(crate) arm_requests_seen: u32,
1133}
1134
1135impl<'s> ViolationChannel<'s> {
1136    pub(crate) fn new(ring: super::storage::CarvedVec<'s, Violation>) -> Self {
1137        Self {
1138            report: true,
1139            drain_report: crate::config::VIOLATION_DRAIN_REPORT,
1140            sink: None,
1141            reports: ReportQueue::default(),
1142            ring,
1143            counts: ViolationCounts {
1144                total: 0,
1145                dropped: 0,
1146                armed: MonitorArming::DEFAULT.armed_at_first_spin(),
1147                suppressed_before_arm: 0,
1148                arm_on_call: MonitorArming::DEFAULT.on_call,
1149                arm_grace_ms: MonitorArming::DEFAULT.grace_ms,
1150                spun: false,
1151                first_spin_ms: 0,
1152                arm_requests_seen: arm_requests(),
1153            },
1154        }
1155    }
1156
1157    /// Issue 1635 / phase-474 I1 -- THE one place a detected violation goes:
1158    /// the log floor (issue 0514) unless the drain hook reports instead, the
1159    /// image's sink's queue when one is installed (sent later, phase-474 I7),
1160    /// the trace marker when callback
1161    /// tracing is compiled in, the SWD record when the image keeps one, and
1162    /// the ring [`drain_violations`] reads.
1163    ///
1164    /// [`drain_violations`]: super::Executor::drain_violations
1165    pub(crate) fn record(&mut self, v: Violation) {
1166        if !self.counts.armed {
1167            // phase-474 I2 -- start-up: counted, never stored.
1168            self.counts.suppressed_before_arm = self.counts.suppressed_before_arm.saturating_add(1);
1169            #[cfg(nros_boot_report)]
1170            NROS_VIOLATION_RECORD
1171                .suppressed_before_arm
1172                .fetch_add(1, Ordering::Relaxed);
1173            return;
1174        }
1175        if self.report && !self.drain_report {
1176            log_violation(&v);
1177        }
1178        if self.sink.is_some() {
1179            // phase-474 I7 -- queued, not sent: the report leaves at the end of
1180            // a spin with slack (`Executor::flush_violation_reports`), so it
1181            // never costs the dispatch being judged.
1182            if self.reports.pending.is_full() {
1183                self.reports.pending.remove(0);
1184                self.reports.overflowed = self.reports.overflowed.saturating_add(1);
1185            }
1186            let _ = self.reports.pending.push(v.clone());
1187        }
1188        // `total` is this executor's sequence number for the verdict: the log
1189        // line and the trace marker carry it, so the two name one verdict by
1190        // one number. The SWD record numbers across every executor in the
1191        // image; on a single-executor image the two coincide.
1192        self.counts.total = self.counts.total.wrapping_add(1);
1193        #[cfg(nros_boot_report)]
1194        NROS_VIOLATION_RECORD.store(&v);
1195        #[cfg(feature = "trace-callbacks")]
1196        super::callback_trace::violation(self.counts.total, &v);
1197        if self.ring.capacity() == 0 {
1198            self.counts.dropped = self.counts.dropped.saturating_add(1);
1199            return;
1200        }
1201        if self.ring.len() == self.ring.capacity() {
1202            self.ring.pop_front();
1203            self.counts.dropped = self.counts.dropped.saturating_add(1);
1204        }
1205        // Cannot fail: a slot was just made if the ring was full.
1206        let _ = self.ring.push(v);
1207    }
1208
1209    /// Hand every entry still in the ring to `f`, oldest first, with its
1210    /// sequence number, and empty the ring.
1211    pub(crate) fn drain(&mut self, mut f: impl FnMut(u32, &Violation)) {
1212        let n = self.ring.len() as u32;
1213        let first = self.counts.total.wrapping_sub(n).wrapping_add(1);
1214        for (k, v) in self.ring.iter().enumerate() {
1215            f(first.wrapping_add(k as u32), v);
1216        }
1217        self.ring.clear();
1218    }
1219
1220    /// phase-474 I1 -- the drain-and-report hook: one log line per entry with
1221    /// its sequence number and the counters, so a reader of the log knows how
1222    /// many it missed. Called at the end of a spin when `drain_report` is on.
1223    pub(crate) fn drain_and_report(&mut self) {
1224        if !self.drain_report || self.ring.is_empty() {
1225            return;
1226        }
1227        let (total, dropped) = (self.counts.total, self.counts.dropped);
1228        self.drain(|seq, v| log_drained_violation(seq, total, dropped, v));
1229    }
1230}
1231
1232/// Per-spec accounting state (parallel to the spec table).
1233#[derive(Debug, Clone, Copy, Default)]
1234pub(crate) struct MonitorState {
1235    /// Window opened (a plain bool, not a 0-sentinel on the timestamp —
1236    /// `now_us == 0` is a legitimate first sample on freshly-started
1237    /// monotonic clocks).
1238    pub(crate) opened: bool,
1239    pub(crate) window_start_us: u64,
1240    pub(crate) count_at_window_start: u32,
1241    /// Suppress duplicate reports: only re-report after a clean window.
1242    pub(crate) violated_last_window: bool,
1243    /// W3b.5 — separate dedup for the latency rule on the same spec row.
1244    pub(crate) latency_violated_last_window: bool,
1245    /// phase-474 I8 -- the open window has been moved onto the stream's
1246    /// phase (or judged as opened). See [`check_rate`].
1247    pub(crate) aligned: bool,
1248}
1249
1250/// Pure rate check over one window boundary. Returns `Some(violation)`
1251/// when the window elapsed AND the measured rate is below the declared
1252/// minimum (and we didn't already report last window).
1253///
1254/// Extracted from the executor so the math is unit-testable without a
1255/// session: publish counting is injected via the cell, time via `now_us`.
1256pub(crate) fn check_rate(
1257    spec: &MonitorSpec,
1258    state: &mut MonitorState,
1259    now_us: u64,
1260) -> Option<Violation> {
1261    if spec.min_rate_hz_milli == 0 {
1262        return None;
1263    }
1264    let count = spec.cell.count.load(Ordering::Relaxed);
1265    if !state.opened {
1266        // First observation: open the window, no verdict yet.
1267        state.opened = true;
1268        state.aligned = false;
1269        state.window_start_us = now_us;
1270        state.count_at_window_start = count;
1271        return None;
1272    }
1273    let window_us = now_us.saturating_sub(state.window_start_us);
1274    if !state.aligned && window_us < RATE_CHECK_INTERVAL_US {
1275        // phase-474 I8 -- the first window starts at the first tick that sees
1276        // a new sample, not where it was opened. The tick runs before the
1277        // spin's dispatch, so in steady state every boundary sits one tick
1278        // after a publish and the count matches the span. The window opened
1279        // at boot or by arming sits wherever that spin fell: off the
1280        // stream's phase it spans N samples over N periods plus the offset,
1281        // and a stream at exactly its declared rate read short (the island:
1282        // 9984 of 10000 mHz, once, after arming). Re-anchoring here puts the
1283        // first window on the same phase the later ones have. A stream that
1284        // stays silent is not held open: once a whole window passes with no
1285        // sample it is judged as opened (below), at 0.
1286        if count != state.count_at_window_start {
1287            state.aligned = true;
1288            state.window_start_us = now_us;
1289            state.count_at_window_start = count;
1290        }
1291        return None;
1292    }
1293    state.aligned = true;
1294    if window_us < RATE_CHECK_INTERVAL_US {
1295        return None;
1296    }
1297    let published = count.wrapping_sub(state.count_at_window_start) as u64;
1298    // milli-Hz = published * 1e3 / window_s = published * 1e9 / window_us
1299    let measured_milli_hz =
1300        (published.saturating_mul(1_000_000_000) / window_us.max(1)).min(u32::MAX as u64) as u32;
1301    // phase-474 I9 -- judge the count, not the floored quotient. The window
1302    // closes at the first tick that finds it elapsed, so `window_us` is the
1303    // declared interval plus that tick's lateness, while a stream at exactly
1304    // its declared minimum has published one sample per period: 50 over
1305    // 5.0005 s reads 9999 of 10000 mHz and was judged slow (the island, every
1306    // window, reported once thanks to `violated_last_window`). A stream at
1307    // the declared minimum delivers at least floor(min_rate * window) samples
1308    // in any window, whatever its phase; fewer than that is slow.
1309    let required = (spec.min_rate_hz_milli as u64).saturating_mul(window_us) / 1_000_000_000;
1310
1311    // Roll the window.
1312    state.window_start_us = now_us;
1313    state.count_at_window_start = count;
1314
1315    if published < required {
1316        if state.violated_last_window {
1317            return None; // still violated — already reported
1318        }
1319        state.violated_last_window = true;
1320        Some(Violation {
1321            rule: "rate-hierarchy-runtime",
1322            fqn: spec.fqn,
1323            measured: measured_milli_hz,
1324            declared: spec.min_rate_hz_milli,
1325            level: "",
1326        })
1327    } else {
1328        state.violated_last_window = false;
1329        None
1330    }
1331}
1332
1333/// Pure latency check: drains the spec cell's window-max take→publish
1334/// latency and fires when it exceeds the declared node-path budget.
1335/// Same report-once-until-recovery semantics as the rate rule; runs on
1336/// every monitor tick (the cell accumulates between ticks, so no window
1337/// bookkeeping is needed — draining IS the window roll).
1338pub(crate) fn check_latency(spec: &MonitorSpec, state: &mut MonitorState) -> Option<Violation> {
1339    if spec.max_latency_ms == 0 {
1340        return None;
1341    }
1342    let max_us = spec.cell.max_latency_us.swap(0, Ordering::Relaxed);
1343    let max_ms = max_us / 1_000;
1344    if max_ms > spec.max_latency_ms {
1345        if state.latency_violated_last_window {
1346            return None;
1347        }
1348        state.latency_violated_last_window = true;
1349        Some(Violation {
1350            rule: "max-latency-runtime",
1351            fqn: spec.fqn,
1352            measured: max_ms,
1353            declared: spec.max_latency_ms,
1354            level: "",
1355        })
1356    } else {
1357        // A quiet window (no dispatch attributed) also counts as clean —
1358        // recovery resets the dedup like the rate rule's clean window.
1359        state.latency_violated_last_window = false;
1360        None
1361    }
1362}
1363
1364/// phase10-B3 -- bind a subscription slot as the route trigger of every row
1365/// whose [`MonitorSpec::route_trigger`] is `topic`. Called once per
1366/// registration; the first subscription on the topic keeps the binding.
1367pub(crate) fn route_bind(table: &[MonitorSpec], topic: &str, slot: usize) {
1368    if slot >= ROUTE_SLOT_MASK as usize {
1369        return;
1370    }
1371    for spec in table.iter().take(MAX_MONITORS) {
1372        if spec.route_max_latency_ms == 0 || spec.route_trigger != topic {
1373            continue;
1374        }
1375        let w = spec.cell.route.load(Ordering::Relaxed);
1376        if w & ROUTE_SLOT_MASK == 0 {
1377            spec.cell.route.store(
1378                (w & !ROUTE_SLOT_MASK) | (slot as u32 + 1),
1379                Ordering::Relaxed,
1380            );
1381        }
1382    }
1383}
1384
1385/// phase10-B3 -- forget a released slot's route bindings and any take it left
1386/// waiting.
1387pub(crate) fn route_unbind(table: &[MonitorSpec], slot: usize) {
1388    for spec in table.iter().take(MAX_MONITORS) {
1389        let w = spec.cell.route.load(Ordering::Relaxed);
1390        if w & ROUTE_SLOT_MASK == slot as u32 + 1 {
1391            spec.cell.route.store(0, Ordering::Relaxed);
1392        }
1393    }
1394}
1395
1396/// phase10-B3 -- the dispatch in `slot` took a sample at `take_us`: every
1397/// route whose trigger is that slot starts its clock, unless an earlier take
1398/// is still waiting for the output (the route is judged from the EARLIEST
1399/// unanswered take: a take that arrives just after a tick waits for the whole
1400/// next period, and that is the wait the budget has to hold).
1401pub(crate) fn route_take(table: &[MonitorSpec], slot: usize, take_us: u64) {
1402    let bound = slot as u32 + 1;
1403    for spec in table.iter().take(MAX_MONITORS) {
1404        let w = spec.cell.route.load(Ordering::Relaxed);
1405        if w & ROUTE_SLOT_MASK != bound || w & ROUTE_PENDING != 0 {
1406            continue;
1407        }
1408        spec.cell
1409            .route_take_us
1410            .store(take_us as u32, Ordering::Relaxed);
1411        // Release: a `RouteWatch` on another thread that sees the route
1412        // pending sees this take with it.
1413        spec.cell.route.store(w | ROUTE_PENDING, Ordering::Release);
1414    }
1415}
1416
1417/// phase10-B3 -- a dispatch ended at `end_us`. Every route output whose
1418/// counter advanced during it (`counts_before`, as the latency rule reads it)
1419/// and that has a take waiting is judged: take to dispatch end, an upper bound
1420/// on take to that publish, against the path's budget. Over budget is
1421/// reported once until a route is within it again.
1422///
1423/// phase-503 -- a SUPERVISED route ([`MonitorSpec::route_deadline_ms`])
1424/// answered at or after its deadline is also overdue: it is reported as
1425/// `route-deadline-runtime` and its reaction requested, as `route_overdue`
1426/// would have done had it run in time. Under `MECHANISM_EXECUTOR` this is the
1427/// only detection a single long callback gets: the callback that holds the
1428/// spin thread past the deadline publishes the output before the executor's
1429/// overdue check can run, so the miss is caught here, at completion -- late
1430/// by the callback's overrun. A route whose deadline was already caught
1431/// (`route_overdue` dropped its take) is not pending any more and is not
1432/// judged again, so each take gets at most one deadline verdict.
1433///
1434/// `report(row, violation, record, react)`: `record` is `false` while the
1435/// route is still marked violated from an earlier verdict (report once until
1436/// a route is within its budget again); `react` asks the caller to call the
1437/// reaction hook, on every late supervised take as `route_overdue` does.
1438pub(crate) fn route_judge(
1439    table: &[MonitorSpec],
1440    counts_before: &[u32; MAX_MONITORS],
1441    end_us: u64,
1442    mut report: impl FnMut(usize, Violation, bool, bool),
1443) {
1444    for (k, spec) in table.iter().take(MAX_MONITORS).enumerate() {
1445        if spec.route_max_latency_ms == 0 {
1446            continue;
1447        }
1448        let w = spec.cell.route.load(Ordering::Relaxed);
1449        if w & ROUTE_PENDING == 0 || spec.cell.count.load(Ordering::Relaxed) == counts_before[k] {
1450            continue;
1451        }
1452        let took_us = (end_us as u32).wrapping_sub(spec.cell.route_take_us.load(Ordering::Relaxed));
1453        let measured_ms = took_us / 1_000;
1454        let first = w & ROUTE_VIOLATED == 0;
1455        let late = measured_ms > spec.route_max_latency_ms;
1456        let overdue =
1457            route_supervised(spec) && took_us >= spec.route_deadline_ms.saturating_mul(1_000);
1458        let mut next = w & !ROUTE_PENDING;
1459        if late && first {
1460            report(
1461                k,
1462                Violation {
1463                    rule: "route-latency-runtime",
1464                    fqn: spec.fqn,
1465                    measured: measured_ms,
1466                    declared: spec.route_max_latency_ms,
1467                    level: "",
1468                },
1469                true,
1470                false,
1471            );
1472        }
1473        if overdue {
1474            report(
1475                k,
1476                Violation {
1477                    rule: "route-deadline-runtime",
1478                    fqn: spec.fqn,
1479                    measured: measured_ms,
1480                    declared: spec.route_deadline_ms,
1481                    level: "",
1482                },
1483                first,
1484                true,
1485            );
1486        }
1487        if late || overdue {
1488            next |= ROUTE_VIOLATED;
1489        } else {
1490            next &= !ROUTE_VIOLATED;
1491        }
1492        spec.cell.route.store(next, Ordering::Relaxed);
1493    }
1494}
1495
1496/// phase-503 -- whether a pending route of `spec` has a supervised deadline.
1497#[inline]
1498fn route_supervised(spec: &MonitorSpec) -> bool {
1499    spec.route_deadline_ms > 0 && spec.route_max_latency_ms > 0
1500}
1501
1502/// Time from now to the earliest deadline of a pending supervised
1503/// route, in microseconds (0 when one is already due), or `None` when no
1504/// supervised route is waiting. This is the executor's wake source for the
1505/// rule, and what a port's independent timer (`MECHANISM_TIMER`) arms on.
1506///
1507/// The due time is `take + route_deadline_ms`, derived from the stored take
1508/// rather than kept in a second cell: both are the clock's low 32 bits, so the
1509/// difference is exact across a wrap as long as a route waits less than ~71
1510/// minutes, and a supervised one is reported long before that.
1511pub fn route_next_due_us(table: &[MonitorSpec], now_us: u64) -> Option<u64> {
1512    route_next_due(table, || now_us)
1513}
1514
1515/// [`route_next_due_us`] with the clock read AFTER each pending row's take is
1516/// loaded, so a take stored by another thread between the two reads can never
1517/// look older than now (which would read as a due already passed).
1518fn route_next_due(table: &[MonitorSpec], now_us: impl Fn() -> u64) -> Option<u64> {
1519    let mut best: Option<u64> = None;
1520    for spec in table.iter().take(MAX_MONITORS) {
1521        if !route_supervised(spec) {
1522            continue;
1523        }
1524        let w = spec.cell.route.load(Ordering::Acquire);
1525        if w & ROUTE_PENDING == 0 {
1526            continue;
1527        }
1528        let take_us = spec.cell.route_take_us.load(Ordering::Relaxed);
1529        let waited_us = (now_us() as u32).wrapping_sub(take_us);
1530        let deadline_us = spec.route_deadline_ms.saturating_mul(1_000);
1531        let left = deadline_us.saturating_sub(waited_us) as u64;
1532        best = Some(best.map_or(left, |b| b.min(left)));
1533        if left == 0 {
1534            break;
1535        }
1536    }
1537    best
1538}
1539
1540/// An executor's supervised routes, read from OUTSIDE it: from
1541/// a port's timer expiry, a reaction thread or an interrupt, while the spin
1542/// thread is anywhere, including inside a dispatch.
1543///
1544/// A route is answered when the dispatch that publishes its output ends:
1545/// `route_judge` clears [`ROUTE_PENDING`] right there, on the executor's
1546/// clock, in the row's atomic cell. Until this type, a port's independent timer
1547/// (`MECHANISM_TIMER`) learned that only from `Executor::route_next_due_us`
1548/// after the spin that answered it RETURNED, so a callback that answered
1549/// before the due inside a spin that ran past it looked like a miss at the
1550/// timer's expiry (a false safe state on a board). [`Self::next_due_us`] reads
1551/// the cells at the moment of the call instead: `Some(0)` only when a take is
1552/// still unanswered at or after its deadline -- the executor's own verdict
1553/// (`route_overdue`, `route_judge`: an answer exactly at the deadline is a
1554/// miss).
1555///
1556/// It never touches the executor: the table and the clock it holds are fixed
1557/// once the monitors are installed (take it after `set_monitor_table` and any
1558/// clock change). Reading takes no lock and allocates nothing.
1559#[derive(Debug, Clone, Copy)]
1560pub struct RouteWatch {
1561    table: &'static [MonitorSpec],
1562    clock_us: fn() -> u64,
1563}
1564
1565impl RouteWatch {
1566    /// A watch over `table` on `clock_us` (microseconds, the clock the
1567    /// executor stamps takes with).
1568    pub const fn new(table: &'static [MonitorSpec], clock_us: fn() -> u64) -> Self {
1569        Self { table, clock_us }
1570    }
1571
1572    /// The watched table.
1573    pub const fn table(&self) -> &'static [MonitorSpec] {
1574        self.table
1575    }
1576
1577    /// The clock the watch reads.
1578    pub const fn clock_us(&self) -> fn() -> u64 {
1579        self.clock_us
1580    }
1581
1582    /// Microseconds from now to the earliest deadline of a pending supervised
1583    /// route; `Some(0)` when one has passed with no answer; `None` when none
1584    /// is waiting (every take answered, or none taken).
1585    pub fn next_due_us(&self) -> Option<u64> {
1586        route_next_due(self.table, self.clock_us)
1587    }
1588}
1589
1590/// phase-503 -- judge every pending supervised route at `now_us`: a take still
1591/// unanswered at or after `take + route_deadline_ms` is OVERDUE. Its waiting
1592/// take is dropped (the route stops pending, so the next take starts a new
1593/// one) and the route is marked [`ROUTE_VIOLATED`], as `route_judge` marks an
1594/// over-budget route.
1595///
1596/// `react(row, violation, first)` is called for every overdue route: `first`
1597/// is `false` while the route is still marked violated from an earlier verdict
1598/// (report once until a route is within its budget again, the latency rule's
1599/// rule), and the caller records the violation only when it is `true`. The
1600/// reaction is requested every time, since each overdue take is a missed
1601/// deadline the fallback has to cover.
1602pub(crate) fn route_overdue(
1603    table: &[MonitorSpec],
1604    now_us: u64,
1605    mut react: impl FnMut(usize, Violation, bool),
1606) {
1607    for (k, spec) in table.iter().take(MAX_MONITORS).enumerate() {
1608        if !route_supervised(spec) {
1609            continue;
1610        }
1611        let w = spec.cell.route.load(Ordering::Relaxed);
1612        if w & ROUTE_PENDING == 0 {
1613            continue;
1614        }
1615        let waited_us =
1616            (now_us as u32).wrapping_sub(spec.cell.route_take_us.load(Ordering::Relaxed));
1617        if waited_us < spec.route_deadline_ms.saturating_mul(1_000) {
1618            continue;
1619        }
1620        spec.cell
1621            .route
1622            .store((w & !ROUTE_PENDING) | ROUTE_VIOLATED, Ordering::Relaxed);
1623        react(
1624            k,
1625            Violation {
1626                rule: "route-deadline-runtime",
1627                fqn: spec.fqn,
1628                measured: waited_us / 1_000,
1629                declared: spec.route_deadline_ms,
1630                level: "",
1631            },
1632            w & ROUTE_VIOLATED == 0,
1633        );
1634    }
1635}
1636
1637/// phase-503 -- whether any row carries a supervised route deadline.
1638pub(crate) fn route_deadline_active(table: &[MonitorSpec]) -> bool {
1639    table.iter().any(route_supervised)
1640}
1641
1642/// phase10-B3 -- whether any row carries a route contract.
1643pub(crate) fn route_active(table: &[MonitorSpec]) -> bool {
1644    table.iter().any(|m| m.route_max_latency_ms > 0)
1645}
1646
1647/// phase10-B3 -- drop every waiting take and the report-once state (arming:
1648/// a take from start-up is not a route of RUN's).
1649pub(crate) fn route_reset(table: &[MonitorSpec]) {
1650    for spec in table.iter() {
1651        let w = spec.cell.route.load(Ordering::Relaxed);
1652        spec.cell
1653            .route
1654            .store(w & ROUTE_SLOT_MASK, Ordering::Relaxed);
1655    }
1656}
1657
1658/// Per-age-spec dedup state.
1659#[derive(Debug, Clone, Copy, Default)]
1660pub(crate) struct AgeState {
1661    pub(crate) violated_last_window: bool,
1662    /// phase-462 W2 -- the silence rule's window. `opened` is a plain bool for
1663    /// the same reason [`MonitorState`]'s is: `now_us == 0` is a legitimate
1664    /// first sample.
1665    pub(crate) silence_opened: bool,
1666    /// Report-once-until-recovery, matching every other rule here.
1667    pub(crate) silence_reported: bool,
1668    /// Monotonic MILLISECONDS of the last check that saw a take (or of the
1669    /// first check, which starts the lease rather than judging it).
1670    ///
1671    /// Milliseconds and `u32`, not the uss the clock hands out, because this
1672    /// array is INLINE in the `Executor` value (`[AgeState; MAX_AGE_MONITORS]`) and
1673    /// that value has a byte budget a knob-scaled table must not blow (issue
1674    /// 0961 / `storage.rs`'s `the_executor_value_does_not_scale_with_the_knobs`
1675    /// -- a `u64` here costs 8 rows x 16 B and fails it). The unit is the
1676    /// contract's own (`max_age_ms`), the comparison is a wrapping delta, so
1677    /// the 49-day rollover is not a discontinuity, and a silence window is
1678    /// never shorter than a millisecond.
1679    pub(crate) last_take_ms: u32,
1680}
1681
1682/// phase-462 W2 -- the on-target liveliness lease: a contracted subscription
1683/// that has taken NOTHING for a whole `max_age_ms` window.
1684///
1685/// The bound needs no new declaration and deliberately does not invent one.
1686/// `max_age_ms` already says how old this input's data may be; data that never
1687/// arrives is older than that by the same clock, so the window IS the declared
1688/// bound. (`on_violation` selects what the executor then DOES about it; the
1689/// reaction beyond reporting is the fault hook phase-462 W3 owns.)
1690///
1691/// Why this is not `max-age-runtime` with a longer arm: that rule judges a
1692/// message that arrived. An input that stops entirely produces no message to
1693/// judge, so it leaves the age rule silent forever -- the exact failure a
1694/// `max_age_ms` promise is made against, and the one play_launch's reaction
1695/// engine catches on the Linux side of the same contract.
1696///
1697/// `now_us` is the executor's monotonic clock, `None` on a build with no clock
1698/// at all. Then nothing is judged: a clock that never moves is a window that
1699/// never elapses, and guessing a window from spin counts would put a tolerance
1700/// nobody declared into a safety rule.
1701///
1702/// phase-462 W5b -- `window_ms` is [`silence_window`]'s: the age bound, or the
1703/// contract's `deadline` when the row is armed for one and it is shorter.
1704fn check_silence(window_ms: u32, state: &mut AgeState, took: u32, now_us: u64) -> bool {
1705    let now_ms = (now_us / 1_000) as u32;
1706    if !state.silence_opened {
1707        state.silence_opened = true;
1708        state.last_take_ms = now_ms;
1709        return false;
1710    }
1711    if took > 0 {
1712        state.last_take_ms = now_ms;
1713        state.silence_reported = false;
1714        return false;
1715    }
1716    if now_ms.wrapping_sub(state.last_take_ms) < window_ms {
1717        return false;
1718    }
1719    if state.silence_reported {
1720        return false; // still silent -- already reported
1721    }
1722    state.silence_reported = true;
1723    true
1724}
1725
1726/// Pure age check: drains the sub cell's window-max take-age and fires
1727/// when it exceeds the declared bound. Report-once-until-recovery.
1728///
1729/// phase-462 W2 -- also the silence rule's tick, because the two verdicts read
1730/// ONE observation (what this endpoint took since the last check) and reading
1731/// it twice would let one rule's drain hide the other's evidence. They cannot
1732/// both fire: with no takes the drained age is 0, so `max-age-runtime` has
1733/// nothing to judge.
1734/// phase-462 W5b -- the silence rule's window and its evidence for one row:
1735/// `(window_ms, evidence)`, or `None` when the row judges no silence at all.
1736///
1737/// An age contract keeps W2's evidence (stamped takes, so an endpoint whose
1738/// type carries no stamp still reads as unjudgeable) and an armed deadline
1739/// shortens the window when it is the tighter bound. A row armed for a
1740/// deadline ALONE counts arrivals, since a deadline promises arrival and
1741/// nothing about stamps. Both counters are drained either way, so neither
1742/// carries a stale window into the next check.
1743fn silence_window(spec: &AgeMonitorSpec) -> Option<(u32, u32)> {
1744    let took = spec.cell.takes.swap(0, Ordering::Relaxed);
1745    let arrived = spec.cell.arrivals.swap(0, Ordering::Relaxed);
1746    let armed = spec.deadline_ms > 0 && spec.cell.deadline_slot.load(Ordering::Relaxed) != 0;
1747    match (spec.max_age_ms, armed) {
1748        (0, false) => None,
1749        (0, true) => Some((spec.deadline_ms, arrived)),
1750        (age, false) => Some((age, took)),
1751        (age, true) => Some((age.min(spec.deadline_ms), took)),
1752    }
1753}
1754
1755pub(crate) fn check_age(
1756    spec: &AgeMonitorSpec,
1757    state: &mut AgeState,
1758    now_us: Option<u64>,
1759) -> Option<Violation> {
1760    let (window_ms, took) = silence_window(spec)?;
1761    if let Some(now_us) = now_us
1762        && check_silence(window_ms, state, took, now_us)
1763    {
1764        return Some(Violation {
1765            rule: "silence-runtime",
1766            fqn: spec.fqn,
1767            // Takes in the window, against the window the contract declares.
1768            measured: 0,
1769            declared: window_ms,
1770            level: "",
1771        });
1772    }
1773    if spec.max_age_ms == 0 {
1774        return None;
1775    }
1776    let max_ms = spec.cell.max_age_ms.swap(0, Ordering::Relaxed);
1777    if max_ms > spec.max_age_ms {
1778        if state.violated_last_window {
1779            return None;
1780        }
1781        state.violated_last_window = true;
1782        Some(Violation {
1783            rule: "max-age-runtime",
1784            fqn: spec.fqn,
1785            measured: max_ms,
1786            declared: spec.max_age_ms,
1787            level: "",
1788        })
1789    } else {
1790        state.violated_last_window = false;
1791        None
1792    }
1793}
1794
1795// ---------------------------------------------------------------------------
1796// phase-462 W3b -- the hazard observer.
1797// ---------------------------------------------------------------------------
1798
1799/// One guard member: which monitor row's verdict says this topic has faulted.
1800///
1801/// The observer adds no detector of its own. A guard topic has faulted when
1802/// the row the image already bakes for it says so: an age row whose
1803/// `silence-runtime` lease is reported, or a rate row whose last window was
1804/// short (`min-rate-runtime`). Reading the rows' state rather than their
1805/// violations keeps the two in step by construction -- a hazard cannot be
1806/// detected by a rule that did not fire, nor stay detected after it recovered.
1807#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1808pub enum HazardMonitorRef {
1809    /// Row index into the executor's age table.
1810    Age(u16),
1811    /// Row index into the executor's rate/latency table.
1812    Rate(u16),
1813}
1814
1815/// One fault a hazard covers: a topic, or a redundant set of topics.
1816#[derive(Debug, Clone, Copy)]
1817pub struct HazardMonitorSpec {
1818    /// `true`: the guard faults only when EVERY member has (a redundant
1819    /// set). `false`: when any member has.
1820    pub all_of: bool,
1821    /// The guard's members.
1822    pub members: &'static [HazardMonitorRef],
1823}
1824
1825/// [`HazardSpec::sink`] when the hazard's reaction states no `safe_state`
1826/// publisher this image monitors: the observer reports detection and
1827/// recovery, and no reaction.
1828pub const NO_SINK: u16 = u16::MAX;
1829
1830/// One hazard's observer state. Baked as a `static` beside the spec, the way
1831/// [`PubMonitorCell`] is, so the observer adds a slice to the `Executor`
1832/// value and nothing per hazard.
1833#[derive(Debug, Default)]
1834pub struct HazardCell {
1835    /// 0 clear, 1 detected, 2 detected and reacted.
1836    state: AtomicU32,
1837    /// Monotonic ms the fault began: the faulting age row's last take, or the
1838    /// tick that first saw a rate guard short.
1839    fault_ms: AtomicU32,
1840    /// The sink publisher's count when the fault was detected.
1841    sink_count: AtomicU32,
1842    /// Index into [`HazardSpec::rungs`] of the rung being judged.
1843    rung_active: AtomicU32,
1844    /// Monotonic ms the active rung became active: the detection tick (the
1845    /// fire), or the tick that saw the ladder fall to it.
1846    rung_armed_ms: AtomicU32,
1847    /// Monotonic ms the active rung's route clock started: its `starts_at`
1848    /// node's detection when this executor observes that node, else
1849    /// [`Self::rung_armed_ms`].
1850    rung_clock_ms: AtomicU32,
1851    /// The active rung's output publisher count when its clock started.
1852    rung_count: AtomicU32,
1853    /// [`RUNG_IDLE`], [`RUNG_ARMED`], [`RUNG_WATCHING`] or [`RUNG_JUDGED`].
1854    rung_state: AtomicU32,
1855}
1856
1857impl HazardCell {
1858    /// A cleared cell, for a `static`.
1859    pub const fn new() -> Self {
1860        Self {
1861            state: AtomicU32::new(0),
1862            fault_ms: AtomicU32::new(0),
1863            sink_count: AtomicU32::new(0),
1864            rung_active: AtomicU32::new(0),
1865            rung_armed_ms: AtomicU32::new(0),
1866            rung_clock_ms: AtomicU32::new(0),
1867            rung_count: AtomicU32::new(0),
1868            rung_state: AtomicU32::new(RUNG_IDLE),
1869        }
1870    }
1871}
1872
1873/// No rung route being watched.
1874const RUNG_IDLE: u32 = 0;
1875/// A rung is active; its route clock waits for its `starts_at` detection.
1876const RUNG_ARMED: u32 = 1;
1877/// The route clock runs; waiting for the rung's first output.
1878const RUNG_WATCHING: u32 = 2;
1879/// The active rung was judged (answered, or reported overdue).
1880const RUNG_JUDGED: u32 = 3;
1881
1882/// [`RungSpec::mode`] for a rung that is not a contract mode (a reaction that
1883/// is a single path has one rung, named after the path).
1884pub const NO_MODE: u16 = u16::MAX;
1885
1886/// [`RungSpec::role`] values, in rlm's `LevelRole` order (~~`RungRole`~~ before rlm v0.3.3).
1887pub const RUNG_ROLE_RUNG: u8 = 0;
1888/// A `window:` rung: lasts at least its window; the rung below takes over
1889/// when the window passes.
1890pub const RUNG_ROLE_WINDOW: u8 = 1;
1891/// The ladder's last rung.
1892pub const RUNG_ROLE_FLOOR: u8 = 2;
1893
1894/// One rung of a hazard's ladder
1895/// (`contracts.hazards.<h>.rungs[]`, top first), lowered by the bake.
1896#[derive(Debug, Clone, Copy)]
1897pub struct RungSpec {
1898    /// The baked mode id the rung IS (the id `request_mode` takes), or
1899    /// [`NO_MODE`]. While the executor is in this mode, the ladder has fallen
1900    /// to this rung.
1901    pub mode: u16,
1902    /// Rate-table row of a publisher on one of the rung's `output` topics, or
1903    /// [`NO_SINK`] when this executor does not observe one.
1904    pub output_row: u16,
1905    /// The rung's ROUTE as play_launch's checker charged it (`route_ms`,
1906    /// rounded up): from its `starts_at` node's detection to the rung's first
1907    /// output, excluding the detection time, any window and the settle. 0 = no
1908    /// route, so the rung is tracked but not judged.
1909    pub route_ms: u32,
1910    /// [`RUNG_ROLE_RUNG`], [`RUNG_ROLE_WINDOW`] or [`RUNG_ROLE_FLOOR`].
1911    pub role: u8,
1912    /// The level's name as the model spells it (the mode key,
1913    /// `degradation_levels[].level`): what `hazard-level-runtime` reports in
1914    /// [`Violation::level`] when the ladder is on this rung.
1915    pub level: &'static str,
1916    /// The hazard's guard members that belong to the rung's `starts_at` node:
1917    /// the route clock starts when one of them reports faulted. Empty when
1918    /// this executor does not observe that node as a detector (a rung below a
1919    /// window starts at the window owner, which is not a guard), and then the
1920    /// clock starts when the rung becomes active.
1921    pub starts_at: &'static [HazardMonitorRef],
1922}
1923
1924/// One contracted hazard (`contracts.hazards`), lowered by the bake.
1925#[derive(Debug, Clone, Copy)]
1926pub struct HazardSpec {
1927    /// The hazard's contract key (`<scope>/<name>`), the report key.
1928    pub key: &'static str,
1929    /// Declared `ftti_ms`; 0 = none declared.
1930    pub ftti_ms: u32,
1931    /// The reacting path's `safe_state.settle_ms`, added to the reaction
1932    /// time as play_launch adds it; 0 = none.
1933    pub settle_ms: u32,
1934    /// The faults the hazard covers; any one of them is the hazard.
1935    pub monitors: &'static [HazardMonitorSpec],
1936    /// Rate-table row of the `safe_state.emits` publisher, or [`NO_SINK`].
1937    pub sink: u16,
1938    /// The id the reaction hook receives when this hazard is
1939    /// DETECTED (the reacting path's, in the model's one reaction id space
1940    /// shared with supervised routes); 0 = no safe-state entry to start.
1941    pub reaction_id: u16,
1942    /// The hazard's ladder, top
1943    /// rung first. Empty: no rung route is monitored.
1944    pub rungs: &'static [RungSpec],
1945    /// The observer's state.
1946    pub cell: &'static HazardCell,
1947}
1948
1949const HAZARD_CLEAR: u32 = 0;
1950const HAZARD_DETECTED: u32 = 1;
1951const HAZARD_REACTED: u32 = 2;
1952
1953/// Whether `member` has faulted, and since when (ms) when the row knows.
1954fn member_fault(
1955    member: HazardMonitorRef,
1956    monitor_states: &[MonitorState],
1957    age_states: &[AgeState],
1958) -> Option<Option<u32>> {
1959    match member {
1960        HazardMonitorRef::Age(i) => {
1961            let s = age_states.get(i as usize)?;
1962            s.silence_reported.then_some(Some(s.last_take_ms))
1963        }
1964        HazardMonitorRef::Rate(i) => {
1965            let s = monitor_states.get(i as usize)?;
1966            s.violated_last_window.then_some(None)
1967        }
1968    }
1969}
1970
1971/// Whether any guard of `spec` has faulted, and the earliest fault start the
1972/// faulting rows know.
1973fn hazard_fault(
1974    spec: &HazardSpec,
1975    monitor_states: &[MonitorState],
1976    age_states: &[AgeState],
1977) -> Option<Option<u32>> {
1978    let mut faulted = false;
1979    let mut since: Option<u32> = None;
1980    for g in spec.monitors {
1981        let mut seen = 0usize;
1982        let mut g_since: Option<u32> = None;
1983        for m in g.members {
1984            if let Some(at) = member_fault(*m, monitor_states, age_states) {
1985                seen += 1;
1986                if let Some(at) = at {
1987                    g_since = Some(g_since.map_or(at, |s: u32| s.min(at)));
1988                }
1989            }
1990        }
1991        let guard_faulted = if g.all_of {
1992            !g.members.is_empty() && seen == g.members.len()
1993        } else {
1994            seen > 0
1995        };
1996        if guard_faulted {
1997            faulted = true;
1998            if let Some(at) = g_since {
1999                since = Some(since.map_or(at, |s| s.min(at)));
2000            }
2001        }
2002    }
2003    faulted.then_some(since)
2004}
2005
2006/// phase-462 W3b -- one tick of a hazard's observer, after the monitor rows
2007/// have run. Emits, in play_launch's vocabulary so one log reader serves both
2008/// sides of a bridge:
2009///
2010/// - `hazard-detected` when a guard first faults: measured is the ms since
2011///   the fault began, declared the FTTI;
2012/// - `hazard-reaction` when the `safe_state` publisher publishes after that:
2013///   measured is fault-to-reaction plus `settle_ms`, declared the FTTI;
2014/// - `hazard-recovered` when no guard is faulted any more: measured is the
2015///   ms the hazard lasted;
2016/// - `hazard-route-runtime` (play_launch phase 96 W4.2) when the ACTIVE
2017///   rung's ROUTE overran: measured is the ms from the rung's route clock
2018///   start to the first publish on its output, or, when none came, to the
2019///   tick that saw the route pass; declared is the rung's `route_ms`. A rung
2020///   that answers within its route reports nothing. Each rung that becomes
2021///   active is judged at most once;
2022/// - `hazard-level-runtime` (phase-560 W8, play_launch phase 102 M5 E7)
2023///   whenever a rung becomes active: at detection, right after
2024///   `hazard-detected`, and on every fall. measured is the level's 0-based
2025///   index in the ladder, declared the ladder's length, and
2026///   [`Violation::level`] the level's name -- the report play_launch's
2027///   observer makes as `mode-availability`, keyed here by the hazard. A
2028///   ladder that stays on one level reports it once.
2029///
2030/// Which rung is active comes from `mode`, the mode the executor judges by:
2031/// at detection it is the rung whose mode the executor is already in (the
2032/// ladder fell before this fault), else the top rung; while the hazard holds,
2033/// the executor entering a LOWER rung's mode is a fall, and that rung becomes
2034/// active. A rung's clock starts at its `starts_at` node's detection when this
2035/// executor observes that node among the guard's detectors, else when the
2036/// rung becomes active.
2037///
2038/// `fqn` is the hazard's key on all of them.
2039pub(crate) fn check_hazard(
2040    spec: &HazardSpec,
2041    monitor_table: &[MonitorSpec],
2042    monitor_states: &[MonitorState],
2043    age_states: &[AgeState],
2044    mode: u16,
2045    now_ms: u32,
2046    mut emit: impl FnMut(Violation),
2047) {
2048    let cell = spec.cell;
2049    let state = cell.state.load(Ordering::Relaxed);
2050    let sink_count = monitor_table
2051        .get(spec.sink as usize)
2052        .map(|m| m.cell.count.load(Ordering::Relaxed));
2053    let fault = hazard_fault(spec, monitor_states, age_states);
2054    let v = |rule, measured: u32| Violation {
2055        rule,
2056        fqn: spec.key,
2057        measured,
2058        declared: spec.ftti_ms,
2059        level: "",
2060    };
2061    match (state, fault) {
2062        (HAZARD_CLEAR, Some(since)) => {
2063            let at = since.unwrap_or(now_ms);
2064            cell.fault_ms.store(at, Ordering::Relaxed);
2065            cell.sink_count
2066                .store(sink_count.unwrap_or(0), Ordering::Relaxed);
2067            cell.state.store(HAZARD_DETECTED, Ordering::Relaxed);
2068            let active = spec
2069                .rungs
2070                .iter()
2071                .position(|r| r.mode != NO_MODE && r.mode == mode)
2072                .unwrap_or(0);
2073            emit(v("hazard-detected", now_ms.wrapping_sub(at)));
2074            arm_rung(spec, active, now_ms, &mut emit);
2075        }
2076        (HAZARD_DETECTED, Some(_)) => {
2077            if let Some(count) = sink_count
2078                && count != cell.sink_count.load(Ordering::Relaxed)
2079            {
2080                cell.state.store(HAZARD_REACTED, Ordering::Relaxed);
2081                let since = now_ms.wrapping_sub(cell.fault_ms.load(Ordering::Relaxed));
2082                emit(v("hazard-reaction", since.saturating_add(spec.settle_ms)));
2083            }
2084        }
2085        (HAZARD_DETECTED | HAZARD_REACTED, None) => {
2086            cell.state.store(HAZARD_CLEAR, Ordering::Relaxed);
2087            cell.rung_state.store(RUNG_IDLE, Ordering::Relaxed);
2088            let lasted = now_ms.wrapping_sub(cell.fault_ms.load(Ordering::Relaxed));
2089            emit(v("hazard-recovered", lasted));
2090        }
2091        _ => {}
2092    }
2093    if fault.is_some() {
2094        check_rung(
2095            spec,
2096            monitor_table,
2097            monitor_states,
2098            age_states,
2099            mode,
2100            now_ms,
2101            &mut emit,
2102        );
2103    }
2104}
2105
2106/// Make rung `active` the one being judged, from `now_ms`, and report the
2107/// level the ladder is now on (`hazard-level-runtime`).
2108fn arm_rung(spec: &HazardSpec, active: usize, now_ms: u32, emit: &mut impl FnMut(Violation)) {
2109    let cell = spec.cell;
2110    let Some(rung) = spec.rungs.get(active) else {
2111        cell.rung_state.store(RUNG_IDLE, Ordering::Relaxed);
2112        return;
2113    };
2114    cell.rung_active.store(active as u32, Ordering::Relaxed);
2115    cell.rung_armed_ms.store(now_ms, Ordering::Relaxed);
2116    cell.rung_state.store(RUNG_ARMED, Ordering::Relaxed);
2117    emit(Violation {
2118        rule: "hazard-level-runtime",
2119        fqn: spec.key,
2120        measured: active as u32,
2121        declared: spec.rungs.len() as u32,
2122        level: rung.level,
2123    });
2124}
2125
2126/// play_launch phase 96 W4.2 -- while the hazard holds: follow a fall to a
2127/// lower rung, start the active rung's route clock at its `starts_at`
2128/// detection, and judge the rung once, at its first output or when its route
2129/// passes with none.
2130fn check_rung(
2131    spec: &HazardSpec,
2132    monitor_table: &[MonitorSpec],
2133    monitor_states: &[MonitorState],
2134    age_states: &[AgeState],
2135    mode: u16,
2136    now_ms: u32,
2137    emit: &mut impl FnMut(Violation),
2138) {
2139    let cell = spec.cell;
2140    if cell.rung_state.load(Ordering::Relaxed) == RUNG_IDLE {
2141        return;
2142    }
2143    // A fall: the executor entered the mode of a rung below the active one.
2144    let active = cell.rung_active.load(Ordering::Relaxed) as usize;
2145    if let Some(lower) = spec
2146        .rungs
2147        .iter()
2148        .enumerate()
2149        .skip(active + 1)
2150        .find(|(_, r)| r.mode != NO_MODE && r.mode == mode)
2151        .map(|(i, _)| i)
2152    {
2153        arm_rung(spec, lower, now_ms, emit);
2154    }
2155    let active = cell.rung_active.load(Ordering::Relaxed) as usize;
2156    let Some(rung) = spec.rungs.get(active) else {
2157        return;
2158    };
2159    if rung.route_ms == 0 {
2160        return;
2161    }
2162    let Some(count) = monitor_table
2163        .get(rung.output_row as usize)
2164        .map(|m| m.cell.count.load(Ordering::Relaxed))
2165    else {
2166        return;
2167    };
2168    match cell.rung_state.load(Ordering::Relaxed) {
2169        RUNG_ARMED => {
2170            let started = rung.starts_at.is_empty()
2171                || rung
2172                    .starts_at
2173                    .iter()
2174                    .any(|m| member_fault(*m, monitor_states, age_states).is_some());
2175            if !started {
2176                return;
2177            }
2178            let clock = if rung.starts_at.is_empty() {
2179                cell.rung_armed_ms.load(Ordering::Relaxed)
2180            } else {
2181                now_ms
2182            };
2183            cell.rung_clock_ms.store(clock, Ordering::Relaxed);
2184            cell.rung_count.store(count, Ordering::Relaxed);
2185            cell.rung_state.store(RUNG_WATCHING, Ordering::Relaxed);
2186        }
2187        RUNG_WATCHING => {
2188            let elapsed = now_ms.wrapping_sub(cell.rung_clock_ms.load(Ordering::Relaxed));
2189            let answered = count != cell.rung_count.load(Ordering::Relaxed);
2190            if !answered && elapsed <= rung.route_ms {
2191                return;
2192            }
2193            cell.rung_state.store(RUNG_JUDGED, Ordering::Relaxed);
2194            if elapsed > rung.route_ms {
2195                emit(Violation {
2196                    rule: "hazard-route-runtime",
2197                    fqn: spec.key,
2198                    measured: elapsed,
2199                    declared: rung.route_ms,
2200                    level: "",
2201                });
2202            }
2203        }
2204        _ => {}
2205    }
2206}
2207
2208#[cfg(test)]
2209mod hazard_tests {
2210    use super::*;
2211
2212    static PUB_CELL: PubMonitorCell = PubMonitorCell::new();
2213    static SUB_CELL: SubMonitorCell = SubMonitorCell::new();
2214    static SINK_CELL: PubMonitorCell = PubMonitorCell::new();
2215
2216    static RATE_ROWS: [MonitorSpec; 2] = [
2217        MonitorSpec {
2218            topic: "/scan",
2219            fqn: "/sensor/scan",
2220            min_rate_hz_milli: 10_000,
2221            max_latency_ms: 0,
2222            route_trigger: "",
2223            route_max_latency_ms: 0,
2224            route_deadline_ms: 0,
2225            reaction_id: 0,
2226            mechanism: 0,
2227            cell: &PUB_CELL,
2228        },
2229        MonitorSpec {
2230            topic: "/stop",
2231            fqn: "/handler/stop",
2232            min_rate_hz_milli: 0,
2233            max_latency_ms: 0,
2234            route_trigger: "",
2235            route_max_latency_ms: 0,
2236            route_deadline_ms: 0,
2237            reaction_id: 0,
2238            mechanism: 0,
2239            cell: &SINK_CELL,
2240        },
2241    ];
2242    #[allow(dead_code)]
2243    static AGE_ROW: AgeMonitorSpec = AgeMonitorSpec {
2244        topic: "/scan",
2245        fqn: "/handler/scan",
2246        max_age_ms: 100,
2247        deadline_ms: 0,
2248        cell: &SUB_CELL,
2249    };
2250
2251    fn run(
2252        spec: &HazardSpec,
2253        mon: &[MonitorState],
2254        age: &[AgeState],
2255        now: u32,
2256    ) -> std::vec::Vec<Violation> {
2257        let mut out = std::vec::Vec::new();
2258        check_hazard(spec, &RATE_ROWS, mon, age, 0, now, |v| out.push(v));
2259        out
2260    }
2261
2262    /// detected -> reaction -> recovered, each once, on a silence guard, with
2263    /// times measured from the guard's last take.
2264    #[test]
2265    fn a_silence_guard_detects_reacts_and_recovers_once_each() {
2266        static CELL: HazardCell = HazardCell::new();
2267        static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2268            all_of: false,
2269            members: &[HazardMonitorRef::Age(0)],
2270        }];
2271        let spec = HazardSpec {
2272            key: "demo.launch.xml/scan_lost",
2273            ftti_ms: 500,
2274            settle_ms: 30,
2275            monitors: &MONITORS,
2276            sink: 1,
2277            reaction_id: 0,
2278            rungs: &[],
2279            cell: &CELL,
2280        };
2281        let mon = [MonitorState::default(); 2];
2282        let mut age = [AgeState::default(); 1];
2283        assert!(run(&spec, &mon, &age, 1_000).is_empty(), "clear: nothing");
2284
2285        age[0].silence_reported = true;
2286        age[0].last_take_ms = 900;
2287        let v = run(&spec, &mon, &age, 1_000);
2288        assert_eq!(v.len(), 1);
2289        assert_eq!((v[0].rule, v[0].fqn), ("hazard-detected", spec.key));
2290        assert_eq!((v[0].measured, v[0].declared), (100, 500));
2291        assert!(run(&spec, &mon, &age, 1_010).is_empty(), "detected once");
2292
2293        SINK_CELL.count.fetch_add(1, Ordering::Relaxed);
2294        let v = run(&spec, &mon, &age, 1_050);
2295        assert_eq!(v.len(), 1);
2296        assert_eq!(v[0].rule, "hazard-reaction");
2297        assert_eq!(v[0].measured, 150 + 30, "fault-to-reaction plus settle");
2298        SINK_CELL.count.fetch_add(1, Ordering::Relaxed);
2299        assert!(run(&spec, &mon, &age, 1_060).is_empty(), "reacted once");
2300
2301        age[0].silence_reported = false;
2302        let v = run(&spec, &mon, &age, 1_200);
2303        assert_eq!(v.len(), 1);
2304        assert_eq!((v[0].rule, v[0].measured), ("hazard-recovered", 300));
2305        assert!(run(&spec, &mon, &age, 1_210).is_empty(), "recovered once");
2306    }
2307
2308    /// A redundant set faults only when every member has.
2309    #[test]
2310    fn an_all_of_guard_waits_for_every_member() {
2311        static CELL: HazardCell = HazardCell::new();
2312        static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2313            all_of: true,
2314            members: &[HazardMonitorRef::Age(0), HazardMonitorRef::Rate(0)],
2315        }];
2316        let spec = HazardSpec {
2317            key: "demo.launch.xml/both_lost",
2318            ftti_ms: 0,
2319            settle_ms: 0,
2320            monitors: &MONITORS,
2321            sink: NO_SINK,
2322            reaction_id: 0,
2323            rungs: &[],
2324            cell: &CELL,
2325        };
2326        let mut mon = [MonitorState::default(); 2];
2327        let mut age = [AgeState::default(); 1];
2328        age[0].silence_reported = true;
2329        assert!(
2330            run(&spec, &mon, &age, 10).is_empty(),
2331            "one of two: no hazard"
2332        );
2333        mon[0].violated_last_window = true;
2334        let v = run(&spec, &mon, &age, 20);
2335        assert_eq!(v[0].rule, "hazard-detected");
2336        assert_eq!(v[0].declared, 0, "no FTTI declared");
2337    }
2338
2339    /// phase-462 W4 -- the text `mode_variants::render_mode_tables_rs` emits
2340    /// after the base tables for a one-row model with one mode (its
2341    /// `the_variant_tables_render_over_the_base_cells` fixture), verbatim but
2342    /// for the crate root, so the generated shape compiles against the real
2343    /// types. phase-462 W4c -- with the deadline rows and switch budget of its
2344    /// `the_variant_tables_render_deadlines_and_the_switch_budget` fixture.
2345    #[allow(dead_code, non_upper_case_globals)]
2346    mod rendered_modes {
2347        use crate::executor::monitor::{AgeMonitorSpec, MonitorSpec, PubMonitorCell};
2348
2349        static NROS_MONITOR_CELL_0: PubMonitorCell = PubMonitorCell::new();
2350        pub static NROS_MONITORS: &[MonitorSpec] = &[MonitorSpec {
2351            topic: "/cmd",
2352            fqn: "/talker/cmd",
2353            min_rate_hz_milli: 10000u32,
2354            max_latency_ms: 20u32,
2355            route_trigger: "",
2356            route_max_latency_ms: 0u32,
2357            route_deadline_ms: 0u32,
2358            reaction_id: 0u16,
2359            mechanism: 0u8,
2360            cell: &NROS_MONITOR_CELL_0,
2361        }];
2362        pub static NROS_AGE_MONITORS: &[AgeMonitorSpec] = &[];
2363
2364        // phase-462 W4 -- the contract's modes: the base rows, the base cells, the
2365        // mode's numbers.
2366        pub static NROS_MODE_MONITORS_1: &[MonitorSpec] = &[MonitorSpec {
2367            topic: "/cmd",
2368            fqn: "/talker/cmd",
2369            min_rate_hz_milli: 5000u32,
2370            max_latency_ms: 20u32,
2371            route_trigger: "",
2372            route_max_latency_ms: 0u32,
2373            route_deadline_ms: 0u32,
2374            reaction_id: 0u16,
2375            mechanism: 0u8,
2376            cell: &NROS_MONITOR_CELL_0,
2377        }];
2378        pub static NROS_MODE_AGE_MONITORS_1: &[AgeMonitorSpec] = &[];
2379        pub static NROS_MODE_DEADLINES_0: &[crate::executor::monitor::ModeDeadline] =
2380            &[crate::executor::monitor::ModeDeadline {
2381                sc: 0u8,
2382                deadline_us: 5000u32,
2383            }];
2384        pub static NROS_MODE_DEADLINES_1: &[crate::executor::monitor::ModeDeadline] =
2385            &[crate::executor::monitor::ModeDeadline {
2386                sc: 0u8,
2387                deadline_us: 2000u32,
2388            }];
2389        pub static NROS_MODE_TABLES: &[crate::executor::monitor::ModeTables] = &[
2390            crate::executor::monitor::ModeTables {
2391                monitors: NROS_MONITORS,
2392                ages: NROS_AGE_MONITORS,
2393                deadlines: NROS_MODE_DEADLINES_0,
2394                switch_budget_ms: 0u32,
2395                reaction: "",
2396            },
2397            crate::executor::monitor::ModeTables {
2398                monitors: NROS_MODE_MONITORS_1,
2399                ages: NROS_MODE_AGE_MONITORS_1,
2400                deadlines: NROS_MODE_DEADLINES_1,
2401                switch_budget_ms: 50u32,
2402                reaction: "//enter_safe",
2403            },
2404        ];
2405
2406        /// Install the mode variants AFTER `nros_install_monitors`; then
2407        /// `request_mode(id)` switches this executor at its next spin.
2408        pub fn nros_install_mode_tables(
2409            executor: &mut crate::executor::Executor<'_>,
2410        ) -> ::core::result::Result<(), crate::executor::monitor::ModeTablesMismatch> {
2411            executor.set_mode_tables(NROS_MODE_TABLES)
2412        }
2413    }
2414
2415    /// The text `contract_monitors::render_monitor_rs_full` emits for the
2416    /// W3a/W3b fixture (one sensor, one handler, one hazard), verbatim but for
2417    /// the crate root. It is here so the GENERATED shape is compiled against
2418    /// the real types: a renderer change that stops compiling has to change
2419    /// this copy too, in plain sight.
2420    #[allow(dead_code, non_upper_case_globals)]
2421    mod rendered {
2422        use crate::executor::monitor::{
2423            AgeMonitorSpec, MonitorSpec, PubMonitorCell, SubMonitorCell,
2424        };
2425
2426        static NROS_MONITOR_CELL_0: PubMonitorCell = PubMonitorCell::new();
2427        static NROS_MONITOR_CELL_1: PubMonitorCell = PubMonitorCell::new();
2428        static NROS_AGE_CELL_0: SubMonitorCell = SubMonitorCell::new();
2429
2430        pub static NROS_MONITORS: &[MonitorSpec] = &[
2431            MonitorSpec {
2432                topic: "/stop",
2433                fqn: "/handler/stop",
2434                min_rate_hz_milli: 0u32,
2435                max_latency_ms: 20u32,
2436                route_trigger: "/scan",
2437                route_max_latency_ms: 20u32,
2438                route_deadline_ms: 0u32,
2439                reaction_id: 0u16,
2440                mechanism: 0u8,
2441                cell: &NROS_MONITOR_CELL_0,
2442            },
2443            MonitorSpec {
2444                topic: "/scan",
2445                fqn: "/sensor/scan",
2446                min_rate_hz_milli: 10000u32,
2447                max_latency_ms: 0u32,
2448                route_trigger: "",
2449                route_max_latency_ms: 0u32,
2450                route_deadline_ms: 0u32,
2451                reaction_id: 0u16,
2452                mechanism: 0u8,
2453                cell: &NROS_MONITOR_CELL_1,
2454            },
2455        ];
2456
2457        pub static NROS_AGE_MONITORS: &[AgeMonitorSpec] = &[AgeMonitorSpec {
2458            topic: "/scan",
2459            fqn: "/handler/scan",
2460            max_age_ms: 100u32,
2461            deadline_ms: 0,
2462            cell: &NROS_AGE_CELL_0,
2463        }];
2464
2465        use crate::executor::monitor::{
2466            HazardCell, HazardMonitorRef, HazardMonitorSpec, HazardSpec,
2467        };
2468
2469        static NROS_HAZARD_CELL_0: HazardCell = HazardCell::new();
2470        const NROS_HAZARD_MONITORS_0: &[HazardMonitorSpec] = &[HazardMonitorSpec {
2471            all_of: false,
2472            members: &[HazardMonitorRef::Age(0u16), HazardMonitorRef::Rate(1u16)],
2473        }];
2474
2475        pub static NROS_HAZARDS: &[HazardSpec] = &[HazardSpec {
2476            key: "demo.launch.xml/scan_lost",
2477            ftti_ms: 0u32,
2478            settle_ms: 30u32,
2479            monitors: NROS_HAZARD_MONITORS_0,
2480            sink: 0u16,
2481            reaction_id: 1u16,
2482            rungs: &[crate::executor::monitor::RungSpec {
2483                mode: crate::executor::monitor::NO_MODE,
2484                output_row: 0u16,
2485                route_ms: 25u32,
2486                role: 2u8,
2487                level: "stop",
2488                starts_at: &[HazardMonitorRef::Age(0u16)],
2489            }],
2490            cell: &NROS_HAZARD_CELL_0,
2491        }];
2492    }
2493
2494    /// The rendered tables drive the observer: the age row's silence is the
2495    /// hazard, and the sink row the renderer chose is the one it watches.
2496    #[test]
2497    fn the_rendered_include_drives_the_observer() {
2498        let spec = &rendered::NROS_HAZARDS[0];
2499        let mon = [MonitorState::default(); 2];
2500        let mut age = [AgeState::default(); 1];
2501        age[0].silence_reported = true;
2502        age[0].last_take_ms = 40;
2503        let mut out = std::vec::Vec::new();
2504        check_hazard(spec, rendered::NROS_MONITORS, &mon, &age, 0, 100, |v| {
2505            out.push(v)
2506        });
2507        assert_eq!((out[0].rule, out[0].measured), ("hazard-detected", 60));
2508        assert_eq!(
2509            rendered::NROS_MONITORS[spec.sink as usize].fqn,
2510            "/handler/stop"
2511        );
2512    }
2513
2514    /// play_launch phase 96 W4.2 -- a rung's route runs from the detection
2515    /// tick (the fire), not from the fault: a rung that answers within
2516    /// `route_ms` reports nothing, one that answers late reports the elapsed
2517    /// time, one that never answers is reported once when its route passes,
2518    /// and each detection is judged once.
2519    #[test]
2520    fn a_rung_route_is_judged_from_the_fire_once_per_detection() {
2521        static CELL: HazardCell = HazardCell::new();
2522        static RUNG_CELL: PubMonitorCell = PubMonitorCell::new();
2523        static ROWS: [MonitorSpec; 1] = [MonitorSpec {
2524            topic: "/brake",
2525            fqn: "/handler/brake",
2526            min_rate_hz_milli: 0,
2527            max_latency_ms: 0,
2528            route_trigger: "",
2529            route_max_latency_ms: 0,
2530            route_deadline_ms: 0,
2531            reaction_id: 0,
2532            mechanism: 0,
2533            cell: &RUNG_CELL,
2534        }];
2535        static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2536            all_of: false,
2537            members: &[HazardMonitorRef::Age(0)],
2538        }];
2539        let spec = HazardSpec {
2540            key: "demo.launch.xml/scan_lost",
2541            ftti_ms: 500,
2542            settle_ms: 0,
2543            monitors: &MONITORS,
2544            sink: NO_SINK,
2545            reaction_id: 0,
2546            rungs: &[RungSpec {
2547                mode: NO_MODE,
2548                output_row: 0,
2549                route_ms: 20,
2550                role: RUNG_ROLE_FLOOR,
2551                level: "brake",
2552                starts_at: &[],
2553            }],
2554            cell: &CELL,
2555        };
2556        let mon = [MonitorState::default(); 1];
2557        let mut age = [AgeState::default(); 1];
2558        let tick = |age: &[AgeState], now: u32| {
2559            let mut out = std::vec::Vec::new();
2560            check_hazard(&spec, &ROWS, &mon, age, 0, now, |v| out.push(v));
2561            out
2562        };
2563        let routes = |v: &[Violation]| -> std::vec::Vec<(u32, u32)> {
2564            v.iter()
2565                .filter(|v| v.rule == "hazard-route-runtime")
2566                .map(|v| (v.measured, v.declared))
2567                .collect()
2568        };
2569        let detect = |age: &mut [AgeState], now: u32| {
2570            age[0].silence_reported = true;
2571            age[0].last_take_ms = now - 150; // the fault began long before
2572            let v = tick(age, now);
2573            assert_eq!(v[0].rule, "hazard-detected");
2574            assert!(routes(&v).is_empty(), "nothing is judged at the fire");
2575        };
2576        let recover = |age: &mut [AgeState], now: u32| {
2577            age[0].silence_reported = false;
2578            let v = tick(age, now);
2579            assert_eq!(v[0].rule, "hazard-recovered");
2580        };
2581
2582        // Within: a publish 15 ms after the fire, route 20 ms.
2583        detect(&mut age, 1_000);
2584        assert!(routes(&tick(&age, 1_010)).is_empty(), "still within");
2585        RUNG_CELL.count.fetch_add(1, Ordering::Relaxed);
2586        assert!(routes(&tick(&age, 1_015)).is_empty(), "answered in time");
2587        RUNG_CELL.count.fetch_add(1, Ordering::Relaxed);
2588        assert!(routes(&tick(&age, 1_100)).is_empty(), "judged once");
2589        recover(&mut age, 1_200);
2590
2591        // Late: the first publish is seen at the tick 30 ms after the fire,
2592        // and 30 > 20. (The monitor has tick resolution, like
2593        // `hazard-reaction`.)
2594        detect(&mut age, 2_000);
2595        RUNG_CELL.count.fetch_add(1, Ordering::Relaxed);
2596        let v = tick(&age, 2_030);
2597        assert_eq!(routes(&v), [(30, 20)], "late: measured from the fire");
2598        RUNG_CELL.count.fetch_add(1, Ordering::Relaxed);
2599        assert!(routes(&tick(&age, 2_040)).is_empty(), "judged once");
2600        recover(&mut age, 2_100);
2601
2602        // Never: no publish; reported at the first tick past the route.
2603        detect(&mut age, 3_000);
2604        assert!(routes(&tick(&age, 3_020)).is_empty(), "20 is not past 20");
2605        assert_eq!(routes(&tick(&age, 3_021)), [(21, 20)], "overdue");
2606        assert!(routes(&tick(&age, 3_500)).is_empty(), "reported once");
2607        RUNG_CELL.count.fetch_add(1, Ordering::Relaxed);
2608        assert!(
2609            routes(&tick(&age, 3_510)).is_empty(),
2610            "a late answer after the overdue report is not a second verdict"
2611        );
2612        recover(&mut age, 3_600);
2613
2614        // A recovery before the rung answers ends the watch silently.
2615        detect(&mut age, 4_000);
2616        recover(&mut age, 4_005);
2617        assert!(
2618            routes(&tick(&age, 4_100)).is_empty(),
2619            "nothing after recovery"
2620        );
2621    }
2622
2623    /// A rung with no route (`route_ms` 0) never reports one, whatever
2624    /// `output_row` names: row 0 is a real row.
2625    #[test]
2626    fn no_route_no_route_verdict() {
2627        static CELL: HazardCell = HazardCell::new();
2628        static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2629            all_of: false,
2630            members: &[HazardMonitorRef::Rate(0)],
2631        }];
2632        let spec = HazardSpec {
2633            key: "k",
2634            ftti_ms: 100,
2635            settle_ms: 0,
2636            monitors: &MONITORS,
2637            sink: NO_SINK,
2638            reaction_id: 0,
2639            rungs: &[RungSpec {
2640                mode: NO_MODE,
2641                output_row: 0,
2642                route_ms: 0,
2643                role: RUNG_ROLE_FLOOR,
2644                level: "k",
2645                starts_at: &[],
2646            }],
2647            cell: &CELL,
2648        };
2649        let mut mon = [MonitorState::default(); 2];
2650        mon[0].violated_last_window = true;
2651        assert_eq!(run(&spec, &mon, &[], 50)[0].rule, "hazard-detected");
2652        assert!(run(&spec, &mon, &[], 5_000).is_empty());
2653    }
2654
2655    /// A three-rung ladder -- a `window:` rung (mode 1), a rung (mode 2) and
2656    /// the floor (mode 3) -- each on its own output row, with distinct routes
2657    /// so a verdict names the rung it judged.
2658    ///
2659    /// Each test builds its OWN output cells and hazard cell: `cargo test`
2660    /// runs tests on parallel threads, and one shared `static` row let a
2661    /// `publish(0)` in one test answer the top rung in another, which then
2662    /// reported no route violation (seen as an intermittent failure of
2663    /// `a_fault_at_the_top_is_judged_against_the_top_rung`).
2664    mod ladder {
2665        use super::*;
2666
2667        const fn row(topic: &'static str, cell: &'static PubMonitorCell) -> MonitorSpec {
2668            MonitorSpec {
2669                topic,
2670                fqn: topic,
2671                min_rate_hz_milli: 0,
2672                max_latency_ms: 0,
2673                route_trigger: "",
2674                route_max_latency_ms: 0,
2675                route_deadline_ms: 0,
2676                reaction_id: 0,
2677                mechanism: 0,
2678                cell,
2679            }
2680        }
2681        pub static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2682            all_of: false,
2683            members: &[HazardMonitorRef::Age(0), HazardMonitorRef::Age(1)],
2684        }];
2685        /// The top rung starts at the detector the guard's age row 0 belongs
2686        /// to; the two below start at the window owner, which is not a guard
2687        /// detector here, so their clocks start when the ladder falls.
2688        pub static RUNGS: [RungSpec; 3] = [
2689            RungSpec {
2690                mode: 1,
2691                output_row: 0,
2692                route_ms: 10,
2693                role: RUNG_ROLE_WINDOW,
2694                level: "slow",
2695                starts_at: &[HazardMonitorRef::Age(0)],
2696            },
2697            RungSpec {
2698                mode: 2,
2699                output_row: 1,
2700                route_ms: 20,
2701                role: RUNG_ROLE_RUNG,
2702                level: "stop",
2703                starts_at: &[],
2704            },
2705            RungSpec {
2706                mode: 3,
2707                output_row: 2,
2708                route_ms: 30,
2709                role: RUNG_ROLE_FLOOR,
2710                level: "estop",
2711                starts_at: &[],
2712            },
2713        ];
2714        fn spec(cell: &'static HazardCell) -> HazardSpec {
2715            HazardSpec {
2716                key: "demo.launch.xml/scan_lost",
2717                ftti_ms: 0,
2718                settle_ms: 0,
2719                monitors: &MONITORS,
2720                sink: NO_SINK,
2721                reaction_id: 0,
2722                rungs: &RUNGS,
2723                cell,
2724            }
2725        }
2726        /// One test's ladder: its own output rows and hazard cell, leaked so
2727        /// they are `'static` like the generated tables they stand in for.
2728        pub struct Ladder {
2729            out: &'static [PubMonitorCell; 3],
2730            rows: &'static [MonitorSpec; 3],
2731            spec: HazardSpec,
2732        }
2733        impl Ladder {
2734            pub fn new() -> Self {
2735                let out: &'static [PubMonitorCell; 3] =
2736                    std::boxed::Box::leak(std::boxed::Box::new([
2737                        PubMonitorCell::new(),
2738                        PubMonitorCell::new(),
2739                        PubMonitorCell::new(),
2740                    ]));
2741                let rows: &'static [MonitorSpec; 3] =
2742                    std::boxed::Box::leak(std::boxed::Box::new([
2743                        row("/slow", &out[0]),
2744                        row("/stop", &out[1]),
2745                        row("/estop", &out[2]),
2746                    ]));
2747                let cell: &'static HazardCell =
2748                    std::boxed::Box::leak(std::boxed::Box::new(HazardCell::new()));
2749                Ladder {
2750                    out,
2751                    rows,
2752                    spec: spec(cell),
2753                }
2754            }
2755            pub fn tick(&self, age: &[AgeState], mode: u16, now: u32) -> std::vec::Vec<(u32, u32)> {
2756                self.verdicts(age, mode, now)
2757                    .iter()
2758                    .filter(|v| v.rule == "hazard-route-runtime")
2759                    .map(|v| (v.measured, v.declared))
2760                    .collect()
2761            }
2762            /// Every verdict of one tick, in emission order.
2763            pub fn verdicts(
2764                &self,
2765                age: &[AgeState],
2766                mode: u16,
2767                now: u32,
2768            ) -> std::vec::Vec<Violation> {
2769                let mon = [MonitorState::default(); 3];
2770                let mut out = std::vec::Vec::new();
2771                check_hazard(&self.spec, self.rows, &mon, age, mode, now, |v| out.push(v));
2772                out
2773            }
2774            /// The `hazard-level-runtime` reports of one tick,
2775            /// as `(level, index, ladder length)`.
2776            pub fn levels(
2777                &self,
2778                age: &[AgeState],
2779                mode: u16,
2780                now: u32,
2781            ) -> std::vec::Vec<(&'static str, u32, u32)> {
2782                self.verdicts(age, mode, now)
2783                    .iter()
2784                    .filter(|v| v.rule == "hazard-level-runtime")
2785                    .map(|v| (v.level, v.measured, v.declared))
2786                    .collect()
2787            }
2788            pub fn publish(&self, i: usize) {
2789                self.out[i].count.fetch_add(1, Ordering::Relaxed);
2790            }
2791        }
2792        pub fn faulted(silent: [bool; 2]) -> [AgeState; 2] {
2793            let mut age = [AgeState::default(); 2];
2794            for (a, s) in age.iter_mut().zip(silent) {
2795                a.silence_reported = s;
2796            }
2797            age
2798        }
2799    }
2800
2801    /// phase-560 W8 -- a detection in the base mode reports the TOP level,
2802    /// index 0 of 3, right after `hazard-detected`, keyed by the hazard.
2803    #[test]
2804    fn a_detection_reports_the_top_level() {
2805        let rig = ladder::Ladder::new();
2806        let age = ladder::faulted([true, false]);
2807        let v = rig.verdicts(&age, 0, 1_000);
2808        let rules: std::vec::Vec<&str> = v.iter().map(|v| v.rule).collect();
2809        assert_eq!(rules, ["hazard-detected", "hazard-level-runtime"]);
2810        assert_eq!(v[1].fqn, "demo.launch.xml/scan_lost");
2811        assert_eq!((v[1].level, v[1].measured, v[1].declared), ("slow", 0, 3));
2812        assert!(v[0].level.is_empty(), "only the level report names a level");
2813    }
2814
2815    /// phase-560 W8 -- a detection while the executor is already in a lower
2816    /// rung's mode reports THAT level, not the top.
2817    #[test]
2818    fn a_detection_after_a_fall_reports_the_level_the_ladder_is_on() {
2819        let rig = ladder::Ladder::new();
2820        let age = ladder::faulted([true, false]);
2821        assert_eq!(rig.levels(&age, 2, 2_000), [("stop", 1, 3)]);
2822    }
2823
2824    /// phase-560 W8 -- a fall reports the lower level, once; a tick on the
2825    /// same level, a rise, and a mode that is no rung report nothing.
2826    #[test]
2827    fn a_fall_reports_the_lower_level_once() {
2828        let rig = ladder::Ladder::new();
2829        let age = ladder::faulted([true, false]);
2830        assert_eq!(rig.levels(&age, 0, 1_000), [("slow", 0, 3)]);
2831        assert!(rig.levels(&age, 0, 1_010).is_empty(), "level unchanged");
2832        assert!(rig.levels(&age, 1, 1_020).is_empty(), "still the top level");
2833        assert_eq!(rig.levels(&age, 2, 1_500), [("stop", 1, 3)], "the fall");
2834        assert!(rig.levels(&age, 2, 1_510).is_empty(), "level unchanged");
2835        assert!(rig.levels(&age, 1, 1_520).is_empty(), "a rise is no fall");
2836        assert_eq!(rig.levels(&age, 3, 1_600), [("estop", 2, 3)], "the floor");
2837        assert!(rig.levels(&age, 3, 1_700).is_empty(), "level unchanged");
2838        // A recovery and a fresh detection report the level again.
2839        rig.verdicts(&ladder::faulted([false, false]), 0, 1_800);
2840        assert_eq!(rig.levels(&age, 0, 1_900), [("slow", 0, 3)]);
2841    }
2842
2843    /// A fault in the base mode is judged against the TOP rung: its output
2844    /// and its route, from its `starts_at` detection.
2845    #[test]
2846    fn a_fault_at_the_top_is_judged_against_the_top_rung() {
2847        let rig = ladder::Ladder::new();
2848        let age = ladder::faulted([true, false]);
2849        assert!(rig.tick(&age, 0, 1_000).is_empty());
2850        // The floor publishing is not the top rung answering.
2851        rig.publish(2);
2852        assert!(rig.tick(&age, 0, 1_005).is_empty());
2853        assert_eq!(rig.tick(&age, 0, 1_011), [(11, 10)], "top route 10");
2854    }
2855
2856    /// A fault arriving after the ladder has fallen -- the executor is already
2857    /// in the rung's mode -- is judged against THAT rung.
2858    #[test]
2859    fn a_fault_after_a_fall_is_judged_against_the_lower_rung() {
2860        let rig = ladder::Ladder::new();
2861        let age = ladder::faulted([true, false]);
2862        assert!(rig.tick(&age, 2, 2_000).is_empty());
2863        // Only the active rung's output answers it.
2864        rig.publish(0);
2865        assert!(rig.tick(&age, 2, 2_015).is_empty(), "within 20");
2866        assert_eq!(rig.tick(&age, 2, 2_021), [(21, 20)], "rung route 20");
2867        // And it answered within its route on a second fault.
2868        let clear = ladder::faulted([false, false]);
2869        rig.tick(&clear, 2, 2_100);
2870        assert!(rig.tick(&age, 2, 3_000).is_empty());
2871        rig.publish(1);
2872        assert!(rig.tick(&age, 2, 3_019).is_empty(), "answered at 19");
2873        assert!(rig.tick(&age, 2, 3_500).is_empty(), "judged once");
2874    }
2875
2876    /// The window rung answers, its window passes and the ladder falls to the
2877    /// rung below: that rung's clock starts at the FALL (its `starts_at` is
2878    /// the window owner, not a detector here), and it is judged on its own
2879    /// output and route.
2880    #[test]
2881    fn a_fall_from_the_window_rung_starts_the_rung_below_at_the_fall() {
2882        let rig = ladder::Ladder::new();
2883        let age = ladder::faulted([true, false]);
2884        assert!(rig.tick(&age, 0, 1_000).is_empty());
2885        rig.publish(0);
2886        assert!(rig.tick(&age, 1, 1_004).is_empty(), "window rung in time");
2887        // The window passes; the executor enters the rung below at 1_500.
2888        assert!(rig.tick(&age, 2, 1_500).is_empty(), "nothing at the fall");
2889        assert_eq!(
2890            rig.tick(&age, 2, 1_521),
2891            [(21, 20)],
2892            "measured from the fall, not the fire"
2893        );
2894    }
2895
2896    /// The floor: a fall straight to it starts its clock, and a floor that
2897    /// never publishes is reported once when its route passes. A rise back up
2898    /// the ladder is not a fall.
2899    #[test]
2900    fn a_fall_to_the_floor_is_judged_against_the_floor() {
2901        let rig = ladder::Ladder::new();
2902        let age = ladder::faulted([true, false]);
2903        assert!(rig.tick(&age, 0, 1_000).is_empty());
2904        assert_eq!(rig.tick(&age, 0, 1_011), [(11, 10)], "top overdue");
2905        assert!(rig.tick(&age, 3, 1_100).is_empty(), "fall to the floor");
2906        assert!(rig.tick(&age, 1, 1_110).is_empty(), "not a fall");
2907        assert!(rig.tick(&age, 3, 1_130).is_empty(), "30 is not past 30");
2908        assert_eq!(rig.tick(&age, 3, 1_131), [(31, 30)], "floor route 30");
2909        assert!(rig.tick(&age, 3, 1_500).is_empty(), "reported once");
2910    }
2911
2912    /// The top rung's clock starts at ITS `starts_at` detector, not at the
2913    /// first guard member to fault: here member 1 detects first and member 0
2914    /// (the top rung's `starts_at`) only later.
2915    #[test]
2916    fn the_route_clock_starts_at_the_starts_at_detection() {
2917        let rig = ladder::Ladder::new();
2918        assert!(
2919            rig.tick(&ladder::faulted([false, true]), 0, 1_000)
2920                .is_empty()
2921        );
2922        let both = ladder::faulted([true, true]);
2923        assert!(
2924            rig.tick(&both, 0, 1_050).is_empty(),
2925            "50 ms after the fire, but the clock starts now"
2926        );
2927        assert!(rig.tick(&both, 0, 1_060).is_empty(), "10 is not past 10");
2928        assert_eq!(rig.tick(&both, 0, 1_061), [(11, 10)]);
2929    }
2930
2931    /// With no sink the observer never claims a reaction it cannot see.
2932    #[test]
2933    fn no_sink_no_reaction() {
2934        static CELL: HazardCell = HazardCell::new();
2935        static MONITORS: [HazardMonitorSpec; 1] = [HazardMonitorSpec {
2936            all_of: false,
2937            members: &[HazardMonitorRef::Rate(0)],
2938        }];
2939        let spec = HazardSpec {
2940            key: "k",
2941            ftti_ms: 100,
2942            settle_ms: 0,
2943            monitors: &MONITORS,
2944            sink: NO_SINK,
2945            reaction_id: 0,
2946            rungs: &[],
2947            cell: &CELL,
2948        };
2949        let mut mon = [MonitorState::default(); 2];
2950        mon[0].violated_last_window = true;
2951        let v = run(&spec, &mon, &[], 50);
2952        assert_eq!((v[0].rule, v[0].measured), ("hazard-detected", 0));
2953        PUB_CELL.count.fetch_add(5, Ordering::Relaxed);
2954        assert!(run(&spec, &mon, &[], 60).is_empty());
2955    }
2956}
2957
2958#[cfg(test)]
2959mod tests {
2960    use super::*;
2961
2962    static CELL: PubMonitorCell = PubMonitorCell::new();
2963
2964    /// phase-496 W1 -- the Autoware Safety Island's shape: 14 rate rows and
2965    /// no age rows fit an executor sized 14/0, and a 15th rate row is refused
2966    /// with the knob to raise NAMED, not truncated.
2967    #[test]
2968    fn a_table_past_the_knob_is_refused_and_names_it() {
2969        assert_eq!(check_capacity_against(14, 0, 14, 0), Ok(()));
2970        let full = check_capacity_against(15, 0, 14, 0).expect_err("15 > 14 must refuse");
2971        assert_eq!(full.knob, "NROS_EXECUTOR_MAX_MONITORS");
2972        assert_eq!((full.rows, full.capacity), (15, 14));
2973        let said = std::format!("{full}");
2974        assert!(
2975            said.contains("raise NROS_EXECUTOR_MAX_MONITORS"),
2976            "the refusal must name the knob: {said}"
2977        );
2978        let age = check_capacity_against(0, 1, 14, 0).expect_err("an age row past 0 must refuse");
2979        assert_eq!(age.knob, "NROS_EXECUTOR_MAX_AGE_MONITORS");
2980        // The two tables are separate knobs: a full age table does not borrow
2981        // from the rate one.
2982        assert!(check_capacity_against(3, 9, 14, 8).is_err());
2983    }
2984
2985    /// The generated consts ARE the public ones, so the installers and the
2986    /// spin loop read one number.
2987    #[test]
2988    fn the_public_bounds_are_the_generated_config() {
2989        assert_eq!(MAX_MONITORS, crate::config::MAX_MONITORS);
2990        assert_eq!(MAX_AGE_MONITORS, crate::config::MAX_AGE_MONITORS);
2991        assert_eq!(check_table_capacity(MAX_MONITORS, MAX_AGE_MONITORS), Ok(()));
2992        assert!(check_table_capacity(MAX_MONITORS + 1, 0).is_err());
2993    }
2994
2995    fn spec(min_milli: u32) -> MonitorSpec {
2996        MonitorSpec {
2997            topic: "/chatter",
2998            fqn: "/demo/talker/chatter",
2999            min_rate_hz_milli: min_milli,
3000            max_latency_ms: 0,
3001            route_trigger: "",
3002            route_max_latency_ms: 0,
3003            route_deadline_ms: 0,
3004            reaction_id: 0,
3005            mechanism: 0,
3006            cell: &CELL,
3007        }
3008    }
3009
3010    #[test]
3011    fn slow_publisher_fires_once_until_recovery() {
3012        CELL.count.store(0, Ordering::Relaxed);
3013        let s = spec(100_000); // 100 Hz declared
3014        let mut st = MonitorState::default();
3015
3016        // t=0: opens window.
3017        assert!(check_rate(&s, &mut st, 0).is_none());
3018        // 5 publishes in 5 s = 1 Hz — violation.
3019        CELL.count.store(5, Ordering::Relaxed);
3020        let v = check_rate(&s, &mut st, RATE_CHECK_INTERVAL_US).expect("fires");
3021        assert_eq!(v.rule, "rate-hierarchy-runtime");
3022        assert_eq!(v.fqn, "/demo/talker/chatter");
3023        assert_eq!(v.measured, 1_000);
3024        assert_eq!(v.declared, 100_000);
3025        // Still slow next window — suppressed (no re-report spam).
3026        CELL.count.store(10, Ordering::Relaxed);
3027        assert!(check_rate(&s, &mut st, 2 * RATE_CHECK_INTERVAL_US).is_none());
3028        // Recovers (500 publishes in 5 s = 100 Hz) — clean window resets.
3029        CELL.count.store(510, Ordering::Relaxed);
3030        assert!(check_rate(&s, &mut st, 3 * RATE_CHECK_INTERVAL_US).is_none());
3031        // Degrades again — fires again.
3032        CELL.count.store(511, Ordering::Relaxed);
3033        assert!(check_rate(&s, &mut st, 4 * RATE_CHECK_INTERVAL_US).is_some());
3034    }
3035
3036    /// phase-474 I8 -- the island's first window after arming read 10 Hz
3037    /// publishers at 9984 mHz and never again. The monitor tick runs at the
3038    /// top of a spin, before that spin's dispatch publishes, so in steady
3039    /// state every window boundary sits one spin after a publish and the
3040    /// count matches the span. The window arming opens sits wherever the
3041    /// arming spin fell: off the publisher's phase, it spans 50 publishes
3042    /// over 5007 ms and reads short. A stream at exactly its declared rate,
3043    /// armed mid-period, must not be judged slow.
3044    #[test]
3045    fn a_stream_at_its_rate_armed_mid_period_is_not_judged_slow() {
3046        static C8: PubMonitorCell = PubMonitorCell::new();
3047        let s = MonitorSpec {
3048            topic: "/i8",
3049            fqn: "/n/i8",
3050            min_rate_hz_milli: 10_000, // 10 Hz declared
3051            max_latency_ms: 0,
3052            route_trigger: "",
3053            route_max_latency_ms: 0,
3054            route_deadline_ms: 0,
3055            reaction_id: 0,
3056            mechanism: 0,
3057            cell: &C8,
3058        };
3059        // Published at 0, 100 ms, ..., 50 s: 501 samples before arming.
3060        C8.count.store(501, Ordering::Relaxed);
3061        let mut st = MonitorState::default();
3062        // Arming spin, off the 10 ms grid (a wake for another entry).
3063        assert!(check_rate(&s, &mut st, 50_003_000).is_none());
3064        let mut t = 50_010_000u64;
3065        while t <= 80_000_000 {
3066            // The tick, then the spin's dispatch: the 10 Hz timer publishes.
3067            let v = check_rate(&s, &mut st, t);
3068            assert!(v.is_none(), "judged slow at {t} us: {v:?}");
3069            if t.is_multiple_of(100_000) {
3070                C8.count.fetch_add(1, Ordering::Relaxed);
3071            }
3072            t += 10_000;
3073        }
3074        // And a stream that IS slow is still judged in the first window:
3075        // half its rate from arming on.
3076        static C9: PubMonitorCell = PubMonitorCell::new();
3077        let slow = MonitorSpec { cell: &C9, ..s };
3078        let mut st = MonitorState::default();
3079        assert!(check_rate(&slow, &mut st, 50_003_000).is_none());
3080        let mut t = 50_010_000u64;
3081        let mut fired = None;
3082        while t <= 60_000_000 && fired.is_none() {
3083            fired = check_rate(&slow, &mut st, t).map(|v| (t, v.measured));
3084            if t.is_multiple_of(200_000) {
3085                C9.count.fetch_add(1, Ordering::Relaxed);
3086            }
3087            t += 10_000;
3088        }
3089        let (at, measured) = fired.expect("a 5 Hz stream against 10 Hz is judged");
3090        assert!(measured <= 5_100, "{measured}");
3091        // Judged one window after its first sample: at most one of its
3092        // periods (200 ms) plus a tick later than the window arming opened.
3093        assert!(at <= 50_003_000 + RATE_CHECK_INTERVAL_US + 210_000, "{at}");
3094        // A stream silent from arming on is judged at the first window's end,
3095        // not held open waiting for a sample that never comes.
3096        static C10: PubMonitorCell = PubMonitorCell::new();
3097        let dead = MonitorSpec { cell: &C10, ..s };
3098        let mut st = MonitorState::default();
3099        assert!(check_rate(&dead, &mut st, 50_003_000).is_none());
3100        let v = check_rate(&dead, &mut st, 50_003_000 + RATE_CHECK_INTERVAL_US)
3101            .expect("silent stream judged");
3102        assert_eq!(v.measured, 0);
3103    }
3104
3105    /// phase-474 I9 -- the island's 10 Hz publishers read 9999 of 10000 mHz
3106    /// in every window once I8 aligned the first one: the spin that closes a
3107    /// window runs some hundreds of microseconds after the interval, so the
3108    /// quotient floors under the declared rate while the count is exact. The
3109    /// count judges; a stream at its declared rate checked late is not slow,
3110    /// a stream at half its rate still is.
3111    #[test]
3112    fn a_stream_at_its_rate_checked_late_is_not_judged_slow() {
3113        static C11: PubMonitorCell = PubMonitorCell::new();
3114        let s = MonitorSpec {
3115            topic: "/i9",
3116            fqn: "/n/i9",
3117            min_rate_hz_milli: 10_000,
3118            max_latency_ms: 0,
3119            route_trigger: "",
3120            route_max_latency_ms: 0,
3121            route_deadline_ms: 0,
3122            reaction_id: 0,
3123            mechanism: 0,
3124            cell: &C11,
3125        };
3126        let mut st = MonitorState::default();
3127        // Publishes at 0, 100 ms, ...; the monitor tick runs 700 us after
3128        // each publish, so every window spans the interval plus 700 us.
3129        let mut t = 0u64;
3130        while t <= 60_000_000 {
3131            if t.is_multiple_of(100_000) {
3132                C11.count.fetch_add(1, Ordering::Relaxed);
3133            }
3134            let v = check_rate(&s, &mut st, t + 700);
3135            assert!(v.is_none(), "judged slow at {t} us: {v:?}");
3136            t += 10_000;
3137        }
3138        // Half the rate, checked the same way: judged, measured about 5 Hz.
3139        static C12: PubMonitorCell = PubMonitorCell::new();
3140        let slow = MonitorSpec { cell: &C12, ..s };
3141        let mut st = MonitorState::default();
3142        let mut t = 0u64;
3143        let mut fired = None;
3144        while t <= 20_000_000 && fired.is_none() {
3145            if t.is_multiple_of(200_000) {
3146                C12.count.fetch_add(1, Ordering::Relaxed);
3147            }
3148            fired = check_rate(&slow, &mut st, t + 700).map(|v| v.measured);
3149            t += 10_000;
3150        }
3151        let measured = fired.expect("a 5 Hz stream against 10 Hz is judged");
3152        assert!((4_900..=5_100).contains(&measured), "{measured}");
3153    }
3154
3155    #[test]
3156    fn compliant_and_uncontracted_stay_silent() {
3157        static C2: PubMonitorCell = PubMonitorCell::new();
3158        let s = MonitorSpec {
3159            topic: "/t",
3160            fqn: "/n/t",
3161            min_rate_hz_milli: 500, // 0.5 Hz
3162            max_latency_ms: 0,
3163            route_trigger: "",
3164            route_max_latency_ms: 0,
3165            route_deadline_ms: 0,
3166            reaction_id: 0,
3167            mechanism: 0,
3168            cell: &C2,
3169        };
3170        let mut st = MonitorState::default();
3171        assert!(check_rate(&s, &mut st, 0).is_none());
3172        C2.count.store(5, Ordering::Relaxed); // 1 Hz measured ≥ 0.5 Hz declared
3173        assert!(check_rate(&s, &mut st, RATE_CHECK_INTERVAL_US).is_none());
3174
3175        // min_rate 0 = uncontracted: never fires, no state.
3176        let s0 = MonitorSpec {
3177            topic: "/t",
3178            fqn: "/n/t",
3179            min_rate_hz_milli: 0,
3180            max_latency_ms: 0,
3181            route_trigger: "",
3182            route_max_latency_ms: 0,
3183            route_deadline_ms: 0,
3184            reaction_id: 0,
3185            mechanism: 0,
3186            cell: &C2,
3187        };
3188        let mut st0 = MonitorState::default();
3189        assert!(check_rate(&s0, &mut st0, 10 * RATE_CHECK_INTERVAL_US).is_none());
3190    }
3191
3192    #[test]
3193    fn stale_take_fires_age_once_until_recovery() {
3194        static SC: SubMonitorCell = SubMonitorCell::new();
3195        let s = AgeMonitorSpec {
3196            topic: "/scan",
3197            fqn: "/perc/detector/scan",
3198            max_age_ms: 100,
3199            deadline_ms: 0,
3200            cell: &SC,
3201        };
3202        let mut st = AgeState::default();
3203
3204        // Fresh message: stamped 5 ms ago -- silent. Every tick here SEES a
3205        // take, so the silence rule never opens a window (phase-462 W2).
3206        SC.observe(1_000_000_000, 1_000_005_000);
3207        assert!(check_age(&s, &mut st, Some(0)).is_none());
3208        // Stale: 250 ms old — fires with the measured age.
3209        SC.observe(1_000_000_000, 1_000_250_000);
3210        let v = check_age(&s, &mut st, Some(1_000)).expect("fires");
3211        assert_eq!(v.rule, "max-age-runtime");
3212        assert_eq!(v.fqn, "/perc/detector/scan");
3213        assert_eq!(v.measured, 250);
3214        assert_eq!(v.declared, 100);
3215        // Still stale next window — suppressed.
3216        SC.observe(1_000_000_000, 1_000_300_000);
3217        assert!(check_age(&s, &mut st, Some(2_000)).is_none());
3218        // Recovers — clean window resets; stale again refires.
3219        SC.observe(1_000_000_000, 1_000_010_000);
3220        assert!(check_age(&s, &mut st, Some(3_000)).is_none());
3221        SC.observe(1_000_000_000, 1_000_999_000);
3222        assert!(check_age(&s, &mut st, Some(4_000)).is_some());
3223    }
3224
3225    /// phase-462 W2 -- an input that stops coming is a violation of the same
3226    /// `max_age_ms` promise, and the age rule cannot see it.
3227    #[test]
3228    fn a_silent_subscription_fires_once_until_it_is_fed() {
3229        static SC2: SubMonitorCell = SubMonitorCell::new();
3230        let s = AgeMonitorSpec {
3231            topic: "/scan",
3232            fqn: "/perc/detector/scan",
3233            max_age_ms: 100,
3234            deadline_ms: 0,
3235            cell: &SC2,
3236        };
3237        let mut st = AgeState::default();
3238
3239        // t=0 opens the lease; a first check is never a verdict.
3240        SC2.observe(1_000_000_000, 1_000_005_000);
3241        assert!(check_age(&s, &mut st, Some(0)).is_none());
3242        // 50 ms of nothing, inside the declared 100 ms window.
3243        assert!(check_age(&s, &mut st, Some(50_000)).is_none());
3244        // 120 ms of nothing: the lease is up.
3245        let v = check_age(&s, &mut st, Some(120_000)).expect("silence fires");
3246        assert_eq!(v.rule, "silence-runtime");
3247        assert_eq!(v.fqn, "/perc/detector/scan");
3248        assert_eq!(v.measured, 0, "nothing was taken");
3249        assert_eq!(v.declared, 100, "the window the contract declares");
3250        // Still silent -- one fault, not one per tick.
3251        assert!(check_age(&s, &mut st, Some(500_000)).is_none());
3252        // Fed again: the lease restarts and a later silence reports afresh.
3253        SC2.observe(1_000_000_000, 1_000_005_000);
3254        assert!(check_age(&s, &mut st, Some(600_000)).is_none());
3255        assert!(check_age(&s, &mut st, Some(650_000)).is_none());
3256        assert!(check_age(&s, &mut st, Some(800_000)).is_some());
3257    }
3258
3259    /// The negative control for the same rule, in three parts: an
3260    /// uncontracted endpoint, a fed endpoint, and a build with no clock.
3261    #[test]
3262    fn silence_needs_a_contract_a_gap_and_a_clock() {
3263        static SC3: SubMonitorCell = SubMonitorCell::new();
3264        // No age contract: nothing is promised, so nothing is judged.
3265        let uncontracted = AgeMonitorSpec {
3266            topic: "/t",
3267            fqn: "/n/t",
3268            max_age_ms: 0,
3269            deadline_ms: 0,
3270            cell: &SC3,
3271        };
3272        let mut st = AgeState::default();
3273        assert!(check_age(&uncontracted, &mut st, Some(0)).is_none());
3274        assert!(check_age(&uncontracted, &mut st, Some(10_000_000)).is_none());
3275
3276        // Contracted and fed on every tick: silent rule, silent drain.
3277        let s = AgeMonitorSpec {
3278            max_age_ms: 100,
3279            deadline_ms: 0,
3280            ..uncontracted
3281        };
3282        let mut st = AgeState::default();
3283        for tick in 0..10u64 {
3284            SC3.observe(1_000_000_000, 1_000_001_000);
3285            assert!(
3286                check_age(&s, &mut st, Some(tick * 1_000_000)).is_none(),
3287                "a fed endpoint never reports silence"
3288            );
3289        }
3290
3291        // No clock: degrade, never guess. A window measured in spins would be
3292        // a tolerance nobody declared.
3293        let mut st = AgeState::default();
3294        assert!(check_age(&s, &mut st, None).is_none());
3295        assert!(check_age(&s, &mut st, None).is_none());
3296    }
3297
3298    #[test]
3299    fn peek_stamp_reads_le_time_and_rejects_unstamped() {
3300        // Encapsulation header (4B) + sec=100 nsec=5000 at offset 4.
3301        let mut raw = [0u8; 12];
3302        raw[4..8].copy_from_slice(&100i32.to_le_bytes());
3303        raw[8..12].copy_from_slice(&5_000u32.to_le_bytes());
3304        assert_eq!(peek_stamp_us(&raw, 4), Some(100_000_005));
3305        // Zero / negative sec = unstamped: no age sample.
3306        assert_eq!(peek_stamp_us(&[0u8; 12], 4), None);
3307        // Short buffer: no panic, no sample.
3308        assert_eq!(peek_stamp_us(&raw[..8], 4), None);
3309    }
3310
3311    #[test]
3312    fn slow_path_fires_latency_once_until_recovery() {
3313        static C3: PubMonitorCell = PubMonitorCell::new();
3314        let s = MonitorSpec {
3315            topic: "/cmd",
3316            fqn: "/ctrl/control/cmd",
3317            min_rate_hz_milli: 0,
3318            max_latency_ms: 10,
3319            route_trigger: "",
3320            route_max_latency_ms: 0,
3321            route_deadline_ms: 0,
3322            reaction_id: 0,
3323            mechanism: 0,
3324            cell: &C3,
3325        };
3326        let mut st = MonitorState::default();
3327        // 4 ms dispatch — within budget.
3328        C3.max_latency_us.store(4_000, Ordering::Relaxed);
3329        assert!(check_latency(&s, &mut st).is_none());
3330        assert_eq!(C3.max_latency_us.load(Ordering::Relaxed), 0, "drained");
3331        // 25 ms dispatch — fires.
3332        C3.max_latency_us.store(25_000, Ordering::Relaxed);
3333        let v = check_latency(&s, &mut st).expect("fires");
3334        assert_eq!(v.rule, "max-latency-runtime");
3335        assert_eq!(v.measured, 25);
3336        assert_eq!(v.declared, 10);
3337        // Still slow — suppressed; recovery resets.
3338        C3.max_latency_us.store(30_000, Ordering::Relaxed);
3339        assert!(check_latency(&s, &mut st).is_none());
3340        C3.max_latency_us.store(1_000, Ordering::Relaxed);
3341        assert!(check_latency(&s, &mut st).is_none());
3342        C3.max_latency_us.store(30_000, Ordering::Relaxed);
3343        assert!(check_latency(&s, &mut st).is_some());
3344    }
3345}
3346
3347/// Issue #514 — emit one violation to the log.
3348///
3349/// A log line is deliberately the floor rather than a `/diagnostics`
3350/// publication: it needs no publisher, no topic wiring, and no contract
3351/// on the reporting path itself, so it works on a bare RTOS image and
3352/// during boot. Publishing the same verdicts as `DiagnosticArray`
3353/// belongs on top of this, not instead of it.
3354///
3355/// Free function rather than an `Executor` method because every call
3356/// site sits inside a loop that already borrows the executor's spec
3357/// tables.
3358pub(crate) fn log_violation(v: &Violation) {
3359    // phase-560 W8 -- a level report names its level; every other line is
3360    // unchanged (log readers match the prefix).
3361    if v.level.is_empty() {
3362        nros_log::log_warn!(
3363            nros_log::get_logger("nros"),
3364            "contract violation: {} {} measured={} declared={}",
3365            v.rule,
3366            v.fqn,
3367            v.measured,
3368            v.declared
3369        );
3370    } else {
3371        nros_log::log_warn!(
3372            nros_log::get_logger("nros"),
3373            "contract violation: {} {} measured={} declared={} level={}",
3374            v.rule,
3375            v.fqn,
3376            v.measured,
3377            v.declared,
3378            v.level
3379        );
3380    }
3381}
3382
3383/// phase-474 I1 -- the drain-and-report hook's line: the issue-0514 line plus
3384/// the verdict's sequence number and the counters, so a reader who sees line
3385/// `#12` after `#9` knows two were missed, and `dropped` says whether the ring
3386/// lost any before this drain.
3387fn log_drained_violation(seq: u32, total: u32, dropped: u32, v: &Violation) {
3388    if v.level.is_empty() {
3389        nros_log::log_warn!(
3390            nros_log::get_logger("nros"),
3391            "contract violation #{}: {} {} measured={} declared={} (total={} dropped={})",
3392            seq,
3393            v.rule,
3394            v.fqn,
3395            v.measured,
3396            v.declared,
3397            total,
3398            dropped
3399        );
3400    } else {
3401        nros_log::log_warn!(
3402            nros_log::get_logger("nros"),
3403            "contract violation #{}: {} {} measured={} declared={} level={} (total={} dropped={})",
3404            seq,
3405            v.rule,
3406            v.fqn,
3407            v.measured,
3408            v.declared,
3409            v.level,
3410            total,
3411            dropped
3412        );
3413    }
3414}
3415
3416/// Issue #505 — periodic activations a timer dropped because its
3417/// executor was blocked past the period boundary.
3418///
3419/// This rule exists because `check_rate` cannot see an isolated stall:
3420/// it samples publish counts over a ~5 s window, so 20 missed
3421/// activations of a 100 Hz loop are a 0.4% rate deficit — under any
3422/// sane declared minimum, silence. (And under
3423/// [`TimerOverrunPolicy::CatchUp`](super::arena::TimerOverrunPolicy)
3424/// the replayed activations refill the window entirely, so the rate
3425/// rule reports a HEALTHY loop while the tier is stalling.) The
3426/// overrun counter is exact, needs no window, and does not depend on
3427/// clock resolution.
3428///
3429/// `overruns` is the timer's monotonic saturating counter;
3430/// `last_reported` is the value at the previous check, so the verdict
3431/// is on the delta. Returns a violation when more than `tolerated`
3432/// activations were dropped since the last check.
3433pub(crate) fn check_timer_overrun(
3434    overruns: u32,
3435    last_reported: &mut u32,
3436    tolerated: u32,
3437) -> Option<Violation> {
3438    let dropped = overruns.saturating_sub(*last_reported);
3439    *last_reported = overruns;
3440    if dropped <= tolerated {
3441        return None;
3442    }
3443    Some(Violation {
3444        rule: "timer-overrun-runtime",
3445        // Timer entries carry no name at this altitude; same stand-in
3446        // as `deadline-miss-runtime`.
3447        fqn: "timer",
3448        measured: dropped,
3449        declared: tolerated,
3450        level: "",
3451    })
3452}
3453
3454/// Issue #515 — report a spin wake that arrived so late the cadence it
3455/// claims cannot have been met.
3456///
3457/// Like `check_timer_overrun` and unlike the rate/age/latency rules, this
3458/// needs no baked spec table. The bound is the spin period ITSELF: the
3459/// caller passes it to `spin_once` as the pacing quantum, it is what
3460/// `system.toml` declares as `spin_period_us`, and a wake later than a full
3461/// period past its predecessor means an activation's worth of cadence was
3462/// lost. That is a contract failure for any declared period, so there is
3463/// nothing further to declare.
3464///
3465/// The tolerance is one whole period rather than zero, and deliberately so.
3466/// Sub-period lateness is ordinary scheduling noise -- on the measured FVP
3467/// lane the executor is late on a large fraction of wakes while still
3468/// holding its rate -- and a rule that fired on each one would report a
3469/// healthy system as broken thousands of times a second. What is NOT
3470/// ordinary is being a full period late, because by then the wake that
3471/// should have happened in between never did.
3472///
3473/// phase-474 I11 -- for a `spin_once(period)` loop with no declared cadence
3474/// the lateness is release minus scheduled release on the executor's release
3475/// grid (a dropped release counts its age when dropped), not entry-to-entry
3476/// minus the period; see `Executor::record_release_jitter`.
3477///
3478/// `max_jitter_us` is the executor's high-water since the last check and
3479/// `last_reported` the value at the previous one, so the verdict is on the
3480/// delta -- the same shape as the overrun counter, and for the same reason:
3481/// a maximum that has not moved is not a new fault.
3482pub(crate) fn check_release_jitter(
3483    max_jitter_us: u64,
3484    last_reported: &mut u64,
3485    period_us: u64,
3486) -> Option<Violation> {
3487    if period_us == 0 || max_jitter_us <= *last_reported {
3488        return None;
3489    }
3490    *last_reported = max_jitter_us;
3491    if max_jitter_us < period_us {
3492        return None;
3493    }
3494    Some(Violation {
3495        rule: "release-jitter-runtime",
3496        // Same stand-in as the timer and deadline rules: the spin loop is
3497        // not an endpoint and carries no fqn at this altitude.
3498        fqn: "spin",
3499        measured: max_jitter_us.min(u32::MAX as u64) as u32,
3500        declared: period_us.min(u32::MAX as u64) as u32,
3501        level: "",
3502    })
3503}
3504
3505/// Report a spin thread whose stack has come closer to its end than the
3506/// declared minimum.
3507///
3508/// Unlike every other rule here the bound CANNOT be derived from something
3509/// already declared, and that is worth stating rather than papering over.
3510/// `check_timer_overrun` and `check_release_jitter` both judge against a
3511/// period the caller already passes in; there is no equivalent for a stack.
3512/// The executor never sees `stack_bytes` -- it lives in the spawn attr and
3513/// goes no further -- and the total is not portably queryable either:
3514/// FreeRTOS exposes the high-water mark and not the size it was taken
3515/// against, so even a percentage cannot be computed. A minimum headroom is
3516/// therefore a real declaration, and `min_bytes == 0` means the caller has
3517/// not made one, which disables the rule.
3518///
3519/// Reports on the WORST case, not on each crossing: `worst_reported` holds
3520/// the lowest headroom already reported, so a stack hovering just under the
3521/// bound says so once and then only when it gets worse. The same delta
3522/// discipline as the overrun and jitter rules, inverted because for headroom
3523/// smaller is worse.
3524pub(crate) fn check_stack_headroom(
3525    unused_bytes: usize,
3526    min_bytes: usize,
3527    worst_reported: &mut usize,
3528) -> Option<Violation> {
3529    if min_bytes == 0 || unused_bytes >= min_bytes {
3530        return None;
3531    }
3532    // `usize::MAX` is the "nothing reported yet" sentinel: any real headroom
3533    // is below it, so the first breach always reports.
3534    if *worst_reported != usize::MAX && unused_bytes >= *worst_reported {
3535        return None;
3536    }
3537    *worst_reported = unused_bytes;
3538    Some(Violation {
3539        rule: "stack-headroom-runtime",
3540        // The spin thread is not an endpoint; same stand-in as the timer,
3541        // deadline and jitter rules.
3542        fqn: "stack",
3543        measured: unused_bytes.min(u32::MAX as usize) as u32,
3544        declared: min_bytes.min(u32::MAX as usize) as u32,
3545        level: "",
3546    })
3547}
3548
3549#[cfg(test)]
3550mod stack_headroom_rule_tests {
3551    use super::*;
3552
3553    /// No declared minimum means no claim to breach.
3554    #[test]
3555    fn a_zero_minimum_disables_the_rule() {
3556        let mut worst = usize::MAX;
3557        assert!(check_stack_headroom(8, 0, &mut worst).is_none());
3558    }
3559
3560    #[test]
3561    fn headroom_at_the_bound_is_not_a_breach() {
3562        let mut worst = usize::MAX;
3563        assert!(check_stack_headroom(1024, 1024, &mut worst).is_none());
3564        assert!(check_stack_headroom(2048, 1024, &mut worst).is_none());
3565    }
3566
3567    #[test]
3568    fn reports_the_first_breach_with_both_numbers() {
3569        let mut worst = usize::MAX;
3570        let v = check_stack_headroom(512, 1024, &mut worst).expect("under the bound reports");
3571        assert_eq!(v.rule, "stack-headroom-runtime");
3572        assert_eq!(v.measured, 512);
3573        assert_eq!(v.declared, 1024);
3574    }
3575
3576    /// Smaller is worse for headroom, so the delta runs the other way.
3577    #[test]
3578    fn only_a_new_low_is_a_new_fault() {
3579        let mut worst = usize::MAX;
3580        assert!(check_stack_headroom(512, 1024, &mut worst).is_some());
3581        assert!(check_stack_headroom(512, 1024, &mut worst).is_none());
3582        assert!(check_stack_headroom(600, 1024, &mut worst).is_none());
3583        let v = check_stack_headroom(100, 1024, &mut worst).expect("a new low reports");
3584        assert_eq!(v.measured, 100);
3585    }
3586}
3587
3588#[cfg(test)]
3589mod publish_stamp_tests {
3590    use super::*;
3591
3592    /// CDR: 4-byte encapsulation header, then `Time { i32 sec; u32 nanosec }`
3593    /// little-endian, so `sec` sits at byte 4 — the layout `STAMP_OFFSET`
3594    /// encodes.
3595    fn cdr_with_stamp(sec: i32, nanosec: u32) -> [u8; 12] {
3596        let mut b = [0u8; 12];
3597        b[4..8].copy_from_slice(&sec.to_le_bytes());
3598        b[8..12].copy_from_slice(&nanosec.to_le_bytes());
3599        b
3600    }
3601
3602    #[test]
3603    fn records_the_age_of_what_was_published() {
3604        let cell = PubMonitorCell::new();
3605        let raw = cdr_with_stamp(10, 0); // stamped at 10_000_000 us
3606        observe_publish_stamp(&cell, &raw, 4, 10_500_000);
3607        assert_eq!(
3608            cell.last_publish_stamp_age_us.load(Ordering::Relaxed),
3609            500_000,
3610            "published data was half a second old"
3611        );
3612    }
3613
3614    /// The signature of a node that RE-STAMPED: it publishes data whose
3615    /// stamp is now, so downstream age is single-hop, not end-to-end.
3616    #[test]
3617    fn a_restamping_node_shows_near_zero_age() {
3618        let cell = PubMonitorCell::new();
3619        let raw = cdr_with_stamp(10, 0);
3620        observe_publish_stamp(&cell, &raw, 4, 10_000_000);
3621        assert_eq!(cell.last_publish_stamp_age_us.load(Ordering::Relaxed), 0);
3622    }
3623
3624    /// A state, not a window maximum: one stale message at startup must not
3625    /// pin the value for the life of the process.
3626    #[test]
3627    fn the_latest_publish_replaces_the_previous() {
3628        let cell = PubMonitorCell::new();
3629        observe_publish_stamp(&cell, &cdr_with_stamp(10, 0), 4, 12_000_000);
3630        assert_eq!(
3631            cell.last_publish_stamp_age_us.load(Ordering::Relaxed),
3632            2_000_000
3633        );
3634        observe_publish_stamp(&cell, &cdr_with_stamp(20, 0), 4, 20_100_000);
3635        assert_eq!(
3636            cell.last_publish_stamp_age_us.load(Ordering::Relaxed),
3637            100_000,
3638            "a fresh publish replaces the old age rather than maxing with it"
3639        );
3640    }
3641
3642    /// An unset stamp is not an age of `now`. `peek_stamp_us` rejects
3643    /// `sec <= 0`, so a zeroed header records nothing at all.
3644    #[test]
3645    fn an_unstamped_message_records_nothing() {
3646        let cell = PubMonitorCell::new();
3647        observe_publish_stamp(&cell, &cdr_with_stamp(0, 0), 4, 5_000_000);
3648        assert_eq!(
3649            cell.last_publish_stamp_age_us.load(Ordering::Relaxed),
3650            0,
3651            "no stamp means no observation, not an enormous age"
3652        );
3653    }
3654}
3655
3656/// Per-SchedContext liveness accounting, one per SC slot.
3657///
3658/// `Default` is DERIVED, not hand-written: every field's default is its type's
3659/// own (`false`, `0`), so a manual impl restates four of them and is one edit
3660/// away from disagreeing with the struct — `clippy::derivable_impls` is a
3661/// `-D warnings` error in the embedded lane, which is where this was caught.
3662#[derive(Debug, Clone, Copy, Default)]
3663pub(crate) struct AliveState {
3664    pub opened: bool,
3665    pub window_start_us: u64,
3666    pub count_at_window_start: u32,
3667    /// Report-once-until-recovery, matching the rate rule.
3668    pub violated_last_window: bool,
3669}
3670
3671/// One SchedContext's alive-supervision record: the counter the dispatch
3672/// path bumps and the window state the monitor tick reads.
3673///
3674/// A region of the carved backing (`storage::carve`), one per SC the
3675/// executor was sized for — NOT an inline `[_; MAX_SC]` in the header.
3676/// `MAX_SC` is a sizing knob, so an inline table grows the `Executor` value
3677/// with it, which is the regression issue 0961 exists to prevent.
3678#[derive(Debug, Clone, Copy, Default)]
3679pub(crate) struct AliveSlot {
3680    pub dispatches: u32,
3681    pub state: AliveState,
3682}
3683
3684/// Report a SchedContext that has not dispatched AT ALL over a full window
3685/// while declaring a period that says it should have.
3686///
3687/// AUTOSAR's Watchdog Manager separates ALIVE supervision -- did it run at
3688/// all, at roughly the right rate -- from DEADLINE supervision, did it finish
3689/// in time. Every rule here is the second kind or a variant of it: they fire
3690/// when something happens and is wrong. Nothing fires when a callback stops
3691/// happening altogether.
3692///
3693/// `rate-hierarchy-runtime` does not cover it. That rule counts PUBLISHES on
3694/// a contracted publisher, so a timer callback that silently stops firing
3695/// while its topic is published from elsewhere -- another tier, a bridge, a
3696/// republisher -- leaves it satisfied. The gap is a callback, not an
3697/// endpoint.
3698///
3699/// The bound needs no declaration: `period_us` is already on the SC, and a
3700/// context claiming a period that produced no activation in a window many
3701/// times longer than it is a contract failure for any period. `period_us ==
3702/// 0` declares no cadence, so nothing is judged.
3703///
3704/// ZERO, not a fraction. A throttled-but-alive context is a different fault
3705/// with different evidence -- `SporadicState` already counts window skips and
3706/// dispatches for exactly that -- and picking a percentage here would invent
3707/// a tolerance nobody declared. Zero activations against a declared period is
3708/// unambiguous.
3709pub(crate) fn check_alive(
3710    period_us: u64,
3711    dispatches: u32,
3712    state: &mut AliveState,
3713    now_us: u64,
3714) -> Option<Violation> {
3715    if period_us == 0 {
3716        return None;
3717    }
3718    if !state.opened {
3719        state.opened = true;
3720        state.window_start_us = now_us;
3721        state.count_at_window_start = dispatches;
3722        return None;
3723    }
3724    let window_us = now_us.saturating_sub(state.window_start_us);
3725    if window_us < RATE_CHECK_INTERVAL_US {
3726        return None;
3727    }
3728    let fired = dispatches.wrapping_sub(state.count_at_window_start);
3729    state.window_start_us = now_us;
3730    state.count_at_window_start = dispatches;
3731
3732    // Only judge a window long enough to have contained an activation. A
3733    // period longer than the check interval is not late merely for not having
3734    // fired yet.
3735    if window_us < period_us {
3736        return None;
3737    }
3738    if fired > 0 {
3739        state.violated_last_window = false;
3740        return None;
3741    }
3742    if state.violated_last_window {
3743        return None; // still silent — already reported
3744    }
3745    state.violated_last_window = true;
3746    Some(Violation {
3747        rule: "alive-supervision-runtime",
3748        // SCs carry no name at this altitude; same stand-in as the deadline
3749        // rule, which reports against the SC too.
3750        fqn: "sched-context",
3751        measured: 0,
3752        declared: (window_us / period_us).min(u32::MAX as u64) as u32,
3753        level: "",
3754    })
3755}
3756
3757#[cfg(test)]
3758mod alive_supervision_tests {
3759    use super::*;
3760
3761    const W: u64 = RATE_CHECK_INTERVAL_US;
3762
3763    #[test]
3764    fn a_zero_period_declares_no_cadence() {
3765        let mut st = AliveState::default();
3766        assert!(check_alive(0, 0, &mut st, 0).is_none());
3767        assert!(check_alive(0, 0, &mut st, W * 4).is_none());
3768    }
3769
3770    /// The first observation opens the window; there is no verdict yet.
3771    #[test]
3772    fn the_first_window_only_opens() {
3773        let mut st = AliveState::default();
3774        assert!(check_alive(1_000, 0, &mut st, 0).is_none());
3775        assert!(st.opened);
3776    }
3777
3778    #[test]
3779    fn silence_across_a_full_window_reports() {
3780        let mut st = AliveState::default();
3781        check_alive(1_000, 0, &mut st, 0);
3782        let v = check_alive(1_000, 0, &mut st, W).expect("no dispatch in a full window");
3783        assert_eq!(v.rule, "alive-supervision-runtime");
3784        assert_eq!(v.measured, 0);
3785        assert_eq!(v.declared, (W / 1_000) as u32);
3786    }
3787
3788    /// Any activation at all clears it -- this rule asks whether the context
3789    /// is alive, not whether it is keeping up.
3790    #[test]
3791    fn a_single_dispatch_is_enough() {
3792        let mut st = AliveState::default();
3793        check_alive(1_000, 0, &mut st, 0);
3794        assert!(check_alive(1_000, 1, &mut st, W).is_none());
3795    }
3796
3797    /// Report once, then stay quiet until it recovers, like the rate rule.
3798    #[test]
3799    fn continued_silence_is_not_a_new_fault() {
3800        let mut st = AliveState::default();
3801        check_alive(1_000, 0, &mut st, 0);
3802        assert!(check_alive(1_000, 0, &mut st, W).is_some());
3803        assert!(check_alive(1_000, 0, &mut st, W * 2).is_none());
3804        // Recovery, then silence again, reports afresh.
3805        assert!(check_alive(1_000, 5, &mut st, W * 3).is_none());
3806        assert!(check_alive(1_000, 5, &mut st, W * 4).is_some());
3807    }
3808
3809    /// A period longer than the window has not had its chance yet.
3810    #[test]
3811    fn a_period_longer_than_the_window_is_not_judged() {
3812        let mut st = AliveState::default();
3813        check_alive(W * 10, 0, &mut st, 0);
3814        assert!(check_alive(W * 10, 0, &mut st, W).is_none());
3815    }
3816}
3817
3818#[cfg(test)]
3819mod release_jitter_rule_tests {
3820    use super::*;
3821
3822    /// Sub-period lateness is noise, not a violation -- otherwise a
3823    /// healthy-but-jittery loop reports thousands of faults a second.
3824    #[test]
3825    fn tolerates_lateness_within_one_period() {
3826        let mut last = 0;
3827        assert!(check_release_jitter(4_000, &mut last, 5_000).is_none());
3828        assert_eq!(last, 4_000, "still recorded, so the next delta is honest");
3829    }
3830
3831    /// A full period late means the wake that belonged in between never
3832    /// happened.
3833    #[test]
3834    fn reports_a_wake_a_whole_period_late() {
3835        let mut last = 0;
3836        let v = check_release_jitter(5_000, &mut last, 5_000).expect("one period late reports");
3837        assert_eq!(v.rule, "release-jitter-runtime");
3838        assert_eq!(v.measured, 5_000);
3839        assert_eq!(v.declared, 5_000);
3840    }
3841
3842    /// The verdict is on the DELTA. A high-water that has not moved is the
3843    /// same fault already reported, not a new one.
3844    #[test]
3845    fn an_unchanged_maximum_is_not_a_new_fault() {
3846        let mut last = 0;
3847        assert!(check_release_jitter(9_000, &mut last, 5_000).is_some());
3848        assert!(check_release_jitter(9_000, &mut last, 5_000).is_none());
3849        assert!(check_release_jitter(12_000, &mut last, 5_000).is_some());
3850    }
3851
3852    /// No declared period means no cadence to be late for.
3853    #[test]
3854    fn a_zero_period_declares_nothing() {
3855        let mut last = 0;
3856        assert!(check_release_jitter(1_000_000, &mut last, 0).is_none());
3857    }
3858}
3859
3860#[cfg(test)]
3861mod timer_overrun_rule_tests {
3862    use super::*;
3863
3864    #[test]
3865    fn reports_the_delta_not_the_total() {
3866        let mut last = 0;
3867        let v = check_timer_overrun(19, &mut last, 0).expect("first drop reports");
3868        assert_eq!(v.rule, "timer-overrun-runtime");
3869        assert_eq!(v.measured, 19);
3870        // Same total on the next check is not a new fault.
3871        assert!(check_timer_overrun(19, &mut last, 0).is_none());
3872        // Only the newly dropped activations are reported.
3873        assert_eq!(check_timer_overrun(25, &mut last, 0).unwrap().measured, 6);
3874    }
3875
3876    #[test]
3877    fn a_clean_timer_never_reports() {
3878        let mut last = 0;
3879        for _ in 0..10 {
3880            assert!(check_timer_overrun(0, &mut last, 0).is_none());
3881        }
3882    }
3883
3884    #[test]
3885    fn tolerance_suppresses_small_drops() {
3886        let mut last = 0;
3887        assert!(check_timer_overrun(2, &mut last, 2).is_none());
3888        assert_eq!(check_timer_overrun(6, &mut last, 2).unwrap().measured, 4);
3889    }
3890}
3891
3892// phase-436 E4 — when the stack-headroom query is due. The decision is pure so
3893// the three cases are pinned without a clock or a port.
3894#[cfg(test)]
3895mod stack_headroom_throttle_tests {
3896    use super::*;
3897
3898    #[test]
3899    fn the_first_check_is_immediate_with_or_without_a_clock() {
3900        assert!(stack_headroom_check_due(Some(5), None, 0));
3901        assert!(stack_headroom_check_due(None, None, 0));
3902    }
3903
3904    #[test]
3905    fn a_clocked_check_waits_one_full_interval() {
3906        let i = STACK_HEADROOM_CHECK_INTERVAL_US;
3907        assert!(!stack_headroom_check_due(
3908            Some(1_000 + i - 1),
3909            Some(1_000),
3910            0
3911        ));
3912        assert!(stack_headroom_check_due(Some(1_000 + i), Some(1_000), 0));
3913    }
3914
3915    #[test]
3916    fn a_clockless_build_checks_once_per_stride_of_spins() {
3917        let s = STACK_HEADROOM_CHECK_SPIN_STRIDE;
3918        assert!(!stack_headroom_check_due(None, Some(0), s - 1));
3919        assert!(stack_headroom_check_due(None, Some(0), s));
3920    }
3921}
3922
3923/// phase-474 I1 -- the wire vocabulary and the SWD record.
3924#[cfg(test)]
3925mod ring_record_tests {
3926    use super::*;
3927
3928    fn v(rule: &'static str, fqn: &'static str, measured: u32) -> Violation {
3929        Violation {
3930            rule,
3931            fqn,
3932            measured,
3933            declared: 10,
3934            level: "",
3935        }
3936    }
3937
3938    #[test]
3939    fn every_rule_the_executor_reports_has_a_stable_code() {
3940        // The order is the wire format: a capture or a RAM dump decodes by it.
3941        assert_eq!(rule_code("rate-hierarchy-runtime"), 1);
3942        assert_eq!(rule_code("max-latency-runtime"), 3);
3943        assert_eq!(rule_code("release-jitter-runtime"), 9);
3944        assert_eq!(rule_code("no-such-rule"), 0);
3945        for (i, r) in RULE_IDS.iter().enumerate() {
3946            assert_eq!(rule_name(rule_code(r)), Some(*r), "code {}", i + 1);
3947        }
3948        assert_eq!(rule_name(0), None);
3949        assert_eq!(rule_name(RULE_IDS.len() as u32 + 1), None);
3950    }
3951
3952    #[test]
3953    fn fqn_hash_is_fnv1a_32() {
3954        // Reference values of 32-bit FNV-1a, so a Python decoder can match.
3955        assert_eq!(fqn_hash(""), 0x811c_9dc5);
3956        assert_eq!(fqn_hash("a"), 0xe40c_292c);
3957        assert_eq!(fqn_hash("foobar"), 0xbf9c_f968);
3958    }
3959
3960    #[test]
3961    fn a_violation_is_four_marker_events() {
3962        let w = violation_marker_words(5, &v("max-latency-runtime", "/n/out", 25));
3963        assert_eq!(w[0], (MARKER_VIOLATION, (5 << 8) | 3));
3964        assert_eq!(w[1], (MARKER_VIOLATION_FQN, fqn_hash("/n/out")));
3965        assert_eq!(w[2], (MARKER_VIOLATION_MEASURED, 25));
3966        assert_eq!(w[3], (MARKER_VIOLATION_DECLARED, 10));
3967        // The sequence number keeps its low 24 bits; the rule its low 8.
3968        let w = violation_marker_words(0x0100_0007, &v("silence-runtime", "/x", 0));
3969        assert_eq!(w[0].1, (7 << 8) | 7);
3970    }
3971
3972    #[test]
3973    fn the_record_keeps_the_latest_and_counts_what_it_overwrote() {
3974        let r: ViolationRecord<3> = ViolationRecord::new();
3975        assert_eq!(r.magic.load(Ordering::Relaxed), RECORD_MAGIC);
3976        assert_eq!(r.capacity.load(Ordering::Relaxed), 3);
3977        for m in 1..=5 {
3978            assert_eq!(r.store(&v("timer-overrun-runtime", "timer", m)), m);
3979        }
3980        assert_eq!(r.total.load(Ordering::Relaxed), 5);
3981        assert_eq!(r.dropped.load(Ordering::Relaxed), 2);
3982        assert_eq!(r.head.load(Ordering::Relaxed), 5 % 3);
3983        let mut seen = std::vec::Vec::new();
3984        r.newest_first(|seq, rule, fqn, measured, declared| {
3985            assert_eq!(rule, rule_code("timer-overrun-runtime"));
3986            assert_eq!(fqn, fqn_hash("timer"));
3987            assert_eq!(declared, 10);
3988            seen.push((seq, measured));
3989        });
3990        assert_eq!(seen, [(5, 5), (4, 4), (3, 3)], "newest first, oldest gone");
3991    }
3992
3993    /// The layout a debugger decodes: `u32` words only, header then slots, the
3994    /// same size on every target. `scripts/read-violation-record.py` reads it
3995    /// by these numbers.
3996    #[test]
3997    fn the_record_is_packed_u32_words() {
3998        use core::mem::{offset_of, size_of};
3999        assert_eq!(size_of::<ViolationSlot>(), RECORD_SLOT_WORDS as usize * 4);
4000        assert_eq!(
4001            offset_of!(ViolationRecord<4>, slots),
4002            RECORD_HEADER_WORDS as usize * 4
4003        );
4004        assert_eq!(
4005            size_of::<ViolationRecord<4>>(),
4006            (RECORD_HEADER_WORDS + 4 * RECORD_SLOT_WORDS) as usize * 4
4007        );
4008        assert_eq!(offset_of!(ViolationRecord<4>, total), 16);
4009        assert_eq!(offset_of!(ViolationRecord<4>, head), 20);
4010        assert_eq!(offset_of!(ViolationRecord<4>, dropped), 24);
4011        assert_eq!(offset_of!(ViolationRecord<4>, suppressed_before_arm), 28);
4012        assert_eq!(offset_of!(ViolationRecord<4>, armed), 32);
4013        assert_eq!(offset_of!(ViolationSlot, fqn_addr), 20);
4014    }
4015}
4016
4017/// phase10-B3 -- the route rule's pure half: binding, the earliest unanswered
4018/// take, judging only on a publish of the output, report once until clean.
4019#[cfg(test)]
4020mod route_tests {
4021    use super::*;
4022
4023    static CELL: PubMonitorCell = PubMonitorCell::new();
4024    static OTHER: PubMonitorCell = PubMonitorCell::new();
4025    static TABLE: [MonitorSpec; 2] = [
4026        MonitorSpec {
4027            topic: "/out",
4028            fqn: "/n/out",
4029            min_rate_hz_milli: 0,
4030            max_latency_ms: 0,
4031            route_trigger: "/in",
4032            route_max_latency_ms: 149,
4033            route_deadline_ms: 0,
4034            reaction_id: 0,
4035            mechanism: 0,
4036            cell: &CELL,
4037        },
4038        MonitorSpec {
4039            topic: "/other",
4040            fqn: "/n/other",
4041            min_rate_hz_milli: 0,
4042            max_latency_ms: 0,
4043            route_trigger: "",
4044            route_max_latency_ms: 0,
4045            route_deadline_ms: 0,
4046            reaction_id: 0,
4047            mechanism: 0,
4048            cell: &OTHER,
4049        },
4050    ];
4051
4052    fn snapshot() -> [u32; MAX_MONITORS] {
4053        let mut c = [0u32; MAX_MONITORS];
4054        for (k, s) in TABLE.iter().enumerate() {
4055            c[k] = s.cell.count.load(Ordering::Relaxed);
4056        }
4057        c
4058    }
4059
4060    fn judge(end_us: u64, before: &[u32; MAX_MONITORS]) -> Vec<(u32, u32)> {
4061        let mut out = Vec::new();
4062        route_judge(&TABLE, before, end_us, |_, v, record, react| {
4063            assert!(record && !react, "an unsupervised route only records");
4064            assert_eq!(v.rule, "route-latency-runtime");
4065            assert_eq!(v.fqn, "/n/out");
4066            out.push((v.measured, v.declared));
4067        });
4068        out
4069    }
4070
4071    extern crate alloc;
4072    use alloc::vec::Vec;
4073
4074    #[test]
4075    fn route_rule() {
4076        assert!(route_active(&TABLE));
4077        route_bind(&TABLE, "/elsewhere", 1);
4078        assert_eq!(
4079            CELL.route.load(Ordering::Relaxed),
4080            0,
4081            "wrong topic binds nothing"
4082        );
4083        route_bind(&TABLE, "/in", 3);
4084        route_bind(&TABLE, "/in", 5);
4085        assert_eq!(
4086            CELL.route.load(Ordering::Relaxed),
4087            4,
4088            "first subscription keeps it"
4089        );
4090        assert_eq!(OTHER.route.load(Ordering::Relaxed), 0);
4091
4092        // A take on another slot starts nothing; two takes keep the earliest.
4093        route_take(&TABLE, 5, 1_000);
4094        assert_eq!(CELL.route.load(Ordering::Relaxed) & ROUTE_PENDING, 0);
4095        route_take(&TABLE, 3, 10_000);
4096        route_take(&TABLE, 3, 90_000);
4097        // A dispatch that publishes nothing judges nothing.
4098        let b = snapshot();
4099        assert!(judge(400_000, &b).is_empty());
4100        assert_ne!(CELL.route.load(Ordering::Relaxed) & ROUTE_PENDING, 0);
4101        // The output published: 10 ms -> 160 ms is 150 ms, over 149.
4102        let b = snapshot();
4103        CELL.count.fetch_add(1, Ordering::Relaxed);
4104        assert_eq!(judge(160_000, &b), [(150, 149)]);
4105        assert_eq!(
4106            CELL.route.load(Ordering::Relaxed) & ROUTE_PENDING,
4107            0,
4108            "answered"
4109        );
4110        // Over again: reported once until a route is within the budget.
4111        route_take(&TABLE, 3, 200_000);
4112        let b = snapshot();
4113        CELL.count.fetch_add(1, Ordering::Relaxed);
4114        assert!(
4115            judge(400_000, &b).is_empty(),
4116            "still over: not reported twice"
4117        );
4118        route_take(&TABLE, 3, 500_000);
4119        let b = snapshot();
4120        CELL.count.fetch_add(1, Ordering::Relaxed);
4121        assert!(judge(600_000, &b).is_empty(), "100 ms: within");
4122        assert_eq!(CELL.route.load(Ordering::Relaxed) & ROUTE_VIOLATED, 0);
4123        route_take(&TABLE, 3, 700_000);
4124        let b = snapshot();
4125        CELL.count.fetch_add(1, Ordering::Relaxed);
4126        assert_eq!(
4127            judge(1_000_000, &b),
4128            [(300, 149)],
4129            "over after clean: reported"
4130        );
4131        // A publish with no waiting take is not a route.
4132        let b = snapshot();
4133        CELL.count.fetch_add(1, Ordering::Relaxed);
4134        assert!(judge(9_000_000, &b).is_empty());
4135        // Arming drops a waiting take and the report-once state, keeps the
4136        // binding; a release unbinds.
4137        route_take(&TABLE, 3, 9_100_000);
4138        route_reset(&TABLE);
4139        assert_eq!(CELL.route.load(Ordering::Relaxed), 4);
4140        route_unbind(&TABLE, 3);
4141        assert_eq!(CELL.route.load(Ordering::Relaxed), 0);
4142        // Wrapping: the stamp is the clock's low 32 bits.
4143        route_bind(&TABLE, "/in", 3);
4144        route_take(&TABLE, 3, u32::MAX as u64 - 9_999);
4145        let b = snapshot();
4146        CELL.count.fetch_add(1, Ordering::Relaxed);
4147        assert!(
4148            judge(u32::MAX as u64 + 90_001, &b).is_empty(),
4149            "100 ms across the wrap"
4150        );
4151    }
4152
4153    #[test]
4154    fn route_rule_code_is_appended() {
4155        assert_eq!(rule_code("route-latency-runtime"), 10);
4156        assert_eq!(rule_code("release-jitter-runtime"), 9);
4157        assert_eq!(rule_code("route-deadline-runtime"), 11);
4158    }
4159
4160    static DL_CELL: PubMonitorCell = PubMonitorCell::new();
4161    static DL_PLAIN: PubMonitorCell = PubMonitorCell::new();
4162    static DL_TABLE: [MonitorSpec; 2] = [
4163        // A route with the budget only: judged on completion, never overdue.
4164        MonitorSpec {
4165            topic: "/plain",
4166            fqn: "/n/plain",
4167            min_rate_hz_milli: 0,
4168            max_latency_ms: 0,
4169            route_trigger: "/in",
4170            route_max_latency_ms: 149,
4171            route_deadline_ms: 0,
4172            reaction_id: 0,
4173            mechanism: 0,
4174            cell: &DL_PLAIN,
4175        },
4176        // phase-503 -- the same route, supervised.
4177        MonitorSpec {
4178            topic: "/out",
4179            fqn: "/n/out",
4180            min_rate_hz_milli: 0,
4181            max_latency_ms: 0,
4182            route_trigger: "/in",
4183            route_max_latency_ms: 149,
4184            route_deadline_ms: 149,
4185            reaction_id: 3,
4186            mechanism: MECHANISM_TIMER,
4187            cell: &DL_CELL,
4188        },
4189    ];
4190
4191    fn overdue(now_us: u64) -> Vec<(usize, u32, u32, bool)> {
4192        let mut out = Vec::new();
4193        route_overdue(&DL_TABLE, now_us, |row, v, first| {
4194            assert_eq!(v.rule, "route-deadline-runtime");
4195            assert_eq!(v.fqn, "/n/out");
4196            out.push((row, v.measured, v.declared, first));
4197        });
4198        out
4199    }
4200
4201    /// phase-503 -- an output that never comes is judged at its deadline, not
4202    /// never: the wake source names the due time, the check at due reports it
4203    /// once with the row the hook is called for, and the next take starts a
4204    /// fresh route.
4205    #[test]
4206    fn route_deadline_rule() {
4207        assert!(route_deadline_active(&DL_TABLE));
4208        assert!(
4209            !route_deadline_active(&TABLE),
4210            "phase10-B3 rows stay unsupervised"
4211        );
4212        assert_eq!(route_next_due_us(&DL_TABLE, 0), None, "nothing pending");
4213        route_bind(&DL_TABLE, "/in", 2);
4214        route_take(&DL_TABLE, 2, 1_000_000);
4215        // The wake source: 149 ms after the take, then counting down.
4216        assert_eq!(route_next_due_us(&DL_TABLE, 1_000_000), Some(149_000));
4217        assert_eq!(route_next_due_us(&DL_TABLE, 1_100_000), Some(49_000));
4218        // One microsecond early: not overdue, still pending.
4219        assert!(overdue(1_148_999).is_empty());
4220        assert_ne!(DL_CELL.route.load(Ordering::Relaxed) & ROUTE_PENDING, 0);
4221        assert_eq!(route_next_due_us(&DL_TABLE, 1_148_999), Some(1));
4222        // At the deadline plus one 1 ms tick: reported for row 1, first.
4223        assert_eq!(overdue(1_150_000), [(1, 150, 149, true)]);
4224        let w = DL_CELL.route.load(Ordering::Relaxed);
4225        assert_eq!(w & ROUTE_PENDING, 0, "the take is dropped");
4226        assert_ne!(w & ROUTE_VIOLATED, 0);
4227        // The unsupervised row keeps its take for the completion verdict.
4228        assert_ne!(DL_PLAIN.route.load(Ordering::Relaxed) & ROUTE_PENDING, 0);
4229        assert_eq!(route_next_due_us(&DL_TABLE, 1_150_000), None);
4230        assert!(overdue(5_000_000).is_empty(), "judged once per take");
4231        // Still never answered: the next take misses too. The reaction is
4232        // requested again, the violation is not recorded twice.
4233        route_take(&DL_TABLE, 2, 6_000_000);
4234        assert_eq!(overdue(6_200_000), [(1, 200, 149, false)]);
4235        // A take answered in time clears the mark (route_judge's recovery).
4236        route_take(&DL_TABLE, 2, 7_000_000);
4237        let mut before = [0u32; MAX_MONITORS];
4238        for (k, s) in DL_TABLE.iter().enumerate() {
4239            before[k] = s.cell.count.load(Ordering::Relaxed);
4240        }
4241        DL_CELL.count.fetch_add(1, Ordering::Relaxed);
4242        let mut judged = Vec::new();
4243        route_judge(&DL_TABLE, &before, 7_010_000, |_, v, _, _| {
4244            judged.push(v.measured)
4245        });
4246        assert!(judged.is_empty(), "10 ms: within");
4247        assert_eq!(DL_CELL.route.load(Ordering::Relaxed) & ROUTE_VIOLATED, 0);
4248        // Over again after recovery: first again.
4249        route_take(&DL_TABLE, 2, 8_000_000);
4250        assert_eq!(overdue(8_149_000), [(1, 149, 149, true)]);
4251        // Across the clock's 32-bit wrap.
4252        route_take(&DL_TABLE, 2, u32::MAX as u64 - 9_999);
4253        assert_eq!(
4254            route_next_due_us(&DL_TABLE, u32::MAX as u64 + 1),
4255            Some(139_000)
4256        );
4257        assert!(overdue(u32::MAX as u64 + 139_000).is_empty());
4258        assert_eq!(overdue(u32::MAX as u64 + 139_001).len(), 1);
4259    }
4260
4261    static LC_CELL: PubMonitorCell = PubMonitorCell::new();
4262    static LC_TABLE: [MonitorSpec; 1] = [MonitorSpec {
4263        topic: "/out",
4264        fqn: "/n/late",
4265        min_rate_hz_milli: 0,
4266        max_latency_ms: 0,
4267        route_trigger: "/in",
4268        route_max_latency_ms: 149,
4269        route_deadline_ms: 149,
4270        reaction_id: 5,
4271        mechanism: MECHANISM_EXECUTOR,
4272        cell: &LC_CELL,
4273    }];
4274
4275    /// `(row, rule, measured, declared, record, react)` of one `route_judge`
4276    /// call after the output was published once.
4277    #[allow(clippy::type_complexity)]
4278    fn complete(end_us: u64) -> Vec<(usize, &'static str, u32, u32, bool, bool)> {
4279        let mut before = [0u32; MAX_MONITORS];
4280        before[0] = LC_CELL.count.load(Ordering::Relaxed);
4281        LC_CELL.count.fetch_add(1, Ordering::Relaxed);
4282        let mut out = Vec::new();
4283        route_judge(&LC_TABLE, &before, end_us, |row, v, record, react| {
4284            assert_eq!(v.fqn, "/n/late");
4285            out.push((row, v.rule, v.measured, v.declared, record, react));
4286        });
4287        out
4288    }
4289
4290    fn lc_overdue(now_us: u64) -> usize {
4291        let mut n = 0;
4292        route_overdue(&LC_TABLE, now_us, |_, _, _| n += 1);
4293        n
4294    }
4295
4296    /// phase-503 -- a supervised route whose one long callback publishes the
4297    /// output after the deadline, before the executor's overdue check could
4298    /// run: the completion reports the deadline miss and requests the
4299    /// reaction, once per take; a deadline already caught by the check is not
4300    /// reported again at completion; an on-time completion reports nothing.
4301    #[test]
4302    fn a_late_completion_is_a_deadline_miss_once() {
4303        route_bind(&LC_TABLE, "/in", 0);
4304        // Late completion, no overdue check in between (the callback held the
4305        // spin thread): the latency verdict, plus one deadline verdict that
4306        // asks for the reaction.
4307        route_take(&LC_TABLE, 0, 1_000_000);
4308        assert_eq!(
4309            complete(1_327_000),
4310            [
4311                (0, "route-latency-runtime", 327, 149, true, false),
4312                (0, "route-deadline-runtime", 327, 149, true, true),
4313            ]
4314        );
4315        assert_eq!(LC_CELL.route.load(Ordering::Relaxed) & ROUTE_PENDING, 0);
4316        assert_ne!(LC_CELL.route.load(Ordering::Relaxed) & ROUTE_VIOLATED, 0);
4317        // The take was answered: the overdue check has nothing left.
4318        assert_eq!(lc_overdue(1_400_000), 0, "no second verdict");
4319        // Late again while still marked: the reaction again, no record.
4320        route_take(&LC_TABLE, 0, 2_000_000);
4321        assert_eq!(
4322            complete(2_200_000),
4323            [(0, "route-deadline-runtime", 200, 149, false, true)]
4324        );
4325        // On time: nothing, and the mark clears.
4326        route_take(&LC_TABLE, 0, 3_000_000);
4327        assert!(complete(3_100_000).is_empty());
4328        assert_eq!(LC_CELL.route.load(Ordering::Relaxed) & ROUTE_VIOLATED, 0);
4329        // The deadline already fired (the check ran in time, or the timer
4330        // mechanism's): the late output that follows judges nothing.
4331        route_take(&LC_TABLE, 0, 4_000_000);
4332        assert_eq!(lc_overdue(4_150_000), 1);
4333        assert!(
4334            complete(4_327_000).is_empty(),
4335            "no second call at completion"
4336        );
4337        // Exactly at the deadline counts as overdue, as in route_overdue;
4338        // within the budget and before it does not.
4339        route_take(&LC_TABLE, 0, 5_000_000);
4340        let at = complete(5_149_000);
4341        assert_eq!(at.len(), 1);
4342        assert_eq!(at[0].1, "route-deadline-runtime");
4343        route_take(&LC_TABLE, 0, 6_000_000);
4344        assert!(complete(6_148_999).is_empty());
4345    }
4346}
4347
4348/// phase-462 W5b -- the three admission outcomes, decided from the backend's
4349/// own mask, and the arrival evidence an armed row reads.
4350#[cfg(test)]
4351mod unserved_deadline_tests {
4352    use super::*;
4353    use nros_rmw::{QoSPolicyMask, QoSProfile};
4354
4355    static CELL: SubMonitorCell = SubMonitorCell::new();
4356    static ROWS: [AgeMonitorSpec; 1] = [AgeMonitorSpec {
4357        topic: "/scan",
4358        fqn: "/h/scan",
4359        max_age_ms: 0,
4360        deadline_ms: 50,
4361        cell: &CELL,
4362    }];
4363    const ALL: QoSPolicyMask = QoSPolicyMask(u32::MAX);
4364    const NO_DEADLINE: QoSPolicyMask = QoSPolicyMask(!QoSPolicyMask::DEADLINE.0);
4365
4366    fn with_deadline(ms: u32) -> QoSProfile {
4367        QoSProfile {
4368            deadline_ms: ms,
4369            ..QoSProfile::default()
4370        }
4371    }
4372
4373    #[test]
4374    fn a_backend_that_honours_a_deadline_it_was_given_judges_it() {
4375        let (qos, row) = admit_contract_deadline(with_deadline(50), ALL, &ROWS, "/scan");
4376        assert_eq!((qos.deadline_ms, row.is_none()), (50, true));
4377    }
4378
4379    #[test]
4380    fn an_unserved_contract_deadline_is_stripped_and_armed() {
4381        let (qos, row) = admit_contract_deadline(with_deadline(50), NO_DEADLINE, &ROWS, "/scan");
4382        assert_eq!(qos.deadline_ms, 0, "stripped, so create does not refuse it");
4383        assert_eq!(row.map(|r| r.fqn), Some("/h/scan"));
4384    }
4385
4386    #[test]
4387    fn a_deadline_never_handed_to_the_backend_is_armed() {
4388        let (qos, row) = admit_contract_deadline(QoSProfile::default(), ALL, &ROWS, "/scan");
4389        assert_eq!((qos.deadline_ms, row.is_some()), (0, true));
4390    }
4391
4392    /// The negative controls: the caller's OWN different deadline is left for
4393    /// the backend to refuse by name, and a topic with no row is untouched.
4394    #[test]
4395    fn a_callers_own_deadline_and_an_uncontracted_topic_are_left_alone() {
4396        let (qos, _) = admit_contract_deadline(with_deadline(20), NO_DEADLINE, &ROWS, "/scan");
4397        assert_eq!(qos.deadline_ms, 20);
4398        let (qos, row) = admit_contract_deadline(with_deadline(50), NO_DEADLINE, &ROWS, "/other");
4399        assert_eq!((qos.deadline_ms, row.is_none()), (50, true));
4400    }
4401
4402    #[test]
4403    fn readiness_credits_only_the_armed_slot_and_unbind_disarms() {
4404        static C: SubMonitorCell = SubMonitorCell::new();
4405        static T: [AgeMonitorSpec; 1] = [AgeMonitorSpec {
4406            topic: "/t",
4407            fqn: "/n/t",
4408            max_age_ms: 0,
4409            deadline_ms: 10,
4410            cell: &C,
4411        }];
4412        use crate::executor::slot_mask::SlotMask;
4413        credit_arrivals(&T, SlotMask::bit(3));
4414        assert_eq!(C.arrivals.load(Ordering::Relaxed), 0, "not armed");
4415        C.deadline_slot.store(4, Ordering::Relaxed);
4416        credit_arrivals(&T, SlotMask::bit(2));
4417        credit_arrivals(&T, SlotMask::bit(3));
4418        assert_eq!(C.arrivals.load(Ordering::Relaxed), 1);
4419        deadline_unbind(&T, 2);
4420        assert_eq!(C.deadline_slot.load(Ordering::Relaxed), 4, "another slot");
4421        deadline_unbind(&T, 3);
4422        assert_eq!(C.deadline_slot.load(Ordering::Relaxed), 0);
4423    }
4424
4425    // Issue 2541.
4426    /// A row armed on a slot past 64 is credited by that slot's bit, and
4427    /// never by the slot 64 below it.
4428    #[test]
4429    fn readiness_credits_a_slot_past_64_by_its_own_bit() {
4430        use crate::executor::slot_mask::SlotMask;
4431        static C: SubMonitorCell = SubMonitorCell::new();
4432        static T: [AgeMonitorSpec; 1] = [AgeMonitorSpec {
4433            topic: "/t",
4434            fqn: "/n/t",
4435            max_age_ms: 0,
4436            deadline_ms: 10,
4437            cell: &C,
4438        }];
4439        C.deadline_slot.store(101, Ordering::Relaxed);
4440        credit_arrivals(&T, SlotMask::bit(36));
4441        assert_eq!(C.arrivals.load(Ordering::Relaxed), 0, "slot 36 is not 100");
4442        credit_arrivals(&T, SlotMask::bit(100));
4443        assert_eq!(C.arrivals.load(Ordering::Relaxed), 1);
4444    }
4445
4446    /// An armed deadline-only row judges arrivals over the deadline; fed, it
4447    /// stays quiet. Unarmed, the same row judges nothing at all.
4448    #[test]
4449    fn an_armed_deadline_row_judges_arrivals_over_its_window() {
4450        static C: SubMonitorCell = SubMonitorCell::new();
4451        let spec = AgeMonitorSpec {
4452            topic: "/t",
4453            fqn: "/n/t",
4454            max_age_ms: 0,
4455            deadline_ms: 10,
4456            cell: &C,
4457        };
4458        let mut st = AgeState::default();
4459        assert!(check_age(&spec, &mut st, Some(1_000_000)).is_none());
4460        assert!(
4461            check_age(&spec, &mut st, Some(1_050_000)).is_none(),
4462            "unarmed"
4463        );
4464        C.deadline_slot.store(1, Ordering::Relaxed);
4465        let mut st = AgeState::default();
4466        assert!(
4467            check_age(&spec, &mut st, Some(2_000_000)).is_none(),
4468            "opens"
4469        );
4470        C.arrivals.store(1, Ordering::Relaxed);
4471        assert!(check_age(&spec, &mut st, Some(2_020_000)).is_none(), "fed");
4472        let v = check_age(&spec, &mut st, Some(2_040_000)).expect("silent past 10 ms");
4473        assert_eq!((v.rule, v.declared), ("silence-runtime", 10));
4474    }
4475}