Skip to main content

nros_node/executor/
spin.rs

1//! Executor struct and core spin methods.
2
3use core::{marker::PhantomData, mem::MaybeUninit};
4#[cfg(feature = "param-store")]
5use nros_params::ParameterServerOps as _; // phase-515 R10 stage 2
6
7use nros_core::{RosMessage, RosService, ViewableMessage};
8use nros_rmw::{QoSProfile, ServiceInfo, Session, TopicInfo, TransportError};
9
10use crate::{
11    session,
12    timer::{TimerCallInfo, TimerDuration},
13};
14
15#[cfg(feature = "safety-e2e")]
16use super::arena::{
17    SubSafetyEntry, sub_safety_has_data, sub_safety_pre_sample, sub_safety_try_process,
18};
19#[cfg(feature = "rmw-cffi")]
20use super::types::ExecutorConfig;
21use super::types::{ENTRY_IDLE_BUDGET, ENTRY_POLL_BUDGET};
22// phase-427 — unconditional: `spin_forever` takes `SpinOptions` and is not
23// `alloc`-gated (a bare-metal entry is exactly the caller that needs it).
24use super::{
25    arena::{
26        BufferStrategy, CallbackMeta, EntryKind, GuardConditionEntry, ServiceClientCallbackEntry,
27        ServiceClientRawArenaEntry, ServiceClientSendHeader, SrvEntry, SrvRawEntry,
28        SubBufferedEntry, SubBufferedRawCEntry, SubBufferedRawEntry, SubBufferedRawInfoCEntry,
29        SubBufferedRawInfoEntry, SubBufferedRawMsgInfoEntry, SubBufferedTypedCEntry,
30        SubBufferedViewEntry, SubInfoEntry, SubInplaceEntry, TimerClockSource, TimerEntry,
31        TimerHeader, TimerOverrunPolicy, TraceName, always_ready, buffered_region_size, drop_entry,
32        guard_has_data, guard_try_process, no_pre_sample, service_client_callback_try_process,
33        service_client_raw_try_process, srv_has_data, srv_raw_has_data, srv_raw_try_process,
34        srv_try_process, srv_try_process_with_info, sub_buffered_has_data,
35        sub_buffered_raw_c_has_data, sub_buffered_raw_c_try_process, sub_buffered_raw_has_data,
36        sub_buffered_raw_info_c_has_data, sub_buffered_raw_info_c_try_process,
37        sub_buffered_raw_info_has_data, sub_buffered_raw_info_try_process,
38        sub_buffered_raw_msg_info_has_data, sub_buffered_raw_msg_info_try_process,
39        sub_buffered_raw_try_process, sub_buffered_try_process, sub_buffered_typed_c_has_data,
40        sub_buffered_typed_c_try_process, sub_buffered_view_has_data,
41        sub_buffered_view_try_process, sub_info_has_data, sub_info_pre_sample,
42        sub_info_try_process, sub_inplace_has_data, sub_inplace_try_process, timer_try_process,
43    },
44    node::NodeHandle,
45    spsc_ring::SpscRing,
46    triple_buffer::TripleBuffer,
47    types::{
48        ExecutorSemantics, GuardCondition, HandleId, InvocationMode, NodeError,
49        RawMessageDeserializeFn, RawResponseCallback, RawServiceCallback,
50        RawServiceRequestIdCallback, RawSubscriptionCallback, RawSubscriptionInfoCallback,
51        ReadinessSnapshot, SpinOnceResult, SpinOptions, SpinPeriodPollingResult, Trigger,
52        TypedSubscriptionCallback,
53    },
54};
55
56// ============================================================================
57// phase-456 W8 — one subscription registration, stated as one value
58// ============================================================================
59
60/// What a subscription registration STATES — phase-456 W8.
61///
62/// The thirteen `register_subscription_*` / `add_arena_subscription_*` entry
63/// points differ in their DELIVERY SHAPE (typed, raw, borrowed, with-info,
64/// validated) and used to differ in their LANGUAGE, and each re-derived the
65/// same prologue from positional parameters: node identity, topic info, the
66/// declared-depth check, the backend call. Twelve copies of it, and exactly
67/// ONE of them asked the backend whether it dispatches in place.
68///
69/// This is that prologue's argument, as one value. A struct rather than nine
70/// parameters because the fields are independently optional and a caller must
71/// be able to say "I state nothing here" without reordering a call — the same
72/// reason `DescriptorInputs` is a struct one layer up.
73///
74/// Two of its fields are the axes phase-456 W8 found under issue 1319's five
75/// rows: [`backend_hint`](Self::backend_hint) is "does this site know the
76/// type's bound", and [`in_place_capable`](Self::in_place_capable) is what
77/// lets `Executor::open_subscription` ask the third axis once, for every
78/// caller, in every language.
79pub(crate) struct SubscriptionRequest<'a> {
80    /// `None` is the legacy single-node path: identity comes from the
81    /// executor's own name and namespace and the session is slot 0.
82    pub(crate) node_id: Option<super::node_record::NodeId>,
83    pub(crate) topic_name: &'a str,
84    pub(crate) type_name: &'a str,
85    pub(crate) type_hash: &'a str,
86    pub(crate) qos: QoSProfile,
87    /// Bytes the CALL SITE says it expects to receive, for the BACKEND's
88    /// payload size class (phase-231 / RFC-0038, phase-402 W2).
89    ///
90    /// `None` — and, for a C caller whose ABI spells it `0`, a zero — means
91    /// "this site stated nothing", which is a different claim from "zero
92    /// bytes": `with_rx_buffer_hint(0)` would be the second.
93    pub(crate) backend_hint: Option<usize>,
94    /// Bytes ONE receive slot claims from the arena, already derived by the
95    /// caller that has the type.
96    ///
97    /// Not the same number as [`Self::backend_hint`] — the typed Rust path
98    /// hints the type's bound and sizes the slot from
99    /// `default_subscription_rx_bytes`, which may differ — so both travel.
100    /// Ignored entirely when [`SubscriptionOpen::in_place`] comes back true.
101    pub(crate) slot_bytes: usize,
102    /// Can THIS delivery shape dispatch out of the backend's own receive slot?
103    ///
104    /// A property of the shape, not of the backend: `process_raw_in_place`
105    /// hands the callback borrowed BYTES and nothing else, so a shape that
106    /// must also deliver a wire attachment (`_info`), an integrity status
107    /// (`_validated` / `_safety`) or a `MessageInfo` cannot use it however
108    /// capable the backend is. Stated per call site so an omission is a line
109    /// someone wrote rather than a question nobody asked — which is exactly
110    /// what the C path was before W8.
111    pub(crate) in_place_capable: bool,
112}
113
114/// The result of `Executor::open_subscription`: a claimed slot, a live backend
115/// subscriber, and the ONE answer to the in-place question.
116pub(crate) struct SubscriptionOpen {
117    /// The claimed entry slot. Claimed BEFORE the fallible work, per
118    /// `Executor::emplace_entry`'s rule.
119    pub(crate) slot: usize,
120    pub(crate) handle: session::RmwSubscriber,
121    /// **The only place in this crate that
122    /// `Subscription::supports_process_in_place` is read.**
123    ///
124    /// Before phase-456 W8 the read lived inside
125    /// `register_subscription_buffered_on`, which is the Rust typed path and
126    /// only that: every C and C++ subscription on zenoh or XRCE therefore
127    /// allocated a receive region the backend does not need, at the same order
128    /// as issue 1340's ~9.7 KiB per subscription. The irony phase-456 W8
129    /// measured is that the C callback is the BETTER candidate —
130    /// `RawSubscriptionCallback` is already `(const uint8_t*, size_t, void*)`,
131    /// a borrowed-bytes signature, where the Rust typed path has to produce an
132    /// owned `&M` from somewhere.
133    pub(crate) in_place: bool,
134    /// [`SubscriptionRequest::slot_bytes`], carried through so a caller's arena
135    /// arithmetic reads ONE local rather than re-deriving it.
136    pub(crate) slot_bytes: usize,
137    /// The QoS the backend was actually given — phase-454 W13 through
138    /// phase-456 W8.
139    ///
140    /// NOT the caller's `req.qos`. `declared_qos::honour` REWRITES the depth
141    /// when the system declared one, and the twelve prologues this function
142    /// replaced each passed that rewritten value on to the entry they built.
143    /// Returning it is what keeps that true with one honouring site: a caller
144    /// that stored `req.qos` instead would size its entry from a depth the
145    /// backend never saw, and nothing would fail — the subscription would
146    /// simply hold a different number of samples than the build reserved for
147    /// it.
148    pub(crate) qos: QoSProfile,
149}
150
151// ============================================================================
152// Phase 8 — callback registration event (paired stubs)
153// ============================================================================
154//
155// `docs/design/callback_tracing.rst`. Paired stubs (the `entry_sched_tasks.rs`
156// idiom) so `emplace_entry` reads identically whether or not the feature is
157// on, and the `#[cfg]` lives in exactly one place.
158
159/// Emit nros_callback_register(handle, kind, name) for a newly installed
160/// executor entry.
161#[cfg(feature = "trace-callbacks")]
162#[inline]
163fn trace_register(slot: usize, kind: EntryKind, name: TraceName<'_>) {
164    super::callback_trace::register(slot, kind, name);
165}
166
167#[cfg(not(feature = "trace-callbacks"))]
168#[inline]
169fn trace_register(_slot: usize, _kind: EntryKind, _name: TraceName<'_>) {}
170
171// ============================================================================
172// Executor::open() factory method
173// ============================================================================
174
175/// phase-271 / phase-392 W6 — the `'static` `u64` backing the `alloc`
176/// convenience constructors borrow, sized to `sizing`.
177///
178/// **The named static first, the heap second.** phase-271 made this a
179/// `Box::leak`, and a leak has no symbol: `mem-report` reads an ELF's symbol
180/// table, so the largest single RAM consumer of every Rust image was the one
181/// thing the memory instrument could not see (RFC-0002 § 4.4b). It is served
182/// from `executor::backing::EXECUTOR_BACKING` now — same bytes, same
183/// executor-lifetime reservation, in `.bss` where the linker can print them and
184/// out of the allocator arena that used to pay for them.
185///
186/// The heap arm is still reached, and both cases are legitimate rather than
187/// degraded: a SECOND executor opened through an `alloc` convenience
188/// constructor, and an entry sized past the build-time default. A sched-task boot's
189/// spawned sched tasks are NOT that second executor any more: they open over the
190/// entry's `SchedTaskExecutorBacking` slots (`open_with_session_slot`, issue 1571). Neither is an error, so neither
191/// warns — `report_arena_headroom` is where an over-provisioned executor gets
192/// told about itself, and a duplicate line here would just be noise.
193///
194/// `alloc`-only — no_std-no-alloc entries supply their own `static`/stack
195/// backing via `open_in` / `from_session_in`.
196#[cfg(feature = "alloc")]
197fn default_backing(sizing: super::storage::ExecutorSizing) -> &'static mut [MaybeUninit<u64>] {
198    let words = sizing.u64_len();
199    match super::backing::take(words) {
200        Some(backing) => backing,
201        None => alloc::boxed::Box::leak(alloc::boxed::Box::new_uninit_slice(words)),
202    }
203}
204
205/// Issue 2579 — run a fallible open over a default backing, and give the
206/// backing back if the open fails.
207///
208/// A board that boots before its Agent retries `Executor::open` until the
209/// session comes up. With a bare `default_backing` each failed attempt kept
210/// what it claimed: the first one the static reservation (latched for the
211/// life of the process), every later one a fresh `Box::leak` of a default
212/// executor's worth (~87 KB on Cortex-M). That panicked a small heap on the
213/// second retry. Now a failure re-arms the static's latch, or frees the heap
214/// block, so the N-th attempt costs what the first did.
215///
216/// It is sound because an `Err` leaves nothing over the backing. Every
217/// `open*_in` either fails before `from_session_in` builds an executor on it
218/// (backend selection, session open), or drops that executor on the way out
219/// (`open_multi_in`'s extra sessions). `Executor`'s `Drop` tears down every
220/// arena entry, and clears `wake_ctx`, the one pointer it hands the backend,
221/// last. `NodeError` holds no borrow. So once `open` returns `Err`, no
222/// reference into the slice exists, which is what `give_back` requires.
223///
224/// Issue 2576 — on success the executor takes the backing into its
225/// `owned_backing`, so dropping it gives the backing back the same way, and a
226/// board that re-opens after a lost session reuses it.
227#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
228fn with_default_backing(
229    sizing: super::storage::ExecutorSizing,
230    open: impl FnOnce(&'static mut [MaybeUninit<u64>]) -> Result<Executor<'static>, NodeError>,
231) -> Result<Executor<'static>, NodeError> {
232    let backing: *mut [MaybeUninit<u64>] = default_backing(sizing);
233    // SAFETY: `backing` came from `default_backing` as a unique `&'static mut`;
234    // this is that same borrow, passed on. It is not touched again unless the
235    // open fails (below).
236    let mut result = open(unsafe { &mut *backing });
237    if let Ok(exec) = result.as_mut() {
238        // Issue 2576 — the executor owns it now, and hands it back on drop.
239        // SAFETY: `backing` came from `default_backing`, and `exec` is the
240        // executor opened over it.
241        exec.owned_backing = unsafe { super::backing::OwnedBacking::owned(backing) };
242    }
243    if result.is_err() {
244        // SAFETY: the open failed, so (see above) no reference into `backing`
245        // survives it, and it is the block `default_backing` handed out.
246        unsafe { super::backing::release_default_backing(backing) }
247    }
248    result
249}
250
251#[cfg(feature = "rmw-cffi")]
252impl<'s> Executor<'s> {
253    /// Open a new executor session over caller-supplied `backing`,
254    /// sized by `sizing` (per-entry sizing). The core, non-generic sized entry
255    /// point: the `alloc` [`open`](Self::open) convenience leaks a default
256    /// backing and delegates here, and the `nros::main!` macro emits a backing
257    /// sized to the entry's own entity count.
258    ///
259    /// Auto-registers the cffi vtable for whichever
260    /// backend the build was configured for, mirroring the C++ side's
261    /// `#ifdef NROS_RMW_<NAME>` fan-out in `<rclcpp/node.hpp>`. The
262    /// runtime's atomic vtable slot is idempotent: a re-call of any
263    /// backend's `register()` is a no-op, so the fan-out below is safe
264    /// to invoke on every `Executor::open` (cheaper than a `Once` and
265    /// doesn't pull in `std::sync` for no_std targets).
266    ///
267    /// Connects to the middleware at the locator specified in `config`.
268    ///
269    /// # Safety
270    /// `backing` must be ≥ `sizing.u64_len()` words, live for `'s`, and be
271    /// otherwise untouched while the executor lives (see
272    /// [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in)).
273    pub unsafe fn open_in(
274        config: &ExecutorConfig<'_>,
275        backing: &'s mut [MaybeUninit<u64>],
276        sizing: super::storage::ExecutorSizing,
277    ) -> Result<Self, NodeError> {
278        use nros_rmw::Rmw;
279
280        // Phase 128.A.3 / 249 P4b.1 — manifest-driven backend selection.
281        //
282        // Every linked backend self-registered via its `.init_array`
283        // ctor before `main` (RFC-0042 §D3.3), so the registry is
284        // already populated — no runtime section walk.
285        //
286        // 1. Honour `config.rmw` — the caller's explicit backend selection,
287        //    mirroring ROS 2's `RMW_IMPLEMENTATION`. On a hosted build
288        //    `nros::ExecutorConfigEnvExt::from_env` / `nros::env::resolve_hosted`
289        //    fill it from `$NROS_RMW`; issue 0687 moved that read to the edge,
290        //    because reading a process environment is what kept `std` in this
291        //    crate and an RTOS image has no environment to read.
292        // 2. With no selector, pick the unique registered backend.
293        //    Zero registered → `NoBackend`; more than one →
294        //    `Ambiguous` (user must select one, or use
295        //    `Executor::open_multi`).
296        let selector = config.rmw;
297        match nros_rmw_cffi::resolve_backend(selector.map(str::as_bytes)) {
298            nros_rmw_cffi::BackendResolution::Single(_) => {}
299            // Issue 0436 — these are SELECTION outcomes, not transport failures,
300            // and calling them `ConnectionFailed` actively misleads: a PX4 bridge
301            // that registered two backends reported "connection failed", which
302            // reads as a router/network problem and was chased as one. Nothing is
303            // connected at this point — the resolver has not chosen a backend yet.
304            //
305            // The variant still collapses into `NodeError::Transport` (the enum has
306            // no selection arm, and adding one is an ABI change across the C/C++
307            // seams), but `InvalidConfig` at least says "your configuration is
308            // unresolvable", and the std-gated line below names WHICH outcome.
309            other => {
310                {
311                    let why: &str = match other {
312                        nros_rmw_cffi::BackendResolution::NoBackend => {
313                            "no RMW backend is registered"
314                        }
315                        nros_rmw_cffi::BackendResolution::Ambiguous => {
316                            "more than one RMW backend is registered and no \
317                             $NROS_RMW selector was set — name one (e.g. \
318                             NROS_RMW=uorb), or open per-backend sessions"
319                        }
320                        nros_rmw_cffi::BackendResolution::Unknown => {
321                            "$NROS_RMW names a backend that is not registered"
322                        }
323                        nros_rmw_cffi::BackendResolution::Single(_) => unreachable!(),
324                    };
325                    nros_log::log_error!(
326                        nros_log::get_logger("nros"),
327                        "cannot select an RMW backend — {why}"
328                    );
329                }
330                let _ = other;
331                return Err(NodeError::Transport(TransportError::InvalidConfig));
332            }
333        }
334
335        // RFC-0109 D8 — the image's baked session properties (its bringup's
336        // own `rmw/<backend>` file, lowered at build time).
337        let session = super::session_props::with_session_properties(&[], |properties| {
338            let rmw_config = nros_rmw::RmwConfig {
339                locator: config.locator,
340                mode: config.mode,
341                domain_id: config.domain_id,
342                node_name: config.node_name,
343                namespace: config.namespace,
344                properties,
345            };
346            if let Some(name) = selector {
347                // Selector path: route to the specific named backend so
348                // the env-var-disambiguated outcome matches what the
349                // resolver above identified.
350                nros_rmw_cffi::CffiRmw::open_with_rmw(name, &rmw_config)
351            } else {
352                nros_rmw_cffi::CffiRmw.open(&rmw_config)
353            }
354        })
355        .map_err(|e| {
356            // Issue 0465 — do not relabel. This used to discard the backend's
357            // error and report `ConnectionFailed` for every open failure, so an
358            // exhausted session pool (`InvalidConfig`) and a router that is not
359            // there produced the same sentence. Same lesson as the selection
360            // arm above: say which failure happened.
361            nros_log::log_error!(
362                nros_log::get_logger("nros"),
363                "RMW session open failed — {e:?}"
364            );
365            NodeError::Transport(e)
366        })?;
367        // SAFETY: forwarded from this fn's contract — `backing`/`sizing` sized
368        // + alive for `'s`.
369        let mut executor = unsafe { Self::from_session_in(session, backing, sizing) };
370        {
371            // `config.clock_us` overrides the constructor's platform default
372            // (issue: assigning `None` here clobbered it and re-enabled the
373            // credit-the-requested-timeout fallback).
374            if let Some(clock) = config.clock_us {
375                executor.clock_us_fn = Some(clock);
376                executor.last_spin_end_us = Some(clock());
377            }
378            // issue 0671 — the SAME rule as `clock_us` directly above, which is
379            // why that one is guarded: a config that does not SPECIFY an epoch
380            // must not be read as "this target HAS no epoch". Assigning `None`
381            // here clobbered the constructor's platform default
382            // (`Some(default_epoch_us)`), and `ExecutorConfig::new` — the path
383            // `nros::init_*` + `ctx.config()` takes — leaves `epoch_us: None`,
384            // so EVERY hosted node built that way silently lost its wall clock.
385            // With no epoch, `Node::subscription` never attaches the age cell
386            // (it needs `(STAMP_OFFSET, epoch)` both `Some`), so a baked
387            // `max_age_ms` contract becomes a silently-dead monitor — the exact
388            // outcome RFC-0052 says must never happen. The rate monitor rides
389            // the GUARDED `clock_us_fn` and kept working, which is why only the
390            // age half went quiet.
391            if let Some(epoch) = config.epoch_us {
392                executor.epoch_us_fn = Some(epoch);
393            }
394        }
395        executor.set_node_identity(config.node_name, config.namespace);
396        // Issue 0656 — beside the identity, for the same reason: an entity needs
397        // both to be addressable, and this half used to be dropped here.
398        executor.domain_id = config.domain_id;
399        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
400        executor.install_wake_signal_on_primary();
401        // Phase 277 W2.c — readiness marker for E2E harnesses. This is the
402        // single call-through `open()`/`open_sized()` share, so it fires on
403        // every platform that reaches here (native, freertos, zephyr,
404        // threadx, …) regardless of which RMW backend or board owns the
405        // boot path. It replaces the per-example synthetic
406        // `log::info!("Publishing messages")` markers W4 removes — those
407        // only proved a callback had fired at least once; this line proves
408        // the session itself is up, before any node/callback exists.
409        //
410        // STABILITY CONTRACT: the leading `"nros: session open"` text is
411        // load-bearing — test harnesses grep for it verbatim. Keep it
412        // stable even if the trailing `(rmw=...)` detail changes.
413        #[cfg(feature = "log")]
414        {
415            if let Some(name) = selector {
416                log::info!("nros: session open (rmw={name})");
417            } else {
418                log::info!("nros: session open");
419            }
420        }
421        Ok(executor)
422    }
423}
424
425#[cfg(all(feature = "rmw-cffi", feature = "alloc"))]
426impl Executor<'static> {
427    /// Open a new executor session using the active RMW backend, at the
428    /// build-time default sizing. Convenience over
429    /// [`open_in`](Self::open_in): leaks a default-sized backing (executor-
430    /// lifetime) so existing callers keep the zero-storage-arg signature.
431    /// Per-entry sizing goes through `open_in` / the `nros::main!` macro.
432    ///
433    /// # Example
434    ///
435    /// ```ignore
436    /// let config = ExecutorConfig::from_env().node_name("my_node");
437    /// let mut executor = Executor::open(&config)?;
438    /// ```
439    pub fn open(config: &ExecutorConfig<'_>) -> Result<Self, NodeError> {
440        Self::open_sized(config, super::storage::ExecutorSizing::DEFAULT)
441    }
442
443    /// Like [`open`](Self::open) but sized to a caller-supplied
444    /// `sizing` (its own declared topology) instead of the build-time default.
445    /// The `alloc` entry point the `nros::main!` macro's native board path uses
446    /// to size a fat entry (>default `MAX_CBS` callbacks) without a
447    /// workspace-global `NROS_EXECUTOR_MAX_CBS`. Leaks a `sizing`-sized backing
448    /// (executor-lifetime); no-alloc entries use `open_in` with their own static.
449    pub fn open_sized(
450        config: &ExecutorConfig<'_>,
451        sizing: super::storage::ExecutorSizing,
452    ) -> Result<Self, NodeError> {
453        // SAFETY: the backing is exactly `sizing.u64_len()` words, `'static`,
454        // uniquely owned by the returned executor; a failed open gives it back.
455        with_default_backing(sizing, |backing| unsafe {
456            Self::open_in(config, backing, sizing)
457        })
458    }
459
460    /// Explicit per-backend session declaration for
461    /// bridge mode. `specs[0]` becomes the primary session; `specs[1..]`
462    /// open as extras keyed by RMW name. After construction, every
463    /// `create_node_on(name, rmw)` call dispatches to whichever
464    /// session was opened under that RMW name (or, when the rmw name
465    /// matches the primary, the primary session itself).
466    ///
467    /// Single-backend callers should keep using
468    /// [`open`](Self::open) — this entry costs an extra
469    /// `open_with_rmw` per spec and adds no value when only one
470    /// backend is linked.
471    ///
472    /// `$NROS_RMW` env is ignored: bridge mode wants explicit names.
473    ///
474    /// Default-sized `alloc` convenience over
475    /// [`open_multi_in`](crate::executor::ffi::ExecutorFfi::open_multi_in) (leaks a default backing).
476    #[cfg(feature = "rmw-cffi")]
477    pub fn open_multi(specs: &[SessionSpec<'_>]) -> Result<Self, NodeError> {
478        let sizing = super::storage::ExecutorSizing::DEFAULT;
479        // SAFETY: the backing is exactly `sizing.u64_len()` words, `'static`;
480        // a failed open gives it back.
481        with_default_backing(sizing, |backing| unsafe {
482            Self::open_multi_in(specs, backing, sizing)
483        })
484    }
485
486    /// Open the Executor against a specific RMW
487    /// backend by name. Selects from the named registry (Phase
488    /// 104.B.2). `rmw_name` must match one of the names a backend
489    /// registered under (`"zenoh"`, `"cyclonedds"`, `"xrce"`, …).
490    ///
491    /// Equivalent to [`Executor::open`] when the registry has exactly
492    /// one backend (the default-backend fast path). Use this entry
493    /// point in multi-backend builds where `Executor::open` would
494    /// pick the first-registered slot.
495    ///
496    /// Single-Executor multi-Node multi-RMW (the long-term Design X
497    /// (the long-term multi-backend bridge design) is
498    /// follow-up work.
499    ///
500    /// Default-sized `alloc` convenience over
501    /// [`open_with_rmw_in`](Self::open_with_rmw_in) (leaks a default backing).
502    #[cfg(feature = "rmw-cffi")]
503    pub fn open_with_rmw(rmw_name: &str, config: &ExecutorConfig<'_>) -> Result<Self, NodeError> {
504        let sizing = super::storage::ExecutorSizing::DEFAULT;
505        // SAFETY: the backing is exactly `sizing.u64_len()` words, `'static`;
506        // a failed open gives it back.
507        with_default_backing(sizing, |backing| unsafe {
508            Self::open_with_rmw_in(rmw_name, config, backing, sizing)
509        })
510    }
511}
512
513// phase-271 — no-alloc sized cores for the bridge/named open paths. In
514// `impl<'s>` (not the `'static` alloc block) so they stay available in
515// `rmw-cffi`-without-`alloc` builds (e.g. the `nros-bridge` no_std default),
516// which is where `open_multi`/`open_with_rmw` lived before.
517#[cfg(feature = "rmw-cffi")]
518impl<'s> Executor<'s> {
519    /// Per-entry-sized [`open_multi`](Self::open_multi): carves `backing` for
520    /// the executor's tables instead of leaking a default one.
521    ///
522    /// # Safety
523    /// `backing`/`sizing` as in [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in).
524    pub(crate) unsafe fn open_multi_in(
525        specs: &[SessionSpec<'_>],
526        backing: &'s mut [MaybeUninit<u64>],
527        sizing: super::storage::ExecutorSizing,
528    ) -> Result<Self, NodeError> {
529        // Phase 249 P4b.1 — backends self-registered via their
530        // `.init_array` ctor before `main`; no runtime section walk.
531        let primary = specs
532            .first()
533            .ok_or(NodeError::Transport(TransportError::ConnectionFailed))?;
534        let primary_session =
535            nros_rmw_cffi::CffiRmw::open_with_rmw(primary.rmw, &primary.to_rmw_config())
536                .map_err(NodeError::Transport)?;
537        // SAFETY: forwarded from this fn's contract.
538        let mut executor = unsafe { Self::from_session_in(primary_session, backing, sizing) };
539        executor.set_node_identity("", "/");
540        // Phase 156 — see `Executor::open` for primary-identity
541        // recording rationale.
542        let _ = executor.primary_rmw_name.push_str(primary.rmw);
543        let _ = executor.primary_locator.push_str(primary.locator);
544        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
545        executor.install_wake_signal_on_primary();
546
547        for spec in specs.iter().skip(1) {
548            let session = nros_rmw_cffi::CffiRmw::open_with_rmw(spec.rmw, &spec.to_rmw_config())
549                .map_err(NodeError::Transport)?;
550            executor
551                .extra_sessions
552                .push(session)
553                .map_err(|_| NodeError::NodeTableFull)?;
554            // Issue 0436 — record WHICH backend/locator this extra is, so
555            // `NodeBuilder::rmw(name)` can find it instead of opening a second
556            // session against the same (singleton) backend.
557            {
558                let mut rmw_s = heapless::String::<32>::new();
559                let _ = rmw_s.push_str(spec.rmw);
560                let mut loc_s = heapless::String::<128>::new();
561                let _ = loc_s.push_str(spec.locator);
562                let _ = executor.extra_session_ids.push((rmw_s, loc_s));
563            }
564            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
565            {
566                let idx = executor.extra_sessions.len() - 1;
567                executor.install_wake_signal_on_extra(idx);
568            }
569        }
570
571        Ok(executor)
572    }
573
574    /// Per-entry-sized [`open_with_rmw`](Self::open_with_rmw): carves `backing`
575    /// for the executor's tables instead of leaking a default one.
576    ///
577    /// # Safety
578    /// `backing`/`sizing` as in [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in).
579    pub unsafe fn open_with_rmw_in(
580        rmw_name: &str,
581        config: &ExecutorConfig<'_>,
582        backing: &'s mut [MaybeUninit<u64>],
583        sizing: super::storage::ExecutorSizing,
584    ) -> Result<Self, NodeError> {
585        if !nros_rmw_cffi::backend_registered() {
586            return Err(NodeError::Transport(TransportError::ConnectionFailed));
587        }
588
589        let session = super::session_props::with_session_properties(&[], |properties| {
590            nros_rmw_cffi::CffiRmw::open_with_rmw(
591                rmw_name,
592                &nros_rmw::RmwConfig {
593                    locator: config.locator,
594                    mode: config.mode,
595                    domain_id: config.domain_id,
596                    node_name: config.node_name,
597                    namespace: config.namespace,
598                    properties,
599                },
600            )
601        })
602        .map_err(|_| NodeError::Transport(TransportError::ConnectionFailed))?;
603        // SAFETY: forwarded from this fn's contract.
604        let mut executor = unsafe { Self::from_session_in(session, backing, sizing) };
605        {
606            // `config.clock_us` overrides the constructor's platform default
607            // (issue: assigning `None` here clobbered it and re-enabled the
608            // credit-the-requested-timeout fallback).
609            if let Some(clock) = config.clock_us {
610                executor.clock_us_fn = Some(clock);
611                executor.last_spin_end_us = Some(clock());
612            }
613            // issue 0671 — the SAME rule as `clock_us` directly above, which is
614            // why that one is guarded: a config that does not SPECIFY an epoch
615            // must not be read as "this target HAS no epoch". Assigning `None`
616            // here clobbered the constructor's platform default
617            // (`Some(default_epoch_us)`), and `ExecutorConfig::new` — the path
618            // `nros::init_*` + `ctx.config()` takes — leaves `epoch_us: None`,
619            // so EVERY hosted node built that way silently lost its wall clock.
620            // With no epoch, `Node::subscription` never attaches the age cell
621            // (it needs `(STAMP_OFFSET, epoch)` both `Some`), so a baked
622            // `max_age_ms` contract becomes a silently-dead monitor — the exact
623            // outcome RFC-0052 says must never happen. The rate monitor rides
624            // the GUARDED `clock_us_fn` and kept working, which is why only the
625            // age half went quiet.
626            if let Some(epoch) = config.epoch_us {
627                executor.epoch_us_fn = Some(epoch);
628            }
629        }
630        executor.set_node_identity(config.node_name, config.namespace);
631        // Phase 156 — record primary identity for the session-
632        // cache hit path. See `Executor::open` for the rationale.
633        let _ = executor.primary_rmw_name.push_str(rmw_name);
634        let _ = executor.primary_locator.push_str(config.locator);
635        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
636        executor.install_wake_signal_on_primary();
637        Ok(executor)
638    }
639}
640
641/// Per-backend session declaration for
642/// [`Executor::open_multi`]. Each spec names an RMW backend (must
643/// match one a backend registered under via
644/// `nros_rmw_cffi_register_named`, which its self-registration calls) and
645/// the locator + domain id to open against it.
646#[cfg(feature = "rmw-cffi")]
647#[derive(Clone, Copy)]
648pub struct SessionSpec<'cfg> {
649    pub rmw: &'cfg str,
650    pub locator: &'cfg str,
651    pub domain_id: u32,
652    pub node_name: &'cfg str,
653    pub namespace: &'cfg str,
654    /// The session's backend-specific properties (`RmwConfig::properties`):
655    /// what its domain's RMW file lowers to.
656    /// Empty: none — the image's baked table is the DEFAULT session's and is
657    /// never given to a spec.
658    pub properties: &'cfg [(&'cfg str, &'cfg str)],
659}
660
661#[cfg(feature = "rmw-cffi")]
662impl<'cfg> SessionSpec<'cfg> {
663    /// Minimal spec — just RMW name + locator. Domain id defaults to
664    /// 0; node name and namespace are empty.
665    pub const fn new(rmw: &'cfg str, locator: &'cfg str) -> Self {
666        Self {
667            rmw,
668            locator,
669            domain_id: 0,
670            node_name: "",
671            namespace: "",
672            properties: &[],
673        }
674    }
675
676    /// The session's backend-specific properties.
677    pub const fn properties(mut self, properties: &'cfg [(&'cfg str, &'cfg str)]) -> Self {
678        self.properties = properties;
679        self
680    }
681
682    pub const fn domain_id(mut self, domain_id: u32) -> Self {
683        self.domain_id = domain_id;
684        self
685    }
686
687    pub const fn node_name(mut self, name: &'cfg str) -> Self {
688        self.node_name = name;
689        self
690    }
691
692    pub const fn namespace(mut self, ns: &'cfg str) -> Self {
693        self.namespace = ns;
694        self
695    }
696
697    fn to_rmw_config(self) -> nros_rmw::RmwConfig<'cfg> {
698        nros_rmw::RmwConfig {
699            locator: self.locator,
700            mode: nros_rmw::SessionMode::Client,
701            domain_id: self.domain_id,
702            node_name: self.node_name,
703            namespace: self.namespace,
704            properties: self.properties,
705        }
706    }
707}
708
709// Phase 128.A.3 — selector for the single-backend resolution path.
710//
711// On hosted (`std`) builds, read `$NROS_RMW`; mirrors ROS 2's
712// `RMW_IMPLEMENTATION`. Returns the name as a byte vector so the
713// caller can pass it to `nros_rmw_cffi::resolve_backend` and (when
714// `Some`) to `CffiRmw::open_with_rmw`.
715//
716// On `no_std` / bare-metal builds, environment variables are not
717// available; resolution always falls through to the single-backend
718// or ambiguous path. Embedded users with multiple backends use the
719// bridge surface `Executor::open_multi` instead.
720// phase-359 W10 / issue 0687 — the private reader that stood here is gone, and
721// so is the shared one that briefly replaced it. `ExecutorConfig::rmw` carries
722// the selection instead: `nros::rmw_selector` reads the variable ONCE, at the
723// hosted edge, and every consumer takes the value.
724
725// ============================================================================
726// SessionStore — owned or borrowed session
727// ============================================================================
728
729/// Session storage: owned or borrowed via raw pointer.
730///
731/// The C API creates a session in `rclc_support_init()` before the
732/// executor. `Borrowed` lets the executor use that session without owning it.
733///
734/// Phase-573 W3 (RFC-0108 D9) -- an owned session that is SHARED (the
735/// per-sched-task model: [`Executor::session_handle`]) must not live inline in
736/// its owner. A pointer into the owner is a child of the owner's reference, so
737/// the owner's next `&mut self` write disables it and every borrower reads
738/// through a dead pointer. So under `alloc` the owner puts its session in its
739/// own allocation (`Heap`), and owner and borrowers reach it through the same
740/// raw pointer, as equals. An inline session is never shared: `Owned` is the
741/// store when that allocation fails (and then [`Executor::session_handle`]
742/// refuses), and without `alloc`, where the shared model is the C++
743/// `open_with_session_handle_in` path and the session stays inline until the
744/// session can be carved from the executor's backing (issue 2845).
745#[allow(clippy::large_enum_variant)]
746pub(crate) enum SessionStore {
747    /// The owner's session in its own allocation, from `try_box`.
748    #[cfg(feature = "alloc")]
749    Heap(core::ptr::NonNull<session::ConcreteSession>),
750    Owned(session::ConcreteSession),
751    Borrowed(*mut session::ConcreteSession),
752}
753
754impl SessionStore {
755    /// The store for a session this executor owns.
756    pub(crate) fn owned(session: session::ConcreteSession) -> Self {
757        #[cfg(feature = "alloc")]
758        {
759            Self::owned_via(session, nros_rmw::fallible::try_box)
760        }
761        #[cfg(not(feature = "alloc"))]
762        {
763            SessionStore::Owned(session)
764        }
765    }
766
767    /// [`owned`](Self::owned) with the allocation as a parameter, so a test can
768    /// fail it. A failed allocation keeps the session inline, which is never
769    /// shared, rather than reaching the out-of-memory handler (issue 1551).
770    #[cfg(feature = "alloc")]
771    pub(crate) fn owned_via(
772        session: session::ConcreteSession,
773        alloc: impl FnOnce(
774            session::ConcreteSession,
775        ) -> Result<
776            alloc::boxed::Box<session::ConcreteSession>,
777            session::ConcreteSession,
778        >,
779    ) -> Self {
780        match alloc(session) {
781            Ok(b) => SessionStore::Heap(core::ptr::NonNull::from(alloc::boxed::Box::leak(b))),
782            Err(session) => SessionStore::Owned(session),
783        }
784    }
785
786    /// Whether this executor owns the session (closes it when it drops).
787    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
788    pub(crate) fn is_owned(&self) -> bool {
789        !matches!(self, SessionStore::Borrowed(_))
790    }
791
792    /// The session as a pointer another executor may share, or `None` for a
793    /// session held inline under `alloc` (see the type's doc).
794    fn shareable_ptr(&mut self) -> Option<*mut session::ConcreteSession> {
795        match self {
796            #[cfg(feature = "alloc")]
797            SessionStore::Heap(p) => Some(p.as_ptr()),
798            SessionStore::Borrowed(p) => Some(*p),
799            #[cfg(feature = "alloc")]
800            SessionStore::Owned(_) => None,
801            #[cfg(not(feature = "alloc"))]
802            SessionStore::Owned(s) => Some(s as *mut session::ConcreteSession),
803        }
804    }
805}
806
807#[cfg(feature = "alloc")]
808impl Drop for SessionStore {
809    fn drop(&mut self) {
810        if let SessionStore::Heap(p) = *self {
811            // SAFETY: `p` came from `Box::leak` in `owned_via` and is freed
812            // only here, when its owner drops; borrowers outlive no owner
813            // (`session_handle`'s contract).
814            drop(unsafe { alloc::boxed::Box::from_raw(p.as_ptr()) });
815        }
816    }
817}
818
819impl core::ops::Deref for SessionStore {
820    type Target = session::ConcreteSession;
821    fn deref(&self) -> &session::ConcreteSession {
822        match self {
823            // SAFETY: the allocation lives until this store drops.
824            #[cfg(feature = "alloc")]
825            SessionStore::Heap(p) => unsafe { p.as_ref() },
826            SessionStore::Owned(s) => s,
827            SessionStore::Borrowed(ptr) => unsafe { &**ptr },
828        }
829    }
830}
831
832impl core::ops::DerefMut for SessionStore {
833    fn deref_mut(&mut self) -> &mut session::ConcreteSession {
834        match self {
835            // SAFETY: as `deref`.
836            #[cfg(feature = "alloc")]
837            SessionStore::Heap(p) => unsafe { p.as_mut() },
838            SessionStore::Owned(s) => s,
839            SessionStore::Borrowed(ptr) => unsafe { &mut **ptr },
840        }
841    }
842}
843
844/// An opaque, `Send` handle to an [`Executor`]'s RMW session.
845///
846/// In the per-sched-task model the boot executor opens the one session and hands each
847/// spawned sched task a handle (not a borrow) so the task opens its own
848/// [`Executor`] over that *same* session across the RTOS task boundary. Wrapping
849/// the `pub(crate)` session pointer lets board crates (`nros-board-linux`,
850/// `nros-board-freertos`, …) name + move the handle without naming the session
851/// type. Obtain via [`Executor::session_handle`]; consume via
852/// [`Executor::open_with_session_handle`].
853#[cfg(any(has_rmw, test))]
854pub struct SessionHandle(*mut session::ConcreteSession);
855
856// SAFETY: the per-sched-task model deliberately shares one session across RTOS tasks;
857// concurrent access is serialized by the RMW backend's internal locks (the RTOS
858// targets build zenoh-pico `Z_FEATURE_MULTI_THREAD=1` — RFC-0032 §5.0). The
859// boot executor owns the session and outlives every sched task.
860#[cfg(any(has_rmw, test))]
861unsafe impl Send for SessionHandle {}
862
863#[cfg(any(has_rmw, test))]
864impl SessionHandle {
865    /// Convert to an opaque `*mut c_void` for C/C++ FFI.
866    ///
867    /// The returned pointer encodes the session address and is valid as long as
868    /// the owning executor lives. Reconstruct via [`Self::from_raw`].
869    pub fn into_raw(self) -> *mut core::ffi::c_void {
870        self.0 as *mut core::ffi::c_void
871    }
872
873    /// Reconstruct a `SessionHandle` from an opaque pointer
874    /// returned by [`Self::into_raw`].
875    ///
876    /// # Safety
877    /// `ptr` must be a pointer obtained from `into_raw()` on a `SessionHandle`
878    /// whose underlying session is still live and owned by its original executor.
879    pub unsafe fn from_raw(ptr: *mut core::ffi::c_void) -> Self {
880        Self(ptr as *mut session::ConcreteSession)
881    }
882}
883
884/// Phase 228.C — pure callback-group filter decision. `None` = wildcard (accept
885/// every group); `Some` = accept only listed groups. Backs
886/// [`Executor::group_active`]; split out so the logic is unit-testable without a
887/// live session.
888pub(crate) fn group_filter_accepts(
889    active: Option<&[super::storage::ActiveGroup]>,
890    node: u64,
891    group: &str,
892) -> bool {
893    match active {
894        None => true,
895        Some(v) => v.iter().any(|(n, g)| *n == node && g.as_str() == group),
896    }
897}
898
899/// Bytes the parameter store asks the platform heap for, in ONE allocation.
900///
901/// The size of THIS build's store, which folds every knob that
902/// shapes it (`MAX_PARAMETERS`, which a contract's `params:` derives, and the
903/// board's string/array capacities). No formula and no measured constant: the
904/// compiler's own answer, so the number reported below cannot drift from the
905/// allocation it describes.
906#[cfg(all(feature = "param-store", feature = "alloc"))]
907pub const PARAMETER_STORE_BYTES: usize = core::mem::size_of::<nros_params::ParameterStorage>();
908
909/// Issue 1706 -- a TEST seam standing in for a platform heap that returns NULL
910/// for the store's request, on the current thread only (tests run in
911/// parallel). Not a test `#[global_allocator]`: `check-feature-contract`
912/// clause (e) allows exactly one, `nros-platform`'s.
913#[cfg(all(test, feature = "alloc", feature = "param-store"))]
914pub(crate) struct RefuseParameterStore;
915
916#[cfg(all(test, feature = "alloc", feature = "param-store"))]
917std::thread_local! {
918    static REFUSE_PARAMETER_STORE: core::cell::Cell<bool> = const { core::cell::Cell::new(false) };
919}
920
921#[cfg(all(test, feature = "alloc", feature = "param-store"))]
922impl RefuseParameterStore {
923    // Only `executor::tests` arms it, and that module is mock-session only.
924    #[cfg(not(feature = "rmw-cffi"))]
925    pub(crate) fn arm() -> Self {
926        REFUSE_PARAMETER_STORE.with(|c| c.set(true));
927        Self
928    }
929
930    fn armed() -> bool {
931        REFUSE_PARAMETER_STORE.with(core::cell::Cell::get)
932    }
933}
934
935#[cfg(all(test, feature = "alloc", feature = "param-store"))]
936impl Drop for RefuseParameterStore {
937    fn drop(&mut self) {
938        REFUSE_PARAMETER_STORE.with(|c| c.set(false));
939    }
940}
941
942/// Issue 2023 / 2493 — create `node`'s `/parameter_events` publisher,
943/// `rcl_interfaces/msg/ParameterEvent`, announced under `node`.
944///
945/// The ONE creation site `check-infra-queryable-counts` holds
946/// [`PARAM_EVENT_PUBLISHERS`](crate::parameter_services::PARAM_EVENT_PUBLISHERS)
947/// to, per node (issue 2493: every node is a publisher, as stock). A node with a record goes through the node's own publisher path (its
948/// session, QoS overrides and the declared-QoS check); an executor with no
949/// registered node — a direct-API image whose parameter services the
950/// reconcile serves under the executor's own identity — publishes under that
951/// same identity on the primary session, so the events and the six services
952/// name one node.
953#[cfg(feature = "param-services")]
954fn create_param_event_pub(
955    exec: &mut Executor<'_>,
956    node: super::node_record::NodeId,
957    qos: QoSProfile,
958) -> Result<session::RmwPublisher, NodeError> {
959    type Event = nros_rcl_interfaces::msg::ParameterEvent;
960    const TOPIC: &str = "/parameter_events";
961    if exec.nodes.get(node.index()).is_some() {
962        return exec.create_raw_publisher_handle_on(
963            node,
964            TOPIC,
965            <Event as RosMessage>::TYPE_NAME,
966            <Event as RosMessage>::TYPE_HASH,
967            qos,
968            super::node::ProfileOrigin::Runtime,
969        );
970    }
971    let node_name = exec.node_name.clone();
972    let namespace = exec.namespace.clone();
973    let mut topic = TopicInfo::new(
974        TOPIC,
975        <Event as RosMessage>::TYPE_NAME,
976        <Event as RosMessage>::TYPE_HASH,
977    )
978    .with_domain(exec.domain_id)
979    .with_namespace(&namespace);
980    if !node_name.is_empty() {
981        topic = topic.with_node_name(&node_name);
982    }
983    let session = &mut *exec.session;
984    // Issue 2920 -- the runtime's own profile: fitted, never refused for a
985    // policy the backend cannot carry.
986    let supported = Session::supported_qos_policies(session);
987    let qos = super::node::fit_runtime_qos(qos, supported, "publisher", TOPIC);
988    super::node::validate_qos_or_report(&qos, supported, "publisher", TOPIC)?;
989    session
990        .create_publisher(&topic, qos)
991        .map_err(|_| NodeError::Transport(TransportError::PublisherCreationFailed))
992}
993
994/// phase-556 W13 -- create `node`'s `/rosout` writer:
995/// `rcl_interfaces/msg/Log` on the absolute topic `/rosout`, announced under
996/// the node (its session, QoS overrides and the declared-QoS check, through
997/// the node publisher path), with [`crate::rosout::qos_bounded`] -- VOLATILE,
998/// the documented divergence from upstream's TRANSIENT_LOCAL.
999///
1000/// The ONE creation site `check-infra-queryable-counts` holds
1001/// [`ROSOUT_PUBLISHERS`](crate::rosout::ROSOUT_PUBLISHERS) to, per node.
1002#[cfg(feature = "rosout")]
1003fn create_rosout_pub(
1004    exec: &mut Executor<'_>,
1005    node: super::node_record::NodeId,
1006) -> Result<session::RmwPublisher, NodeError> {
1007    type Log = nros_rcl_interfaces::msg::Log;
1008    crate::rmw_type_registry::register_type::<Log>()?;
1009    exec.create_raw_publisher_handle_on(
1010        node,
1011        crate::rosout::TOPIC,
1012        <Log as RosMessage>::TYPE_NAME,
1013        <Log as RosMessage>::TYPE_HASH,
1014        crate::rosout::qos_bounded(),
1015        super::node::ProfileOrigin::Runtime,
1016    )
1017}
1018
1019/// phase-556 W13 -- the `/rosout` writer a record from `logger` goes to: the
1020/// writer of the node whose logger it is, or of the node it is a child of
1021/// (`<node>.<child>`); otherwise the first node with a writer. `None` when no
1022/// node has one.
1023///
1024/// The fallback is also what a multi-executor image (spawned tiers) gets:
1025/// the queue is process-wide and whichever executor spins first drains it, so
1026/// a record from another executor's node is published under this executor's
1027/// first node. Its `Log.name` still names the logger that raised it.
1028#[cfg(feature = "rosout")]
1029pub(crate) fn rosout_route<'a>(
1030    nodes: &'a [super::node_record::NodeRecord],
1031    logger: &str,
1032) -> Option<&'a session::RmwPublisher> {
1033    let mut first = None;
1034    for r in nodes {
1035        let Some(p) = r.rosout.publisher() else {
1036            continue;
1037        };
1038        if first.is_none() {
1039            first = Some(p);
1040        }
1041        let name = r.name.as_str();
1042        if logger == name
1043            || (logger.len() > name.len()
1044                && logger.starts_with(name)
1045                && logger.as_bytes()[name.len()] == b'.')
1046        {
1047            return Some(p);
1048        }
1049    }
1050    first
1051}
1052
1053/// phase-556 W13 -- say, once per node, that its `/rosout` writer could not
1054/// be created. Cold: it formats.
1055#[cfg(feature = "rosout")]
1056#[cold]
1057#[inline(never)]
1058fn report_rosout_refused(node: &str, e: NodeError) {
1059    nros_log::log_error!(
1060        nros_log::get_logger("nros"),
1061        "/rosout could not be created for node {} ({:?}); its log records are not \
1062         published.",
1063        node,
1064        e
1065    );
1066}
1067
1068/// Issue 2023 — say that `/parameter_events` could not be created for a node
1069/// whose parameter services did come up. Cold: it formats.
1070#[cfg(feature = "param-services")]
1071#[cold]
1072#[inline(never)]
1073fn report_parameter_events_refused(e: NodeError) {
1074    // issue 2023
1075    nros_log::log_error!(
1076        nros_log::get_logger("nros"),
1077        "/parameter_events could not be created ({:?}); the parameter services are up, \
1078         but no parameter change is published. A publisher slot the image did not size \
1079         for is the usual cause.",
1080        e
1081    );
1082}
1083
1084/// Issue 1706 -- say, once, that the parameter store did not fit.
1085///
1086/// The RFC-0100 D11 shape, one layer up from Cyclone's boot check: the
1087/// failure is named where it is decided, with the number a reader needs to
1088/// size the heap, instead of surfacing as an anonymous halt in the allocator.
1089/// What it can name is the REQUEST; the heap's own report (Zephyr's `HEAP
1090/// EXHAUSTED` line, the board's `nros: heap peak` line) carries the capacity.
1091#[cfg(feature = "param-store")]
1092#[cold]
1093fn report_parameter_store_refused() {
1094    // Issue 1812 -- with no heap there was no allocation to refuse: the
1095    // backing carved no store, and that is the whole story.
1096    #[cfg(not(feature = "alloc"))]
1097    {
1098        let logger = nros_log::get_logger("nros");
1099        nros_log::log_error!(
1100            logger,
1101            "parameter store refused: this executor's backing carves none and the build has no heap"
1102        );
1103        // issue 1812
1104        nros_log::log_error!(
1105            logger,
1106            "every parameter declaration on this executor is refused"
1107        );
1108        // Issue 2777 -- the knob in the one spelling every report uses.
1109        nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_KNOB);
1110        nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_DERIVED);
1111    }
1112    #[cfg(feature = "alloc")]
1113    report_parameter_heap_store_refused();
1114}
1115
1116/// The `alloc` half of [`report_parameter_store_refused`]: the heap refused
1117/// the store's one allocation (issue 1706).
1118#[cfg(all(feature = "param-store", feature = "alloc"))]
1119#[cold]
1120fn report_parameter_heap_store_refused() {
1121    let slots = nros_params::MAX_PARAMETERS;
1122    // THREE short lines, not one sentence: a log backend truncates a long
1123    // line (Zephyr's cut the first draft at its slot count), and the number
1124    // is the one part that must survive.
1125    let logger = nros_log::get_logger("nros");
1126    nros_log::log_error!(
1127        logger,
1128        "parameter store refused: needs {} bytes in one allocation ({} slots x {})",
1129        PARAMETER_STORE_BYTES,
1130        slots,
1131        PARAMETER_STORE_BYTES / if slots == 0 { 1 } else { slots }
1132    );
1133    // issue 1706
1134    nros_log::log_error!(
1135        logger,
1136        "every parameter declaration on this executor is refused"
1137    );
1138    // phase-382 W3' -- the remedy that takes the store OUT of the heap comes
1139    // first: a build that knows the image builds a store carves it from the
1140    // executor backing instead (`nros_params::IMPLIED_STORE_SLOTS`).
1141    // Issue 2777 -- the knob in the one spelling every report uses.
1142    nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_KNOB);
1143    nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_DERIVED);
1144}
1145
1146/// `text` typed as `declared`'s type — phase-482 W5. `None` when it does not
1147/// parse as that type, or the type takes no override yet (arrays).
1148///
1149/// A `NotSet` declaration has no type to follow, so the text decides: `true` /
1150/// `false`, then an integer, then a double, then a string — the order rcl's
1151/// YAML reading gives an unquoted scalar.
1152#[cfg(all(feature = "param-store", feature = "alloc"))]
1153fn typed_param_override(
1154    text: &str,
1155    declared: &nros_params::ParameterValue,
1156) -> Option<nros_params::ParameterValue> {
1157    let mut value = nros_params::ParameterValue::NotSet;
1158    typed_param_override_into(text, declared, &mut value).then_some(value)
1159}
1160
1161/// [`typed_param_override`], written into `out` IN PLACE — issue 2118.
1162/// `false`, with `out` unspecified, where that returns `None`.
1163///
1164/// Returning the value cost every caller two: the `Option` the callee builds
1165/// and the binding the caller moves it into (17 KiB on Cortex-M3 for one
1166/// declaration). A caller that fills a slot it holds keeps one.
1167#[cfg(all(feature = "param-store", feature = "alloc"))]
1168fn typed_param_override_into(
1169    text: &str,
1170    declared: &nros_params::ParameterValue,
1171    out: &mut nros_params::ParameterValue,
1172) -> bool {
1173    use nros_params::ParameterValue as V;
1174    let boolean = |t: &str| match t {
1175        "true" | "True" | "TRUE" => Some(true),
1176        "false" | "False" | "FALSE" => Some(false),
1177        _ => None,
1178    };
1179    // Issue 2104 -- the TYPE is decided first and the value built once. A
1180    // chain of `Option<ParameterValue>`s (`.map(..).or_else(..)`) is one
1181    // ~8 KiB temporary per link, in every caller this inlines into.
1182    enum Typed {
1183        Bool(bool),
1184        Integer(i64),
1185        Double(f64),
1186        String,
1187    }
1188    let typed = match declared {
1189        V::Bool(_) => match boolean(text) {
1190            Some(b) => Typed::Bool(b),
1191            None => return false,
1192        },
1193        V::Integer(_) => match text.parse::<i64>() {
1194            Ok(i) => Typed::Integer(i),
1195            Err(_) => return false,
1196        },
1197        V::Double(_) => match text.parse::<f64>() {
1198            Ok(d) => Typed::Double(d),
1199            Err(_) => return false,
1200        },
1201        V::String(_) => Typed::String,
1202        V::NotSet => {
1203            if let Some(b) = boolean(text) {
1204                Typed::Bool(b)
1205            } else if let Ok(i) = text.parse::<i64>() {
1206                Typed::Integer(i)
1207            } else if let Ok(d) = text.parse::<f64>() {
1208                Typed::Double(d)
1209            } else {
1210                Typed::String
1211            }
1212        }
1213        _ => return false,
1214    };
1215    match typed {
1216        Typed::Bool(b) => *out = V::Bool(b),
1217        Typed::Integer(i) => *out = V::Integer(i),
1218        Typed::Double(d) => *out = V::Double(d),
1219        Typed::String => return out.assign_string(text),
1220    }
1221    true
1222}
1223
1224#[cfg(test)]
1225mod group_filter_tests {
1226    use super::group_filter_accepts;
1227    use crate::executor::storage::{ActiveGroup, node_identity_hash};
1228
1229    type Group = heapless::String<32>;
1230
1231    fn entry(node: &str, ns: &str, g: &str) -> ActiveGroup {
1232        let mut s = Group::new();
1233        s.push_str(g).unwrap();
1234        (node_identity_hash(node, ns), s)
1235    }
1236
1237    #[test]
1238    fn wildcard_accepts_all() {
1239        assert!(group_filter_accepts(
1240            None,
1241            node_identity_hash("n", "/"),
1242            "anything"
1243        ));
1244    }
1245
1246    #[test]
1247    fn set_accepts_only_listed_groups() {
1248        let active = [entry("n", "/", "ctrl")];
1249        let n = node_identity_hash("n", "/");
1250        assert!(group_filter_accepts(Some(&active[..]), n, "ctrl"));
1251        assert!(!group_filter_accepts(Some(&active[..]), n, "telem"));
1252    }
1253
1254    /// issue 1172 — the SAME group id on a DIFFERENT node is not this sched task's.
1255    ///
1256    /// This is the case the whole change exists for: two nodes may legitimately
1257    /// declare `ctrl`, pinned to different sched tasks, and the old filter — keyed on
1258    /// the group name alone — admitted both onto whichever sched task asked first.
1259    #[test]
1260    fn the_same_group_on_another_node_is_not_accepted() {
1261        let active = [entry("talker", "/", "ctrl")];
1262        assert!(group_filter_accepts(
1263            Some(&active[..]),
1264            node_identity_hash("talker", "/"),
1265            "ctrl"
1266        ));
1267        assert!(
1268            !group_filter_accepts(
1269                Some(&active[..]),
1270                node_identity_hash("listener", "/"),
1271                "ctrl"
1272            ),
1273            "another node's identically-named group must NOT be admitted"
1274        );
1275    }
1276
1277    /// The namespace is part of the identity, not decoration: two nodes may
1278    /// share a bare name under different namespaces, which is legal in ROS.
1279    #[test]
1280    fn the_same_name_under_another_namespace_is_a_different_node() {
1281        let active = [entry("talker", "/left", "ctrl")];
1282        assert!(!group_filter_accepts(
1283            Some(&active[..]),
1284            node_identity_hash("talker", "/right"),
1285            "ctrl"
1286        ));
1287    }
1288
1289    /// An empty namespace and `/` are the SAME node. Both ends normalise, and
1290    /// if only one did, a filter would never match what it named.
1291    #[test]
1292    fn an_empty_namespace_normalises_to_root() {
1293        assert_eq!(
1294            node_identity_hash("talker", ""),
1295            node_identity_hash("talker", "/")
1296        );
1297    }
1298
1299    /// The separator is load-bearing: without it `("ab","c")` and `("a","bc")`
1300    /// would hash alike, and a node name may contain any namespace character.
1301    #[test]
1302    fn the_name_namespace_split_cannot_be_forged() {
1303        assert_ne!(
1304            node_identity_hash("ab", "/c"),
1305            node_identity_hash("a", "b/c")
1306        );
1307    }
1308
1309    /// phase-409 — the wildcard and an EMPTY filter are different answers, and
1310    /// the carved table cannot tell them apart on its own (the old
1311    /// `Option<Vec>` could). `Executor::active_groups_filtering` is what keeps
1312    /// them apart; this pins the distinction at the decision itself.
1313    #[test]
1314    fn an_empty_filter_is_not_the_wildcard() {
1315        let empty: [ActiveGroup; 0] = [];
1316        let n = node_identity_hash("n", "/");
1317        assert!(!group_filter_accepts(Some(&empty[..]), n, "anything"));
1318        assert!(group_filter_accepts(None, n, "anything"));
1319    }
1320}
1321
1322// ============================================================================
1323// Executor
1324// ============================================================================
1325
1326/// Backend-agnostic executor that owns a session.
1327///
1328/// Provides `create_node()` for entity creation and `drive_io()` for polling.
1329///
1330/// # Callback Mode
1331///
1332/// The executor supports arena-based callback registration via the
1333/// `node_mut(id).subscription(t)` builder and
1334/// [`register_service()`](Self::register_service), with dispatch via
1335/// [`spin_once()`](Self::spin_once). No heap allocation is needed.
1336///
1337/// The sizes are set via `NROS_EXECUTOR_MAX_CBS` (default 4) and
1338/// `NROS_EXECUTOR_ARENA_BYTES` (default 4096) environment variables at build time.
1339///
1340/// Phase 124.B.2 — opaque context handed to the runtime wake
1341/// callback. Backends store the raw pointer + invoke the callback;
1342/// the callback decodes back to `&WakeCtx`.
1343///
1344/// `repr(align(64))`, or more past 64 callback slots (`entity_wake::WAKE_CTX_ALIGN`),
1345/// because an entity waker carries its slot in the low bits of a pointer to
1346/// this struct (phase-397 W2, `entity_wake`).
1347#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1348#[repr(align(64))]
1349pub(crate) struct WakeCtx {
1350    /// Zero-sized: raises the alignment past 64 when the slot capacity does.
1351    _slot_align: [super::entity_wake::WakeCtxAlign; 0],
1352    pub(crate) flag: portable_atomic_util::Arc<portable_atomic::AtomicBool>,
1353    /// The wake primitive. Phase 130.3 added it beside a `std::sync::Condvar`
1354    /// pair and noted that "a future migration to a single primitive flips one
1355    /// branch instead of two"; phase-359 W10 is that migration, and this is the
1356    /// one that survived.
1357    pub(crate) node_wake: Option<portable_atomic_util::Arc<super::node_wake::NodeWake>>,
1358    /// phase-397 W2 — one bit per entry slot an attributed arrival has marked
1359    /// since the executor last took the word. Set by an entity waker
1360    /// (`entity_wake`), never by the session-scoped callback, which cannot
1361    /// name an entry. W3 reads it instead of scanning.
1362    /// `usize` words, not `u64`: 32-bit targets without 64-bit atomics have
1363    /// no `AtomicU64`. As many words as name every callback slot
1364    /// (`entity_wake::SLOTS`), each written with one single-word atomic.
1365    pub(crate) ready: super::slot_mask::AtomicSlotMask,
1366    /// phase-509 P9b item 3 (RFC-0108 D7) -- the band workers' wake objects
1367    /// (`Executor::attach_band_worker`), a list of `'static` waiters that is
1368    /// only ever pushed to. An attributed arrival wakes the worker whose band
1369    /// holds its slot; an unattributed one wakes every worker.
1370    pub(crate) band_waiters: portable_atomic::AtomicPtr<super::scheduler::BandWaiter>,
1371}
1372
1373#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1374impl WakeCtx {
1375    pub(crate) fn new(
1376        flag: portable_atomic_util::Arc<portable_atomic::AtomicBool>,
1377        node_wake: Option<portable_atomic_util::Arc<super::node_wake::NodeWake>>,
1378    ) -> Self {
1379        Self {
1380            _slot_align: [],
1381            flag,
1382            node_wake,
1383            ready: super::slot_mask::AtomicSlotMask::new(),
1384            band_waiters: portable_atomic::AtomicPtr::new(core::ptr::null_mut()),
1385        }
1386    }
1387
1388    /// phase-509 P9b item 3 -- the wake for an arrival nothing attributes:
1389    /// the executor's own worker, and every band worker, since any of them
1390    /// may own the slot it is for.
1391    pub(crate) fn signal(&self) {
1392        self.signal_own();
1393        let mut w = self.band_waiters.load(portable_atomic::Ordering::Acquire);
1394        while !w.is_null() {
1395            // SAFETY: only `'static` waiters are linked, never unlinked.
1396            let waiter = unsafe { &*w };
1397            waiter.signal();
1398            w = waiter.next.load(portable_atomic::Ordering::Acquire);
1399        }
1400    }
1401
1402    /// The executor's own worker's wake: flag, then the primitive. Shared by
1403    /// the session callback and the entity waker so the two cannot drift.
1404    pub(crate) fn signal_own(&self) {
1405        // Phase 141.B.2 — capture T0 at cb entry. No-op when the
1406        // probe feature is off or no cycle reader is installed.
1407        #[cfg(feature = "wake-latency-probe")]
1408        super::wake_probe::on_wake();
1409        // Lock-free: the `flag` store is SeqCst and therefore happens-before any
1410        // subsequent acquire in the waiter, so a wake cannot be missed even though
1411        // nothing is held here.
1412        self.flag.store(true, core::sync::atomic::Ordering::SeqCst);
1413        // phase-359 W10 — ONE primitive. This used to signal both a
1414        // `std::sync::Condvar` and (since phase 130.3) the `NodeWake`, "so the cb
1415        // keeps working whichever wait primitive spin_once is using". `spin_once`
1416        // now has only one, so this has only one to signal.
1417        if let Some(nw) = self.node_wake.as_ref() {
1418            nw.signal();
1419        }
1420    }
1421
1422    /// Issue 2696 -- [`signal`](Self::signal) from an interrupt handler: the
1423    /// flag, the executor's own wake object, and every band worker, each
1424    /// through its interrupt-safe signal. `true` when the executor's own wake
1425    /// object took the signal; `false` when there is none or its port refuses
1426    /// (the flag is still set, and seen at the next deadline). A band
1427    /// worker's `wake_from_isr` reports nothing back.
1428    pub(crate) fn signal_from_isr(&self) -> bool {
1429        self.flag.store(true, core::sync::atomic::Ordering::SeqCst);
1430        let woke = self
1431            .node_wake
1432            .as_ref()
1433            .is_some_and(|nw| nw.signal_from_isr());
1434        let mut w = self.band_waiters.load(portable_atomic::Ordering::Acquire);
1435        while !w.is_null() {
1436            // SAFETY: only `'static` waiters are linked, never unlinked.
1437            let waiter = unsafe { &*w };
1438            waiter.signal_from_isr();
1439            w = waiter.next.load(portable_atomic::Ordering::Acquire);
1440        }
1441        woke
1442    }
1443
1444    /// phase-397 W2 — an attributed arrival on entry `slot`: its bit, then the
1445    /// wake. The bit is set FIRST, so a waiter that sees the flag sees the bit.
1446    pub(crate) fn mark_ready(&self, slot: usize) {
1447        self.ready.set(slot);
1448        // phase-509 P9b item 3 (RFC-0108 D7) -- only the worker whose band
1449        // holds the slot; the executor's own worker when no band does.
1450        let mut w = self.band_waiters.load(portable_atomic::Ordering::Acquire);
1451        while !w.is_null() {
1452            // SAFETY: only `'static` waiters are linked, never unlinked.
1453            let waiter = unsafe { &*w };
1454            if waiter.slots.test(slot) {
1455                waiter.signal();
1456                return;
1457            }
1458            w = waiter.next.load(portable_atomic::Ordering::Acquire);
1459        }
1460        self.signal_own();
1461    }
1462}
1463
1464/// Phase 124.B.2 — runtime wake callback.
1465///
1466/// RT-context contract:
1467///
1468/// * **Thread-safe**: callable from any thread. The cb is lock-free
1469///   — it sets `wake_flag` and signals the executor's `NodeWake`, a
1470///   binary semaphore, which holds a signal sent before the waiter
1471///   blocks, so no wakeup is lost. (A condvar pair guarded it before
1472///   phase-359 W10: the waiter checked `wake_flag` under ~~`wake_mu`~~.)
1473/// * **NOT async-signal-safe on POSIX**: `pthread_cond_signal`
1474///   isn't on the POSIX async-signal-safe function list. For POSIX
1475///   signal handler wake, use a `signalfd` + select pattern in a
1476///   thread that owns the wake duty — that pattern is Linux-only
1477///   (`signalfd`/`eventfd` are Linux syscalls, not POSIX), which is
1478///   why the `WakeSignalFd` worker is gated `target_os = "linux"`.
1479/// * **NOT for an interrupt handler.** It reaches the port's thread signal
1480///   (`xSemaphoreGive` on FreeRTOS, which must not run in an ISR). An
1481///   interrupt calls [`nros_rmw_runtime_wake_cb_from_isr`] instead, which
1482///   [`GuardCondition::trigger_from_isr`](super::GuardCondition::trigger_from_isr)
1483///   reaches (issue 2696).
1484/// * **Bounded execution time**: O(1) — atomic store + cv notify.
1485///   No allocation, no contended lock.
1486///
1487/// The cb is the symbol backends invoke from their async wake path
1488/// (datagram arrival, worker-thread enqueue, etc.). It does
1489/// flag-write + condvar-signal in that order, lock-free.
1490#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1491pub(crate) unsafe extern "C" fn nros_rmw_runtime_wake_cb(ctx: *mut core::ffi::c_void) {
1492    if ctx.is_null() {
1493        return;
1494    }
1495    // SAFETY: ctx points at a `WakeCtx` owned by an Executor still
1496    // alive at the time of the call. `Executor::clear_wake_signal`
1497    // discharges that obligation — `set_wake_callback(None, _)` on the
1498    // primary and every extra session — from `Executor::close` (before
1499    // the session closes) and from the end of `Executor::drop` (before
1500    // `wake_ctx` is dropped). Issue 1385: until then this comment named
1501    // an "`install_wake_*` teardown path" that did not exist, and
1502    // `set_wake_callback(None` occurred nowhere in the tree but here.
1503    let wake = unsafe { &*(ctx as *const WakeCtx) };
1504    wake.signal();
1505}
1506
1507/// phase-436 — the callback a backend holds when several executors share its
1508/// session: signal every member of the [`WakeFanout`](super::wake_fanout)
1509/// whose address is `ctx`. The entry is a `static`, so `ctx` never dangles.
1510#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1511pub(crate) unsafe extern "C" fn nros_rmw_fanout_wake_cb(ctx: *mut core::ffi::c_void) {
1512    if ctx.is_null() {
1513        return;
1514    }
1515    // SAFETY: `ctx` is `WakeFanout::as_ctx` of a `static` pool entry.
1516    let fanout = unsafe { &*(ctx as *const super::wake_fanout::WakeFanout) };
1517    fanout.fire(nros_rmw_runtime_wake_cb);
1518}
1519
1520/// phase-467 Row 8 — the symbol a backend invokes when the ROS GRAPH changes.
1521///
1522/// `rmw_event_callback_t`'s shape, so it fits the ABI slot unchanged:
1523/// `user_data` plus a coalesced count, and no payload. The count is IGNORED on
1524/// purpose — a guard condition is a level, not a queue, so N changes observed
1525/// before the executor spins are one dispatch. That is the same collapse
1526/// `guard_try_process` already performs on a flag several `trigger()`s set.
1527///
1528/// RT-context contract: identical to [`nros_rmw_runtime_wake_cb`] and for the
1529/// same reason — a relaxed-store-plus-wake, O(1), no allocation, no lock. Both
1530/// are called from a transport or worker thread.
1531///
1532/// # Safety
1533///
1534/// `user_data` must be the pointer `Executor::install_graph_change_guard`
1535/// passed: a `GuardCondition` in a box that executor owns. The obligation is
1536/// discharged by `clear_graph_change_signal`, which retires the pointer from
1537/// the backend BEFORE the box is freed, from `close()` and from `drop`. Issue
1538/// 1385 is what the other ordering costs.
1539#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1540pub(crate) unsafe extern "C" fn nros_rmw_runtime_graph_change_cb(
1541    user_data: *const core::ffi::c_void,
1542    _count: usize,
1543) {
1544    if user_data.is_null() {
1545        return;
1546    }
1547    // SAFETY: see this function's `# Safety`.
1548    let guard = unsafe { &*(user_data as *const GuardCondition) };
1549    guard.trigger();
1550}
1551
1552/// Linux signalfd worker.
1553///
1554/// Owns a Linux `eventfd` plus a worker task that `read()`s the
1555/// fd and forwards it as a wake. The eventfd
1556/// write side is async-signal-safe per the kernel contract
1557/// (`write(2)` to an eventfd is permitted from signal handlers),
1558/// closing the gap that `pthread_cond_signal` leaves open on POSIX.
1559///
1560/// Lifecycle:
1561///   * Constructed lazily in `Executor::signal_fd()` on first
1562///     caller request.
1563///   * `Drop` writes a shutdown sentinel + joins the worker.
1564///
1565/// Caller flow (signal handler):
1566///   1. Get fd via `Executor::signal_fd()` before installing the
1567///      handler.
1568///   2. Handler does `eventfd_write(fd, 1)` (equivalently,
1569///      `write(fd, &1u64, 8)`).
1570///   3. Worker thread reads the fd, signals wake_cv. spin_once
1571///      blocked in cv.wait_timeout_while sees flag=true and exits.
1572///
1573/// The worker is a PLATFORM TASK, not a `std::thread`, and it
1574/// forwards through the same [`NodeWake`](super::node_wake::NodeWake) the
1575/// runtime wake callback uses rather than a `std::sync::Condvar`. The eventfd
1576/// itself is still Linux — that is what makes the write async-signal-safe — so
1577/// this stays `target_os = "linux"`; what it no longer is, is std-only.
1578#[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1579pub struct WakeSignalFd {
1580    fd: core::ffi::c_int,
1581    ctx: portable_atomic_util::Arc<SignalFdCtx>,
1582    task: Option<nros_platform_api::task::PlatformTask>,
1583}
1584
1585/// What the signalfd worker task needs, reachable through one pointer.
1586#[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1587struct SignalFdCtx {
1588    fd: core::ffi::c_int,
1589    shutdown: portable_atomic::AtomicBool,
1590    /// The executor's wake state — the same `WakeCtx` the runtime callback
1591    /// decodes, reached as an address so the context is plainly `Send`.
1592    wake_ctx: usize,
1593}
1594
1595/// Worker entry: read the eventfd, forward as a wake, until shut down.
1596///
1597/// # Safety
1598/// `arg` must point at a live [`SignalFdCtx`] whose `wake_ctx` addresses a
1599/// `WakeCtx` that outlives this task.
1600#[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1601unsafe extern "C" fn signal_fd_worker(arg: *mut core::ffi::c_void) -> *mut core::ffi::c_void {
1602    // SAFETY: the spawn site passes `Arc::as_ptr` of a ctx it keeps alive until
1603    // after the join in `Drop`.
1604    let ctx = unsafe { &*(arg as *const SignalFdCtx) };
1605    loop {
1606        let mut buf = [0u8; 8];
1607        // SAFETY: reading 8 bytes from an eventfd into an 8-byte buffer.
1608        let n = unsafe { libc::read(ctx.fd, buf.as_mut_ptr() as *mut core::ffi::c_void, 8) };
1609        if ctx.shutdown.load(portable_atomic::Ordering::Acquire) {
1610            return core::ptr::null_mut();
1611        }
1612        if n <= 0 {
1613            // EINTR / EOF — shutdown was re-checked above, so loop.
1614            continue;
1615        }
1616        // Same effect as `nros_rmw_runtime_wake_cb`, reached directly because
1617        // the shutdown check above plus `Drop`'s join is what guarantees the
1618        // `WakeCtx` is still alive.
1619        // SAFETY: `wake_ctx` addresses the executor's `WakeCtx`, which outlives
1620        // this task by that same guarantee.
1621        unsafe {
1622            let w = &*(ctx.wake_ctx as *const WakeCtx);
1623            w.flag.store(true, portable_atomic::Ordering::SeqCst);
1624            if let Some(wake) = w.node_wake.as_ref() {
1625                wake.signal();
1626            }
1627        }
1628    }
1629}
1630
1631#[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1632impl WakeSignalFd {
1633    /// Spawn the worker. `wake_ctx_ptr` is the `*const WakeCtx`
1634    /// produced by `Executor::wake_ctx_ptr` — same value the
1635    /// runtime wake cb decodes.
1636    ///
1637    /// phase-359 W10 — returns `NodeError` rather than `std::io::Error`. The
1638    /// only caller is `Executor::signal_fd`, and the errno detail it used to
1639    /// carry had no consumer: the one failure a caller can act on is "this
1640    /// platform would not give me the worker", which is what
1641    /// `NotInitialized` says — the eventfd and the task are both subsystems
1642    /// this capability requires and neither is guaranteed.
1643    fn new(wake_ctx_ptr: *const WakeCtx) -> Result<Self, NodeError> {
1644        // SAFETY: `eventfd(2)` with a valid flag; returns -1 on failure.
1645        let fd = unsafe { libc::eventfd(0, libc::EFD_CLOEXEC) };
1646        if fd < 0 {
1647            return Err(NodeError::NotInitialized);
1648        }
1649        let ctx = portable_atomic_util::Arc::new(SignalFdCtx {
1650            fd,
1651            shutdown: portable_atomic::AtomicBool::new(false),
1652            wake_ctx: wake_ctx_ptr as usize,
1653        });
1654        let arg = portable_atomic_util::Arc::as_ptr(&ctx) as *mut core::ffi::c_void;
1655        // SAFETY: `arg` points at a ctx this struct owns and keeps alive until
1656        // after the join in `Drop`.
1657        let Some(task) = (unsafe {
1658            nros_platform_api::task::PlatformTask::spawn(
1659                signal_fd_worker,
1660                arg,
1661                // A read(2) loop and one atomic store — the smallest stack any
1662                // port will honour is plenty.
1663                8192,
1664                c"nros-wakefd".as_ptr(),
1665            )
1666        }) else {
1667            // SAFETY: nothing else holds the fd — the task never started.
1668            unsafe { libc::close(fd) };
1669            return Err(NodeError::NotInitialized);
1670        };
1671        Ok(Self {
1672            fd,
1673            ctx,
1674            task: Some(task),
1675        })
1676    }
1677
1678    /// Returns the writable eventfd. The caller (typically a POSIX
1679    /// signal handler) writes any non-zero 8-byte value to trigger
1680    /// a wake. `write(2)` on an eventfd is async-signal-safe per
1681    /// `eventfd(2)` man page.
1682    pub fn fd(&self) -> core::ffi::c_int {
1683        self.fd
1684    }
1685}
1686
1687#[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
1688impl Drop for WakeSignalFd {
1689    fn drop(&mut self) {
1690        self.ctx
1691            .shutdown
1692            .store(true, portable_atomic::Ordering::Release);
1693        // Wake the worker so it re-checks shutdown: it is blocked in `read`,
1694        // which only this write can release.
1695        let one: u64 = 1;
1696        // SAFETY: an 8-byte write to our own eventfd.
1697        unsafe {
1698            libc::write(self.fd, &one as *const u64 as *const core::ffi::c_void, 8);
1699        }
1700        if let Some(task) = self.task.take() {
1701            task.join();
1702        }
1703        // SAFETY: the worker has exited, so nothing else touches the fd.
1704        unsafe { libc::close(self.fd) };
1705    }
1706}
1707
1708/// Issue 2696 -- [`nros_rmw_runtime_wake_cb`] from an interrupt handler, or
1709/// on POSIX from a signal handler: what
1710/// [`GuardCondition::trigger_from_isr`](super::GuardCondition::trigger_from_isr)
1711/// calls. It sets the flag and signals through each port's
1712/// `nros_platform_wake_signal_from_isr` and each band worker's
1713/// `wake_from_isr`, never the thread signal (`xSemaphoreGive` on FreeRTOS
1714/// corrupts the scheduler from an interrupt). No allocation, no lock.
1715///
1716/// `ctx` semantics identical to [`nros_rmw_runtime_wake_cb`].
1717#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
1718pub(crate) unsafe extern "C" fn nros_rmw_runtime_wake_cb_from_isr(
1719    ctx: *mut core::ffi::c_void,
1720) -> bool {
1721    if ctx.is_null() {
1722        return false;
1723    }
1724    // SAFETY: as `nros_rmw_runtime_wake_cb`.
1725    let wake = unsafe { &*(ctx as *const WakeCtx) };
1726    wake.signal_from_isr()
1727}
1728
1729/// Executor-owned component tick slot.
1730///
1731/// The layering-clean half of the `install` seam's tick fix.
1732/// A `nros`-layer `install`/`register_node_borrowed`
1733/// builds an `Arc<ComponentCell>` (the typed/poll-driven component
1734/// state) and enrolls it here via [`Executor::enroll_component`]; the
1735/// executor then drives `tick` on every enrolled slot at the tail of
1736/// each [`spin_once`](Executor::spin_once) — so `install`'d nodes
1737/// (C, C++, **and Rust owned-spin**) tick, closing the
1738/// service-client/action poll gap that the callback-`Arc`-only
1739/// lifetime left open.
1740///
1741/// The executor only sees raw pointers + `extern "C"` fn pointers (no
1742/// `nros` dep — `nros-node` is the lower layer):
1743///
1744/// * `state` — a *leaked* `Arc<ComponentCell>` (via `Arc::into_raw`),
1745///   re-borrowed by the `nros`-side `tick`/`drop` fns. Unlike a
1746///   pub/sub/timer component (kept alive by the executor's per-entity
1747///   callback `Arc` clones), a poll-only component has no callbacks, so
1748///   the slot must own a clone of the cell — hence the paired `drop`.
1749/// * `tick` — `nros`-side `extern "C"` fn that casts `state` back to
1750///   `&ComponentCell`, casts `exec_ctx` back to `*mut Executor`, and
1751///   runs that one cell's tick (mirrors `ExecutorNodeRuntime::run_ticks`).
1752/// * `drop` — `nros`-side `extern "C"` fn run on `Executor::drop` that
1753///   reconstitutes + drops the leaked `Arc`, so the executor owns the
1754///   cell's lifetime.
1755#[derive(Clone, Copy)]
1756pub struct ComponentSlot {
1757    /// Leaked `Arc<ComponentCell>` (opaque to the executor). Owned by
1758    /// this slot — dropped via `drop` on `Executor::drop`.
1759    pub state: *mut core::ffi::c_void,
1760    /// `nros`-side tick trampoline: `(state, exec_ctx)` where `exec_ctx`
1761    /// is `*mut Executor`. Drives one component's `tick`.
1762    pub tick: unsafe extern "C" fn(state: *mut core::ffi::c_void, exec_ctx: *mut core::ffi::c_void),
1763    /// `nros`-side drop trampoline: reconstitutes + drops the leaked
1764    /// `Arc<ComponentCell>` at `state`. Run once on `Executor::drop`.
1765    pub drop: unsafe extern "C" fn(state: *mut core::ffi::c_void),
1766    /// The level that registered the component
1767    /// (`Executor::set_registering_level` at enrol time), whose pass runs its
1768    /// `tick`; `NO_OWNING_LEVEL` on an executor whose levels do not own
1769    /// their slots, where the executor's own worker ticks every component.
1770    pub level: u8,
1771    /// Whether the component's `tick` does any work. A tick
1772    /// runs once per spin and is how a component polls a service reply or
1773    /// completes an action goal, so an executor holding one keeps the spin
1774    /// cadence ([`Executor::entry_spin_budget`]). `false` only for a
1775    /// component that states it has no tick.
1776    pub ticks: bool,
1777}
1778
1779// SAFETY: two raw pointers + two extern "C" fn pointers. The `state` pointer's Send/Sync matches the owning
1780// `Executor` (`unsafe impl Send for Executor`); the fn pointers are
1781// Send/Sync by definition.
1782unsafe impl Send for ComponentSlot {}
1783unsafe impl Sync for ComponentSlot {}
1784
1785/// phase-271 — fixed capacity of the per-spin ready-sets (FIFO bitmap + EDF
1786/// heap) and the dispatch loop's upper bound. The executor's callback index is
1787/// carried in slot masks (`slot_mask::SlotMask`), so a callback table holds at
1788/// most this many entries regardless of per-entry sizing; the ready-sets are
1789/// sized to this ceiling (stack-transient) so any entry slice up to it
1790/// dispatches correctly.
1791///
1792/// The value is `crate::config::CALLBACK_SLOT_CAPACITY`, derived from the
1793/// image's own callback counts; the carve caps every table at it
1794/// (`storage::callback_slots`).
1795pub(crate) const MAX_CALLBACK_SLOTS: usize = crate::config::CALLBACK_SLOT_CAPACITY;
1796
1797/// Whether a
1798/// slot whose backend cannot attribute an arrival (XRCE, uORB) is probed after
1799/// every callback ([`Executor::set_reprobe_each_callback`]) or once per pass.
1800///
1801/// Measured on the host (`reprobe_cost_on_an_unattributed_executor`, release
1802/// build, x86-64, `NROS_EXECUTOR_MAX_CBS=32`): 32 unattributed subscriptions,
1803/// 4 ready per pass, empty callbacks. Once per pass 380-385 ns per pass;
1804/// after every callback 565-577 ns, i.e. +185-191 ns per pass, +46-48 ns per
1805/// callback, 1.65-1.71 ns per extra `has_data` (a mock's: no FFI, no
1806/// transport). The cost is one probe per unsettled slot per CALLBACK, so it
1807/// grows with slots x callbacks, and a real XRCE or uORB probe crosses the
1808/// rmw C ABI on an MCU several times slower than this host. Decided: once
1809/// per pass by default (an XRCE / uORB image keeps today's probe cost), with
1810/// the per-callback probe an opt-in. Pushed readiness (zenoh, which
1811/// attributes every arrival) joins mid-pass whatever this says, for one
1812/// atomic swap per callback.
1813pub const REPROBE_EACH_CALLBACK_DEFAULT: bool = false;
1814
1815/// Issue 1667 — the arena's allocation grain. Every region the arena hands out
1816/// starts on it and is a multiple of it, so a released region is always big
1817/// enough, and aligned enough, to hold its own free-list node.
1818pub(crate) const ARENA_GRAIN: usize = core::mem::align_of::<u64>();
1819
1820/// Issue 1667 — the smallest region the arena hands out: one free-list node
1821/// (`next`, `len`), rounded to the grain.
1822pub(crate) const ARENA_MIN_REGION: usize =
1823    (2 * core::mem::size_of::<usize>()).next_multiple_of(ARENA_GRAIN);
1824
1825/// Issue 1667 — the end of the free list.
1826const ARENA_FREE_NONE: usize = usize::MAX;
1827
1828/// Issue 1496 — one arena region, as an allocation hands it out.
1829#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1830pub(crate) struct FreedRegion {
1831    pub(crate) offset: usize,
1832    pub(crate) len: usize,
1833}
1834
1835/// The slots of one executor's RAM remap table
1836/// (across all its nodes).
1837///
1838/// The launch file's rules no longer live
1839/// here: they are one `const` table in flash every executor reads
1840/// ([`super::launch_remap`]). This table holds the RUNTIME rules: `--ros-args
1841/// -r` rules (`crate::ros_args::install_argv_remaps`) and rules a hand-written
1842/// caller declares with [`Executor::declare_remap`]. Its default is
1843/// [`crate::config::RUNTIME_REMAPS`]: 16 on a target with process arguments,
1844/// 0 on bare metal (no argv; `NROS_EXECUTOR_RUNTIME_REMAPS` restores slots).
1845pub const MAX_REMAPS: usize = crate::config::RUNTIME_REMAPS;
1846
1847/// Why [`Executor::declare_remap`] refused a rule -- never a silently dropped
1848/// routing rule.
1849#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1850pub enum RemapRefused {
1851    /// This executor has no runtime remap table: bare metal sizes it 0, since
1852    /// the launch's rules are the flash table and there is no argv. Restore
1853    /// slots with `NROS_EXECUTOR_RUNTIME_REMAPS`, or let codegen emit the rule
1854    /// into the launch table.
1855    NoRuntimeTable,
1856    /// The runtime table is full (`ExecutorSizing::remaps` slots, shared with
1857    /// `--ros-args -r` rules).
1858    TableFull,
1859    /// A string is longer than its slot (node name / namespace 64 bytes,
1860    /// `from` / `to` `MAX_RESOLVED_NAME_LEN`).
1861    TooLong,
1862}
1863
1864impl core::fmt::Display for RemapRefused {
1865    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1866        match self {
1867            Self::NoRuntimeTable => f.write_str(
1868                "declare_remap: this executor has no runtime remap table (0 slots: bare \
1869                 metal takes launch remaps from the flash table, nros_cpp_set_launch_remaps); \
1870                 set NROS_EXECUTOR_RUNTIME_REMAPS to restore runtime slots",
1871            ),
1872            Self::TableFull => f.write_str(
1873                "declare_remap: the runtime remap table is full (NROS_EXECUTOR_RUNTIME_REMAPS \
1874                 slots, shared with --ros-args -r rules)",
1875            ),
1876            Self::TooLong => f.write_str(
1877                "declare_remap: a name is longer than its slot (node name and namespace 64 \
1878                 bytes, from/to MAX_RESOLVED_NAME_LEN)",
1879            ),
1880        }
1881    }
1882}
1883
1884/// Which of [`crate::names::resolve_name_layered`]'s two tiers a stored rule
1885/// belongs to.
1886#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1887pub(crate) enum RemapTier {
1888    /// Projected from the launch file (`declare_remap`, which the generated
1889    /// entry calls). AUTHORITATIVE, scoped to one `(name, namespace)`.
1890    Launch,
1891    /// Parsed from `--ros-args` (`crate::ros_args::install_argv_remaps`).
1892    /// FALLBACK — consulted only when no launch rule matched. Scoped to every
1893    /// node, or to the nodes of one NAME (rcl matches a `node:` prefix
1894    /// against the name alone).
1895    Argv,
1896}
1897
1898/// Phase 305 W3 (issue 0255) — one remap rule. `from`/`to` are stored RAW (as
1899/// written); the lookup in [`Executor::resolve_entity_name_for`] expands both
1900/// sides against the owning node's identity via `crate::names` (exact-FQN
1901/// match, no wildcards).
1902///
1903/// The table holds BOTH tiers, so each rule records which one it belongs to.
1904/// The tier is still decided at resolution, by
1905/// [`crate::names::resolve_name_layered`]'s two parameters, never by where a
1906/// rule sits in this table — `tier_rules` splits the table into those two
1907/// arguments. That is what keeps declaration order from deciding between the
1908/// channels: an argv rule installed before a launch rule still loses to it.
1909pub(crate) struct RemapRule {
1910    /// For [`RemapTier::Launch`]: the owning node. For [`RemapTier::Argv`]:
1911    /// the node name a `name:from:=to` rule was restricted to, or EMPTY for a
1912    /// rule that applies to every node.
1913    pub(crate) node_name: heapless::String<64>,
1914    /// For [`RemapTier::Launch`] only (normalised, `/` for root). Unused by
1915    /// argv rules, whose node prefix carries no namespace.
1916    pub(crate) namespace: heapless::String<64>,
1917    pub(crate) from: heapless::String<{ crate::names::MAX_RESOLVED_NAME_LEN }>,
1918    pub(crate) to: heapless::String<{ crate::names::MAX_RESOLVED_NAME_LEN }>,
1919    pub(crate) tier: RemapTier,
1920}
1921
1922impl RemapRule {
1923    /// Does this rule belong to `tier` and apply to the node `(node_name, ns)`?
1924    /// `ns` must already be normalised (`/` for root).
1925    fn applies(&self, tier: RemapTier, node_name: &str, ns: &str) -> bool {
1926        self.tier == tier
1927            && match tier {
1928                RemapTier::Launch => {
1929                    self.node_name.as_str() == node_name && self.namespace.as_str() == ns
1930                }
1931                RemapTier::Argv => {
1932                    self.node_name.is_empty() || self.node_name.as_str() == node_name
1933                }
1934            }
1935    }
1936}
1937
1938/// The rules of one tier that apply to one node, in declaration order, as the
1939/// `(from, to)` pairs [`crate::names::resolve_name_layered`] takes. The ONE
1940/// place a stored table is split into the two tiers — the executor's resolver,
1941/// `NodeHandle`, and the Rust component road (through
1942/// `crate::ros_args::argv_fallback`) all read through it.
1943pub(crate) fn tier_rules<'r>(
1944    table: &'r [Option<RemapRule>],
1945    tier: RemapTier,
1946    node_name: &'r str,
1947    namespace: &'r str,
1948) -> impl Iterator<Item = (&'r str, &'r str)> + 'r {
1949    let ns = if namespace.is_empty() { "/" } else { namespace };
1950    table
1951        .iter()
1952        .flatten()
1953        .filter(move |r| r.applies(tier, node_name, ns))
1954        .map(|r| (r.from.as_str(), r.to.as_str()))
1955}
1956
1957/// Issue 1971 -- the two places an executor's remap rules live, read as the
1958/// two tiers of [`crate::names::resolve_name_layered`]:
1959///
1960/// * AUTHORITATIVE: the launch table in flash (`launch`) and, after it, any
1961///   rule a hand-written caller declared at run time (`RemapTier::Launch`
1962///   rows of `runtime`);
1963/// * FALLBACK: the `--ros-args -r` rules (`RemapTier::Argv` rows of
1964///   `runtime`).
1965///
1966/// The tier is decided by which parameter a rule is passed in, never by
1967/// where it sits, so an argv rule installed before a launch rule still loses.
1968#[derive(Clone, Copy)]
1969pub(crate) struct RemapView<'r> {
1970    pub(crate) launch: &'r [super::launch_remap::LaunchRemap],
1971    pub(crate) runtime: &'r [Option<RemapRule>],
1972}
1973
1974impl<'r> RemapView<'r> {
1975    /// The authoritative rules for one node: the flash table's, then the
1976    /// runtime-declared ones.
1977    pub(crate) fn launch_rules<'a>(
1978        self,
1979        node_name: &'a str,
1980        ns: &'a str,
1981    ) -> impl Iterator<Item = (&'a str, &'a str)> + 'a
1982    where
1983        'r: 'a,
1984    {
1985        super::launch_remap::launch_rules_for(self.launch, node_name, ns).chain(tier_rules(
1986            self.runtime,
1987            RemapTier::Launch,
1988            node_name,
1989            ns,
1990        ))
1991    }
1992
1993    /// The fallback (`--ros-args -r`) rules for one node.
1994    pub(crate) fn argv_rules<'a>(
1995        self,
1996        node_name: &'a str,
1997        ns: &'a str,
1998    ) -> impl Iterator<Item = (&'a str, &'a str)> + 'a
1999    where
2000        'r: 'a,
2001    {
2002        tier_rules(self.runtime, RemapTier::Argv, node_name, ns)
2003    }
2004
2005    /// `resolve_name_layered` over both tiers.
2006    pub(crate) fn resolve(
2007        self,
2008        source: &str,
2009        node_name: &str,
2010        ns: &str,
2011    ) -> Result<crate::names::ResolvedName, ()> {
2012        crate::names::resolve_name_layered(
2013            source,
2014            node_name,
2015            ns,
2016            self.launch_rules(node_name, ns),
2017            self.argv_rules(node_name, ns),
2018        )
2019    }
2020}
2021
2022/// The executor's halt flag, in the one shape each configuration can hold.
2023///
2024/// Issue 1177. With an allocator it is refcounted, because `halt_flag()` hands
2025/// a caller its own handle to set from a signal handler or another thread.
2026/// Without one there is no handle to hand out -- a C caller reaches the
2027/// executor through its own pointer and calls `cancel()` directly -- so a plain
2028/// atomic is the whole requirement.
2029///
2030/// `Arc<AtomicBool>` derefs to `AtomicBool`, so every `load`/`store` below is
2031/// written once and only construction and the getter are cfg'd.
2032#[cfg(feature = "alloc")]
2033pub(crate) type HaltFlag = portable_atomic_util::Arc<portable_atomic::AtomicBool>;
2034/// See [`HaltFlag`] above -- the no-allocator shape.
2035#[cfg(not(feature = "alloc"))]
2036pub(crate) type HaltFlag = portable_atomic::AtomicBool;
2037
2038/// The executor's entry arena, held as a raw pointer and a length rather than
2039/// a `&'s mut [MaybeUninit<u8>]` (RFC-0108 D9, issue 2675).
2040///
2041/// Every path into the arena derives its pointer from this one: the pass that
2042/// dispatches an entry, and a callback that calls back into the executor (a C
2043/// timer cancel writes the entry it is running from). A stored `&mut` would
2044/// give each path its own reborrow, and a write through one disables the
2045/// other, so the pass could not touch the entry again after the callback.
2046/// Raw pointers derived from one raw pointer share its permission, so the
2047/// pass and the callback stay compatible, and each entry's own `&mut` is
2048/// derived afresh after the callback returns.
2049pub(crate) struct ArenaRef<'s> {
2050    ptr: core::ptr::NonNull<MaybeUninit<u8>>,
2051    len: usize,
2052    _borrow: core::marker::PhantomData<&'s mut [MaybeUninit<u8>]>,
2053}
2054
2055impl<'s> ArenaRef<'s> {
2056    /// Hold `arena` for `'s`: the executor is its only user from here on.
2057    pub(crate) fn new(arena: &'s mut [MaybeUninit<u8>]) -> Self {
2058        let len = arena.len();
2059        Self {
2060            ptr: core::ptr::NonNull::from(arena).cast(),
2061            len,
2062            _borrow: core::marker::PhantomData,
2063        }
2064    }
2065
2066    /// The arena's first byte, for a write.
2067    #[inline]
2068    pub(crate) fn as_mut_ptr(&self) -> *mut MaybeUninit<u8> {
2069        self.ptr.as_ptr()
2070    }
2071
2072    /// The arena's first byte, for a read.
2073    #[inline]
2074    pub(crate) fn as_ptr(&self) -> *const MaybeUninit<u8> {
2075        self.ptr.as_ptr()
2076    }
2077
2078    /// The arena's size in bytes.
2079    #[inline]
2080    pub(crate) fn len(&self) -> usize {
2081        self.len
2082    }
2083}
2084
2085// SAFETY: `ArenaRef` stands for the `&'s mut [MaybeUninit<u8>]` it was made
2086// from, which is `Send` and `Sync` (bytes); it adds no shared state.
2087unsafe impl Send for ArenaRef<'_> {}
2088// SAFETY: as above.
2089unsafe impl Sync for ArenaRef<'_> {}
2090
2091// RFC-0128 D8 (phase-554 W3 slice B).
2092/// The open of an executor-level entity
2093/// that belongs to the image's primary node, run by
2094/// [`Executor::open_on_primary_node`]: with `ctx` and `arg` as installed, and
2095/// the executor, whose primary node now exists (or, in a zero-node image, at
2096/// the first spin -- see [`Executor::open_pending_on_configured_name`]).
2097///
2098/// # Safety
2099/// The installer guarantees `ctx` is valid for the call.
2100pub type PrimaryNodeHook = unsafe fn(
2101    ctx: *mut core::ffi::c_void,
2102    arg: u32,
2103    executor: &mut Executor<'_>,
2104) -> Result<(), NodeError>;
2105
2106pub struct Executor<'s> {
2107    /// Issue 0656 — the ROS domain this executor's entities belong to.
2108    ///
2109    /// Retained because it was NOT: `open_in` passed `config.domain_id` into
2110    /// `RmwConfig` and dropped it, so every entity built from the executor
2111    /// (rather than from a `Node`, which keeps its own) declared on domain 0
2112    /// whatever `ROS_DOMAIN_ID` said. The value was read, printed, and then not
2113    /// used where it counts — issue 0161's shape.
2114    pub(crate) domain_id: u32,
2115    pub(crate) session: SessionStore,
2116    /// phase-271 (issue 0110) — the six sized tables are no longer inline
2117    /// arrays baked to `nros-node`'s build-time consts; they borrow
2118    /// caller-owned, per-entry-sized storage (`&'s mut` slices carved from a
2119    /// raw `[MaybeUninit<u64>]` backing by [`super::storage::carve`]). Lets a
2120    /// fat native entry and a lean embedded entry in one shared-target
2121    /// workspace each size to its own topology. `Executor` stays non-generic
2122    /// (lifetime only) so the C/C++ FFI keeps wrapping one concrete type.
2123    pub(crate) arena: ArenaRef<'s>,
2124    pub(crate) arena_used: usize,
2125    /// Issue 1496 / 1667 — the head of the FREE LIST: arena regions given back
2126    /// by a released entry, reused first-fit by the next allocation that fits.
2127    ///
2128    /// The list is INTRUSIVE — each free region holds its own node
2129    /// (`next`, `len`) in its first bytes — and kept in address order, so a
2130    /// release coalesces with both neighbours and nothing bounds how many holes
2131    /// there are. 1496's form was a fixed table of 8 that dropped a region when
2132    /// full and dropped any split tail under 64 B, and those bytes were gone
2133    /// for good: measured under a churning workload (issue 1667), three live
2134    /// entries leaked the whole 74 KiB arena inside 20 000 create/release
2135    /// rounds. A hole that ends at `arena_used` is given back to the bump
2136    /// pointer instead of being listed.
2137    pub(crate) arena_free_head: usize,
2138    /// Issue 1631 — the region the most recent ENTRY allocation handed out,
2139    /// waiting for `emplace_entry` to record it in the entry's
2140    /// `CallbackMeta::arena_len`. Every registration allocates its entry and
2141    /// then emplaces it, so the pair is adjacent; a registration that fails
2142    /// between them leaves a stale value that the next allocation overwrites.
2143    pub(crate) pending_region: Option<FreedRegion>,
2144    pub(crate) entries: &'s mut [Option<CallbackMeta>],
2145    /// Phase 110.B — registered scheduling contexts. Slot 0 is
2146    /// auto-populated with a `Fifo` SC at construction; every entry
2147    /// without an explicit binding maps to it via
2148    /// `sched_context_bindings`.
2149    pub(crate) sched_contexts: &'s mut [Option<super::sched_context::SchedContext>],
2150    /// Per-entry SC binding parallel to `entries`. Defaults to
2151    /// `SchedContextId(0)` (the auto-created Fifo SC).
2152    pub(crate) sched_context_bindings: &'s mut [super::sched_context::SchedContextId],
2153    /// Phase 110.E — user-space sporadic-server budget state per
2154    /// Sporadic-class SC. Slot indices match `sched_contexts`; non-
2155    /// Sporadic slots stay `None`.
2156    pub(crate) sporadic_states: &'s mut [Option<super::sched_context::SporadicState>],
2157    /// Phase 110.E.b — atomic sporadic state + opaque platform-timer
2158    /// handle for ISR-driven refill. Populated by
2159    /// `register_sporadic_timer`; dropped on Executor `Drop` via the
2160    /// stored `destroy_fn`.
2161    #[cfg(feature = "alloc")]
2162    pub(crate) sporadic_atomic_states: &'s mut [Option<(
2163        portable_atomic_util::Arc<super::sched_context::AtomicSporadicState>,
2164        OpaqueTimerHandle,
2165    )>],
2166    /// Phase 110.G — major-frame length for time-triggered dispatch.
2167    /// `0` (default) disables the TT gate entirely; non-zero enables
2168    /// gating per
2169    /// `SchedContext.tt_window_offset_us / tt_window_duration_us`.
2170    pub(crate) major_frame_us: u32,
2171    pub(crate) trigger: Trigger,
2172    pub(crate) semantics: ExecutorSemantics,
2173    /// Node name for entities the executor registers on the node's behalf.
2174    /// Empty means unset — no liveliness tokens will be declared.
2175    pub(crate) node_name: heapless::String<64>,
2176    /// Phase 228.C — per-sched-task callback-group filter. Wildcard (register every
2177    /// callback — the single-sched-task degenerate case + today's behaviour) until
2178    /// [`set_active_groups`](Self::set_active_groups) names a non-empty set;
2179    /// after that this sched task's executor accepts only callbacks whose
2180    /// `.callback_group()` is in it, and skips the others at registration.
2181    ///
2182    /// phase-409 — CARVED, and the wildcard is a separate flag rather than an
2183    /// `Option` around the table, because the table itself no longer lives in
2184    /// the value. "Filtering with an empty set" and "not filtering" stay
2185    /// distinguishable, which is the whole content of the old `Option`.
2186    pub(crate) active_groups: super::storage::CarvedVec<'s, super::storage::ActiveGroup>,
2187    /// Whether [`active_groups`](Self::active_groups) is a filter at all.
2188    /// `false` = wildcard (the old `None`).
2189    pub(crate) active_groups_filtering: bool,
2190    /// Node namespace (default: "/").
2191    pub(crate) namespace: heapless::String<64>,
2192    /// Phase 104.C.2 — rclcpp-style `add_node` table. Holds the
2193    /// per-Node metadata (name, namespace, rmw, locator, default
2194    /// SchedContext) for every Node attached to this Executor. The
2195    /// implicit "primary" Node (NodeId(0)) mirrors `node_name` +
2196    /// `namespace` above and is auto-populated on first use.
2197    ///
2198    /// phase-409 — CARVED. `NodeId` IS an index into this table, so the
2199    /// carved vector must keep push order and never gain a `swap_remove`.
2200    pub(crate) nodes: super::storage::CarvedVec<'s, super::node_record::NodeRecord>,
2201    /// Phase 272 (RFC-0047) — config-seeded node → sched-context bindings, keyed by the node's
2202    /// fully-qualified `(name, namespace)` pair. `NodeBuilder::build` consults this table to set a
2203    /// node's `default_sched` when no explicit `.sched()` was given. Empty ⇒ every node stays
2204    /// `SchedContextId(0)` (byte-identical to pre-272 behaviour). Sized by `MAX_NODES` (at most
2205    /// one sched task per node — RFC-0047 OQ1).
2206    ///
2207    /// phase-409 — CARVED.
2208    pub(crate) node_sched_table: super::storage::CarvedVec<'s, super::storage::NodeSchedEntry>,
2209    /// Phase 273 (RFC-0047) — config-seeded per-callback-group sched bindings, keyed by the node's
2210    /// fully-qualified `(name, namespace)` pair PLUS the callback-group name. Overrides the node
2211    /// default for a callback created in that group. Empty ⇒ no per-group binding (node default
2212    /// stands). Sized by `MAX_CBS` — an upper bound on distinct callback-group bindings (you can
2213    /// never have more distinct group bindings than max callbacks).
2214    ///
2215    /// phase-409 (issue 0961) — CARVED, and it is the reason the phase exists:
2216    /// at ~168 B per slot this was `MAX_CBS` * 168 bytes INSIDE the value, so
2217    /// raising the handle limit from 14 to 36 — a fix for an unrelated failure —
2218    /// added ~3.7 KiB to the stack frame of every function that moves an
2219    /// `Executor`, and overflowed a 320 KiB part's main thread.
2220    pub(crate) group_sched_table: super::storage::CarvedVec<'s, super::storage::GroupSchedEntry>,
2221    /// Phase 305 W3 (issue 0255) — launch-baked per-node remap rules, keyed by
2222    /// the declaring node's `(name, namespace)` identity. Entries store the
2223    /// rule RAW (as written in launch); [`Self::resolve_entity_name`] expands
2224    /// both sides against the owning node's identity at lookup, via the shared
2225    /// `crate::names` seam (the same semantics the Rust `ExecutorSink` path
2226    /// applies). Declaration order is match order (first rule wins).
2227    /// Issue 0563 — CARVED, not inline. As a `heapless::Vec<RemapRule,
2228    /// MAX_REMAPS>` this one field was 6664 bytes of an 11632-byte `Executor`
2229    /// (57%), which is what made building an executor a ~9.3 KB stack
2230    /// temporary and overflowed the Zephyr Cortex-M main stack (issue 0552).
2231    /// It is the seventh sized table; phase-271 moved the other six here.
2232    /// `remap_len` is the fill cursor — occupied slots are `[0, remap_len)`.
2233    pub(crate) remap_table: &'s mut [Option<RemapRule>],
2234    pub(crate) remap_len: usize,
2235    /// Issue 1971 -- this executor's own launch remap table, when one was set
2236    /// on it ([`Self::set_launch_remaps`]); `None` reads the image's
2237    /// ([`super::launch_remap::launch_remaps`]), which the generated entry
2238    /// installs once before any sched task is set up. A borrow of `.rodata`, never
2239    /// a copy.
2240    pub(crate) launch_remaps: Option<&'static [super::launch_remap::LaunchRemap]>,
2241    /// Phase 258 (Track 2, 2a) — executor-owned component tick registry.
2242    /// Enrolled by [`Executor::enroll_component`] (from `nros`'s
2243    /// `install`/`register_node_borrowed`); each slot's `tick` runs at the
2244    /// tail of [`spin_once`](Self::spin_once); each slot's `drop` runs on
2245    /// `Executor::drop`. Bounded `MAX_NODES` (matches `nodes`).
2246    ///
2247    /// phase-409 — CARVED.
2248    pub(crate) component_slots: super::storage::CarvedVec<'s, ComponentSlot>,
2249    /// Issue 2146 -- callback slots the host DEFERS (`set_deferred`): the
2250    /// spin queues them instead of running them. One bit per slot.
2251    pub(crate) deferred_mask: super::slot_mask::SlotMask,
2252    /// Issue 2146 -- deferred slots queued by a spin and not yet run by
2253    /// `run_deferred` / `run_deferred_handle`.
2254    pub(crate) deferred_pending: super::slot_mask::SlotMask,
2255    /// Issue 2146 -- the host's `(notifier, ctx)`, called once per queueing.
2256    pub(crate) defer_notify: Option<(super::types::DeferNotify, *mut core::ffi::c_void)>,
2257    /// Phase 104.C.3 — extra sessions opened by `node_builder.rmw()`
2258    /// calls that named a backend different from the Executor's
2259    /// primary session. Indexed by `NodeRecord.session_idx`
2260    /// (1..=N maps to `extra_sessions[N-1]`; idx 0 is the primary
2261    /// `self.session`). Sized by `NROS_EXECUTOR_MAX_NODES` since one
2262    /// extra session per Node is the worst case.
2263    ///
2264    /// phase-409 — CARVED, and the biggest single win: `ConcreteSession` is
2265    /// 524 B on the island, so this table alone was ~3.1 KiB of the value.
2266    /// Declared AFTER `session` so field-order drop still closes the primary
2267    /// session before the extras (`CarvedVec` owns its elements' drop).
2268    pub(crate) extra_sessions: super::storage::CarvedVec<'s, session::ConcreteSession>,
2269    /// Issue 0436 — `(rmw_name, locator)` for each entry of `extra_sessions`,
2270    /// the extras' equivalent of `primary_rmw_name` / `primary_locator`.
2271    ///
2272    /// Without it an extra session is ANONYMOUS, and
2273    /// `NodeBuilder::resolve_session_slot` could only recognise one by finding a
2274    /// previously-registered `NodeRecord` bound to it. Sessions opened by
2275    /// `open_multi*` have no such Node yet, so the FIRST `.rmw("zenoh")` node fell
2276    /// through to "open a new session" — a SECOND zenoh session, with an empty
2277    /// locator, which fails (see `primary_rmw_name`'s note: zenoh-pico's global
2278    /// state is a process singleton). That is why the PX4 bridge could open both
2279    /// sessions and then fail to bind its outward Node.
2280    ///
2281    /// Written unconditionally by `open_multi*`, but the only READER is
2282    /// `NodeBuilder::resolve_session_slot`, which is `rmw-cffi`-gated — so
2283    /// without that feature the field is genuinely unread and the
2284    /// workspace's `-D dead_code` is right to say so. Allow it exactly
2285    /// there rather than blanket-allowing a field that must stay live in
2286    /// every configuration that can reach the reader.
2287    ///
2288    /// phase-409 — CARVED.
2289    #[cfg_attr(not(feature = "rmw-cffi"), allow(dead_code))]
2290    pub(crate) extra_session_ids: super::storage::CarvedVec<'s, super::storage::ExtraSessionId>,
2291    /// Phase 156 — primary session's rmw name + locator, captured
2292    /// at `open*` time so `NodeBuilder::resolve_session_slot`'s
2293    /// cache lookup can detect when a `.rmw(name).locator(loc)`
2294    /// matches the primary (slot 0) instead of falling through to
2295    /// `CffiRmw::open_with_rmw` and trying to open a SECOND
2296    /// session against the same backend. zenoh-pico's global state
2297    /// is a process singleton; opening twice fails. Empty when
2298    /// constructed via `from_session(_ptr)` without `open*`
2299    /// recording the metadata; in that case the cache check
2300    /// degrades to "always miss" (today's behaviour).
2301    pub(crate) primary_rmw_name: heapless::String<32>,
2302    pub(crate) primary_locator: heapless::String<128>,
2303    // phase-359 W3 — `portable_atomic_util::Arc`, not `std::sync::Arc`. Same
2304    // atomically-refcounted pointer, available without `std`, and it compiles on
2305    // std too. W3 left the GATE on `std` because the public `halt_flag()` getter
2306    // was std-gated; W10 split that impl, so the field joined `wake_flag` on
2307    // `alloc`.
2308    //
2309    // Issue 1177 — the ALLOCATOR was never the requirement of the FLAG, only of
2310    // SHARING it. The flag is an `AtomicBool`; what needs an allocator is
2311    // `halt_flag()`, the getter that hands a caller its own refcounted handle to
2312    // set from a signal handler or another thread. Gating the flag on `alloc`
2313    // therefore gated the ability to STOP a no_std executor on a feature it does
2314    // not need -- and `nros-c`'s spin loop calls `cancel`/`is_halted`/
2315    // `enter_spin_loop`/`exit_spin_loop`/`is_spinning` unconditionally, so an
2316    // embedded image did not merely lose cancellation, it failed to compile.
2317    //
2318    // `HaltFlag` is the one type name that differs, so every reader below is
2319    // written once: `Arc<AtomicBool>` derefs to `AtomicBool`, so `load`/`store`
2320    // are identical on both sides and only construction and the getter are
2321    // cfg'd.
2322    pub(crate) halt_flag: HaltFlag,
2323    /// Is a spin loop running right now? — the observable behind
2324    /// `is_spinning()` (phase-417 W4.c, rclcpp's `Executor::is_spinning`).
2325    ///
2326    /// A plain atomic, not refcounted like `halt_flag`: nothing hands this one
2327    /// out. `halt_flag()` is a public getter that gives a caller its own
2328    /// handle to set from another thread; `spinning` is only ever set by the
2329    /// executor's own loops through `&self`, so it needs no shared ownership.
2330    ///
2331    /// Issue 1177 — this used to ride `alloc` "for the same reason the impl
2332    /// that reads it does". It never needed an allocator itself; it was gated
2333    /// by ASSOCIATION with `halt_flag`, and when that association turned out to
2334    /// be wrong this went with it.
2335    pub(crate) spinning: portable_atomic::AtomicBool,
2336    /// Phase 104.C.6 — shared executor wake flag. Any source of work
2337    /// (foreign thread handing off a callback, signal handler, future
2338    /// per-session vtable wake hook) sets this; `spin_once` swaps it to
2339    /// `false` on entry and, if it was `true`, polls every session with
2340    /// a 0-ms timeout instead of blocking. Lets one notification wake
2341    /// the executor regardless of which session the user is currently
2342    /// blocked on (the multi-RMW bridge case).
2343    // phase-359 W3 — ONE wake flag, both flavours. W2 had to leave this pair
2344    // alone because `wake_handle()` hands it out as a `std::sync::Arc`;
2345    // converting that signature is what lets the two collapse. Gated on
2346    // `alloc` (which `std` implies) because the Arc needs an allocator.
2347    #[cfg(feature = "alloc")]
2348    pub(crate) wake_flag: portable_atomic_util::Arc<portable_atomic::AtomicBool>,
2349    /// Phase 124.B.2 — wake condvar paired with `wake_flag`. The
2350    /// runtime-supplied wake callback (`nros_rmw_runtime_wake_cb` in
2351    /// nros-rmw-cffi) writes `wake_flag = true` AND signals the executor's
2352    /// `NodeWake` (a condvar pair, ~~`wake_cv`~~ / ~~`wake_mu`~~, before
2353    /// phase-359 W10). `spin_once` blocks on it with a deadline instead of
2354    /// calling `drive_io` with the user's timeout — sub-poll-period wake
2355    /// latency.
2356    ///
2357    /// Poll-only backends (NULL `set_wake_callback` slot) leave the
2358    /// cb uninstalled; the cv wait still fires on its deadline,
2359    /// then drive_io(0) drains whatever the backend's internal
2360    /// poll has buffered.
2361    /// Phase 130.3 — Zephyr+std uses `nros_platform_wake_*` (k_sem)
2362    /// instead of `std::sync::Condvar` because Zephyr's libc
2363    /// `pthread_cond_timedwait` hangs past its deadline. `None`
2364    /// when the platform provider didn't link a wake primitive
2365    /// (e.g. test builds with `rmw-cffi` but no `platform-*`
2366    /// feature); spin_once falls back to driving the transport
2367    /// for the full timeout in that case.
2368    // phase-359 W2 — ONE field, not one per flavour. `portable_atomic_util::Arc`
2369    // compiles on std too, and `std` implies `alloc`, so the std and alloc arms
2370    // were two spellings of the same thing. The inner `NodeWake` was already
2371    // shared; only the Arc differed.
2372    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2373    pub(crate) node_wake: Option<portable_atomic_util::Arc<super::node_wake::NodeWake>>,
2374    /// Phase 130.4 — true when at least one session's backend
2375    /// installed the wake callback. Drives whether `spin_once`
2376    /// uses the wake-primitive wait (`NodeWake` / `Condvar`) or
2377    /// just `drive_io(timeout_ms)`. Poll-only backends
2378    /// (XRCE-DDS-Client, the dust-DDS shim) leave this `false`;
2379    /// Cyclone sets it — it fills the slot and backs it with a real
2380    /// `dds_set_listener` listener; the wait then becomes a no-op sleep that
2381    /// starves reliable retransmission (Phase 127.C.4 root
2382    /// cause: server's `send_response` flushes 100 ms once, then a
2383    /// blind `wait_ms(100)` sleeps with zero session activity, so
2384    /// the agent's ACK arrives into a stalled session and reliable
2385    /// redelivery never fires).
2386    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2387    pub(crate) has_async_wake: bool,
2388    /// phase-397 W2 — one bit per entry slot whose handle accepted an entity
2389    /// waker (`arm_entity_wake`): its arrivals mark [`WakeCtx::ready`] and wake
2390    /// this executor alone. A clear bit is an entry whose backend cannot
2391    /// attribute an arrival, which the session wake still covers. W3 needs
2392    /// both halves: the ready bits are only a complete answer when every live
2393    /// entry that can have data is attributed.
2394    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2395    pub(crate) entity_attributed: super::slot_mask::SlotMask,
2396    /// phase-397 W3 — attributed slots the NEXT spin must ask `has_data`
2397    /// about, although no arrival marked them: each one that was ready on
2398    /// this spin (dispatched or not, since a dispatch may leave data behind
2399    /// and a failed trigger dispatches nothing), one held mid-dispatch when
2400    /// its arrival came, and one just armed (its data may predate the
2401    /// registration, which the ABI says the caller closes with one
2402    /// `has_data`). A slot drops out the first spin its `has_data` is false.
2403    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2404    pub(crate) entity_recheck: super::slot_mask::SlotMask,
2405    /// Issue 2060 — attributed SUBSCRIPTION slots whose `has_data` the scan
2406    /// asks EVERY pass, arrival or not, because a status event is polled
2407    /// there. Every backend that carries subscription status events polls
2408    /// them from `has_data` (zenoh's deadline / liveliness / matched walk,
2409    /// Cyclone's `subscription_take_event` drain through the cffi adapter),
2410    /// and those are the events about NOTHING ARRIVING — the last publisher
2411    /// left, a deadline passed. A pushed slot is otherwise asked only after
2412    /// an arrival, so once the last sample was taken nothing asked again and
2413    /// the matched count never fell.
2414    ///
2415    /// Set by [`Executor::subscription_handle_mut`], the one road by which a
2416    /// status-event callback reaches an arena subscription's backend handle;
2417    /// cleared with the entry. A slot with no status callback is never in it,
2418    /// so an idle image that registered none still makes no probe at all —
2419    /// the phase-397 W3 property `readiness_probe_count` pins. No wake is
2420    /// added either: the cadence is the spin's own (one park per pass), and
2421    /// each backend rate-limits its own walk inside `has_data`.
2422    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2423    pub(crate) entity_status_polled: super::slot_mask::SlotMask,
2424    /// phase-397 W3 — `has_data` calls the readiness scan has made, for the
2425    /// test that proves a pushed spin makes none. Wrapping; read only through
2426    /// [`Executor::readiness_probe_count`].
2427    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2428    pub(crate) readiness_probes: u32,
2429    /// phase-509 P3 (RFC-0108 D2) -- after every callback the dispatcher
2430    /// picks again from the ready set as it is now. Pushed readiness (an
2431    /// attributed slot's arrival) joins mid-pass always; a slot whose backend
2432    /// cannot attribute (XRCE, uORB, a mock) joins mid-pass only when this is
2433    /// set, by a `has_data` probe after each callback. Unset, such a slot is
2434    /// probed once per pass, at the scan. See
2435    /// [`Executor::set_reprobe_each_callback`] for the measured cost.
2436    pub(crate) reprobe_each_callback: bool,
2437    /// Phase 124.B.2 — opaque context Arc handed to backends via
2438    /// `set_wake_callback`. Lazy-allocated on first install; stays
2439    /// alive for the Executor's lifetime so the raw pointer stored
2440    /// in backends remains valid.
2441    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2442    pub(crate) wake_ctx: Option<portable_atomic_util::Arc<WakeCtx>>,
2443    /// Issue 1385 — has THIS executor handed `wake_ctx`'s pointer to a
2444    /// backend? The predicate `clear_wake_signal` reads at teardown.
2445    ///
2446    /// Not `wake_ctx.is_some()`: the ctx is also allocated by `signal_fd()`
2447    /// and by every guard condition, neither of which installs anything on a
2448    /// session. Clearing on those would clear a callback this executor never
2449    /// owned. (Since phase-436 a sched task over a BORROWED session does install: it
2450    /// joins the session's wake fan-out, and its teardown is leaving it.)
2451    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2452    pub(crate) wake_cb_installed: bool,
2453    /// phase-436 — this executor's place in the wake fan-out of its PRIMARY
2454    /// session, when it has one. Every executor over a session joins the same
2455    /// entry, so an arrival wakes all of them, not only the one that happened
2456    /// to install into the backend's single slot. See `wake_fanout`.
2457    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2458    pub(crate) wake_membership: Option<super::wake_fanout::Membership>,
2459    /// phase-467 Row 8 — the graph-change target the BACKEND holds a pointer
2460    /// to, owned here.
2461    ///
2462    /// This box is the whole answer to issue 1385 on this path. The backend
2463    /// fires the graph-change edge from a transport or worker thread, so
2464    /// whatever it dereferences must outlive every such call — and the thing
2465    /// the caller has in hand is a `rcl_guard_condition_t` in ITS storage,
2466    /// which the caller may free or reuse at any time. Handing that pointer
2467    /// over would BE 1385. So the executor keeps its own handle to the same
2468    /// arena flag, at a heap address that does not move when the executor
2469    /// does, and [`clear_graph_change_signal`] retires the backend's pointer
2470    /// BEFORE this box drops.
2471    ///
2472    /// [`clear_graph_change_signal`]: Self::clear_graph_change_signal
2473    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2474    pub(crate) graph_change_target: Option<alloc::boxed::Box<GuardCondition<'s>>>,
2475    /// Phase 124.B.7.c — lazily-allocated Linux signalfd worker.
2476    /// Owned by the Executor; spawned on first `signal_fd()` call.
2477    /// Drop joins the worker thread and closes the fd.
2478    #[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
2479    pub(crate) signal_fd: Option<WakeSignalFd>,
2480    /// Issue 1812 — CARVED from the backing's [`ParamHome`](super::storage::ParamHome)
2481    /// when the sizing carves a store; with `alloc`, one heap allocation
2482    /// otherwise. Without `alloc` there is no heap arm, and an executor whose
2483    /// backing carves no home refuses parameters by name instead.
2484    #[cfg(feature = "param-store")]
2485    pub(crate) params: Option<crate::param_store::Placed<'s, crate::param_store::ParamState<'s>>>,
2486    /// phase-382 W3' — the parameter store's slots, CARVED from this
2487    /// executor's backing and still uninitialised. Taken (left empty) the
2488    /// first time something builds the store; empty from the start when the
2489    /// sizing carved none, in which case the store comes from the heap.
2490    #[cfg(feature = "param-store")]
2491    pub(crate) param_slots: &'s mut [MaybeUninit<nros_params::ParameterSlot>],
2492    /// Issue 1812 — the services' home, CARVED beside the store's slots and
2493    /// still uninitialised. Taken with them; empty when the sizing carved no
2494    /// store.
2495    #[cfg(feature = "param-store")]
2496    pub(crate) param_home: &'s mut [MaybeUninit<super::storage::ParamHome>],
2497    /// Issue 1706 -- the parameter store's one allocation was refused by the
2498    /// platform heap. Recorded so the refusal is REPORTED once and not retried
2499    /// on every declaration: a retry cannot succeed on a heap that only shrinks
2500    /// from here, and on Zephyr each attempt prints its own `HEAP EXHAUSTED`.
2501    #[cfg(feature = "param-store")]
2502    pub(crate) param_store_refused: bool,
2503    /// phase-446 W6 -- the parameters each node's contract DECLARES, baked by
2504    /// the entry from the SystemModel. Empty (nothing checked) until an entry
2505    /// hands one over with [`Self::set_declared_params`].
2506    #[cfg(feature = "param-store")]
2507    pub(crate) declared_params: nros_params::DeclaredParams,
2508    /// phase-425 W3b — the `/clock` subscription this image installed, if any.
2509    /// `None` means no time source; the value is the handle so it can be
2510    /// cancelled when `use_sim_time` goes false.
2511    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2512    pub(crate) sim_time_source: Option<HandleId>,
2513    /// phase-425 W3b — the LAST REQUESTED state of `use_sim_time`, which is not
2514    /// the same thing as the installed state: a request can arrive before any
2515    /// node exists (`nros::main!` declares parameters BEFORE it registers
2516    /// components), and there is no node to hang a subscription on until then.
2517    /// `reconcile_ros_time_source` closes the gap on each spin.
2518    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2519    pub(crate) sim_time_requested: bool,
2520    /// Whether `use_sim_time` was ever stated to THIS executor.
2521    ///
2522    /// `sim_time_requested` alone cannot answer it: `false` is both "told to
2523    /// turn it off" and "never told anything", and the two license opposite
2524    /// actions on a PROCESS-GLOBAL gate. Without this, every executor that
2525    /// never heard of the parameter wrote `set_active(false)` on its first
2526    /// spin -- because the gate defaults to TRUE, so `false != is_active()`
2527    /// held -- and switched off a simulated clock somebody else installed.
2528    /// One `cargo test` process is exactly that situation: 344 sibling tests
2529    /// spin an executor each, and the sim-time test failed 3 runs of 3 while
2530    /// passing alone.
2531    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2532    pub(crate) sim_time_stated: bool,
2533    /// phase-430 W1 — the one-shot that says "`use_sim_time` is on and `/clock`
2534    /// has never spoken", so a MISCONFIGURED image is distinguishable from a
2535    /// merely PAUSED one. Armed when the source attaches, disarmed by the first
2536    /// sample or by the report. The policy, and the argument for its unit, are
2537    /// in [`crate::time_source::SilenceWatch`].
2538    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2539    pub(crate) sim_time_silence: crate::time_source::SilenceWatch,
2540    /// RFC-0128 D1 (phase-554 W1): one REP-2002 state machine PER managed
2541    /// node, keyed by the node it is served under. A heap table, so the
2542    /// `Executor` value holds one `Vec` header whatever the node count (the
2543    /// size ceiling of issue 0961); bounded by the node table, since a
2544    /// managed node is a node.
2545    #[cfg(feature = "lifecycle-services")]
2546    pub(crate) lifecycle: alloc::vec::Vec<crate::lifecycle_services::LifecycleEntry>,
2547    /// Wall-clock instant at which the previous `spin_once` exited. The
2548    /// timer delta on the next call is measured from this point so any
2549    /// time the caller spent between `spin_once` invocations (e.g. an
2550    /// explicit `thread::sleep`) counts toward timer accumulation just
2551    /// like time spent inside `drive_io`.
2552
2553    /// Monotonic clock endpoint for no_std timer accounting.
2554    // phase-359 W4 — ONE field. The std twin held an `Instant`; both now hold
2555    // µs from the single `now_us()` read.
2556    pub(crate) last_spin_end_us: Option<u64>,
2557    /// The executor's monotonic µs clock: `ExecutorConfig::clock_us` when the
2558    /// caller supplied one, else [`default_clock_us_fn`].
2559    ///
2560    /// phase-359 W10 — no longer `no_std`-only. The std build read an
2561    /// `Instant` through a separate field instead, which is how "what time is
2562    /// it" had two answers in one crate.
2563    pub(crate) clock_us_fn: Option<fn() -> u64>,
2564
2565    /// Consecutive `drive_io` failures on the PRIMARY session (issue 0324).
2566    ///
2567    /// Reset to 0 by any successful drive. A session that has died — router
2568    /// gone, lease expired, socket closed — used to keep returning `Ok(())`
2569    /// from `spin()` forever: the node looked alive, publishes went nowhere,
2570    /// and no callback fired. Nothing in the crate could report it; a
2571    /// `git grep` for a health surface found none, so every such
2572    /// investigation started from packet captures (issue 0268 burned days
2573    /// this way).
2574    ///
2575    /// A COUNTER rather than propagating the error out of `spin_once`,
2576    /// deliberately: `drive_io` returns `Err` for any non-OK backend code, and
2577    /// whether a benign poll timeout maps to one is backend-specific. Aborting
2578    /// the spin on a single failure would risk turning a transient into a dead
2579    /// node. A counter cannot regress behaviour and still makes the condition
2580    /// observable via [`Executor::session_io_failures`].
2581    pub(crate) consecutive_io_failures: u32,
2582    /// Issue 2576 — the primary session's backend said the peer no longer
2583    /// holds it (`TransportError::SessionLost`: an XRCE Agent that restarted).
2584    /// Unlike a failure the counter above tallies, this is a verdict, and it
2585    /// does not clear: the session will never do I/O again. See
2586    /// [`Executor::session_lost`].
2587    pub(crate) session_lost: bool,
2588    /// RFC-0052 W3b.2 — wall-clock (epoch µs) source for age monitors.
2589    pub(crate) epoch_us_fn: Option<fn() -> u64>,
2590    /// phase-483 W3 — the component registration frame the `nros` facade
2591    /// installs for the duration of a component's `register`, so the
2592    /// declarative entity constructors on [`Node`](super::node::Node) can reach
2593    /// the sink that owns the component's cell. Opaque here: nros-node sits
2594    /// below the crate that defines the frame. `None` outside a registration.
2595    pub(crate) component_frame: Option<core::ptr::NonNull<()>>,
2596    /// RFC-0052 W3b.4 — baked contract-monitor table (empty = uncontracted
2597    /// image; every monitor path below folds away).
2598    pub(crate) monitor_table: &'static [super::monitor::MonitorSpec],
2599    pub(crate) monitor_states: [super::monitor::MonitorState; super::monitor::MAX_MONITORS],
2600    /// Alive supervision, one record per SchedContext: dispatches are counted
2601    /// in the dispatch path where the SC index is already resolved, and read
2602    /// once per monitor tick. CARVED from the backing like `sporadic_states`.
2603    /// It began as an inline `[_; MAX_SC]` pair on the claim that `MAX_SC` is a
2604    /// build-time constant; it is a SIZING KNOB (`ExecutorSizing::sc`), so the
2605    /// header grew with it and `the_executor_value_does_not_scale_with_the_knobs`
2606    /// caught it (issue 0961).
2607    pub(crate) alive_slots: &'s mut [super::monitor::AliveSlot],
2608    /// phase-476 W0 — per-callback-slot lifetime tags, parallel to
2609    /// `entries`: the generation a handle must match, and the owning node.
2610    pub(crate) slot_tags: &'s mut [super::types::SlotTag],
2611    /// W3b.5 — baked subscriber age-contract table (empty = none).
2612    pub(crate) age_table: &'static [super::monitor::AgeMonitorSpec],
2613    pub(crate) age_states: [super::monitor::AgeState; super::monitor::MAX_AGE_MONITORS],
2614    /// phase-462 W3b — baked hazard table (empty = no contracted hazard). Its
2615    /// state lives in the rows' own `static` cells, so a hazard costs this
2616    /// value nothing.
2617    pub(crate) hazard_table: &'static [super::monitor::HazardSpec],
2618    /// phase-462 W4 -- the baked mode variants of the two monitor tables,
2619    /// index = mode id (0 = the base). Empty for an image with no modes.
2620    pub(crate) mode_tables: &'static [super::monitor::ModeTables],
2621    /// phase-462 W4 -- the last mode request this executor saw, and the mode
2622    /// whose tables it judges by. They differ only after a request for a mode
2623    /// this executor has no table for.
2624    pub(crate) mode_seen: u16,
2625    /// phase-462 W4c -- monotonic ms of the previous mode check, the start
2626    /// of the window a request seen at this one could have waited in.
2627    pub(crate) mode_checked_ms: Option<u32>,
2628    pub(crate) mode_applied: u16,
2629    /// W3b.5 — hook invoked on `DeadlineAction::Fault` (panic when unset).
2630    pub(crate) fault_fn: Option<fn(&super::monitor::Violation)>,
2631    /// phase-503 — the reaction hook and its context: called when a
2632    /// supervised route passes its deadline (`route-deadline-runtime`), and on
2633    /// `DeadlineAction::Fault` when no `fault_fn` is set.
2634    pub(crate) reaction_hook: Option<(super::monitor::ReactionHookFn, *mut core::ffi::c_void)>,
2635    /// phase-509 P9b (RFC-0108 "As built in P9b") -- the lock every path that
2636    /// touches this executor takes once a second thread can reach it (one
2637    /// worker per level over one executor). `None` -- every one-level image --
2638    /// makes each guard a no-op. Read through a raw pointer by
2639    /// [`super::exec_lock::ExecGuard::acquire`], so it is written only while
2640    /// no second thread exists.
2641    pub(crate) exec_lock: Option<super::exec_lock::ExecLock>,
2642    /// phase-509 P9b item 2 -- the callbacks running in an open window, one
2643    /// record per window, each in its pass's frame (`exec_lock::Running`).
2644    /// Read and written only under the lock; null while no window is open.
2645    pub(crate) running: *mut super::exec_lock::Running,
2646    /// Issue #515 — the spin cadence audit runs once, on the first spin
2647    /// that carries a non-zero timeout (which is where the sched task's
2648    /// declared spin period becomes visible to the executor).
2649    pub(crate) spin_quantization_checked: bool,
2650    /// phase-436 W1 — the cadence the quantization audit (issue 0515) actually
2651    /// ran against. Recorded because the audit only LOGS: without this a
2652    /// regression that fed it the wrong number is invisible to a test, and
2653    /// capping the park by the timer deadline is exactly such a regression
2654    /// waiting to happen.
2655    pub(crate) spin_quantization_us: u64,
2656    /// Release jitter: worst observed lateness of a `spin_period` wake
2657    /// against its own nominal schedule, in microseconds.
2658    ///
2659    /// Issue #515 added a STATIC audit for one cause of cadence error --
2660    /// a period that is not a multiple of the spin period. Nothing measured
2661    /// the actual release instants, and `audit_spin_quantization` says so in
2662    /// as many words: "the rate is preserved and no activation is dropped,
2663    /// so every runtime rule is (correctly) silent -- the jitter stays
2664    /// invisible until someone measures cadence on target."
2665    ///
2666    /// This is that measurement, and it is the one `cyclictest` exists to
2667    /// report: the deviation between a timer's programmed wake-up and the
2668    /// instant the task actually resumed, whose MAXIMUM is the figure of
2669    /// merit for a real-time system.
2670    ///
2671    /// `spin_period` already holds both numbers -- `next_us` is the nominal
2672    /// deadline and `now_us()` the actual -- and when the loop is late it
2673    /// skips the sleep and discards the difference. That difference is the
2674    /// jitter.
2675    pub(crate) max_release_jitter_us: u64,
2676    /// Clock reading at the previous `spin_once` entry, for the interval the
2677    /// jitter is measured over. `None` until the first spin, and reset by
2678    /// `clear_release_jitter_stats` so a window starts clean.
2679    pub(crate) last_spin_entry_us: Option<u64>,
2680    /// phase-474 I11 -- the release grid of a `spin_once(timeout)` loop with
2681    /// no declared cadence. See [`ReleaseGrid`].
2682    pub(crate) grid: ReleaseGrid,
2683    /// Jitter high-water at the previous `release-jitter-runtime` check, so
2684    /// the rule reports the DELTA. Same shape as `overruns_reported` on a
2685    /// timer header, and for the same reason: a maximum that has not moved
2686    /// is the fault already reported, not a new one.
2687    pub(crate) jitter_reported_us: u64,
2688    /// phase-509 P6 (RFC-0108 D3) -- this executor's one worker: its band
2689    /// (every dispatch level), its park (RFC-0106) and its stack record. The
2690    /// fields moved here from the executor unchanged; `Executor` is the
2691    /// one-level facade over the scheduler / worker split.
2692    pub(crate) worker: super::scheduler::Worker,
2693    /// The pacing quantum the spin loop was last driven at, in microseconds.
2694    /// This is the bound the jitter rule judges against -- the caller's own
2695    /// declared cadence, so nothing further has to be declared.
2696    pub(crate) spin_nominal_us: u64,
2697    /// Cadence DECLARED by the driver, in microseconds; `0` = not declared.
2698    ///
2699    /// Takes precedence over the `spin_once` timeout when judging release
2700    /// jitter, because the two are not the same quantity. The timeout is how
2701    /// long a spin may BLOCK waiting for work; the cadence is how often the
2702    /// loop intends to come round. A driver that blocks up to 10 ms and then
2703    /// sleeps 30 ms has a 30 ms cadence and a 10 ms timeout, and judging it
2704    /// against the timeout reports a loop that is late on every single wake.
2705    pub(crate) spin_nominal_declared_us: u64,
2706    /// phase-436 A2b -- the declared cadence is met by the `spin_once` WAIT
2707    /// itself (`set_spin_nominal_wait_paced_us`), not by a sleep the caller
2708    /// adds between spins (`set_spin_nominal_us`). A wait-paced cadence runs
2709    /// on the release grid and is worth one park granule; a self-paced one is
2710    /// judged from entry to entry and is worth a microsecond.
2711    pub(crate) spin_nominal_wait_paced: bool,
2712    /// Wakes that were already past their nominal deadline, and wakes total.
2713    ///
2714    /// The maximum alone cannot distinguish one bad wake from a loop that is
2715    /// late every single cycle, and those are different faults: the first is
2716    /// a glitch, the second means the period cannot be met at all.
2717    pub(crate) late_wakes: u32,
2718    pub(crate) total_wakes: u32,
2719    /// phase-436 A2c -- late wakes whose lateness exceeds the granularity the
2720    /// measurement was made at (`release_jitter_granularity_us`). On a loop
2721    /// paced by a tick-granular park nearly every wake is late by a fraction
2722    /// of a tick, by design; `late_wakes` counts those, this does not.
2723    pub(crate) late_wakes_beyond_granule: u32,
2724    /// Issue 0514 / 1635 / phase-474 I1 -- what happens to a detected contract
2725    /// violation: the log switch, the drain-and-report hook, the image's sink,
2726    /// and the ring (CARVED, phase-409) with its total and dropped counters.
2727    /// See [`super::monitor::ViolationChannel`].
2728    pub(crate) violations: super::monitor::ViolationChannel<'s>,
2729    /// RFC-0128 D8 (phase-554 W3 slice B) -- an executor-level entity whose
2730    /// open waits for the PRIMARY node: `(hook, ctx, arg)`, installed by
2731    /// [`Self::open_on_primary_node`] and taken by the node table the moment
2732    /// `NodeId::PRIMARY` is registered. The `/diagnostics` reporter is armed
2733    /// before any node exists, and its publisher belongs to the primary node.
2734    pub(crate) primary_node_hook: Option<(PrimaryNodeHook, usize, u32)>,
2735    /// Issue 0790 — hooks that run BEFORE the session is closed, while every
2736    /// entity still works. The load-bearing half: a device releasing a bus or
2737    /// parking an actuator has to publish its final state / answer its last
2738    /// request from HERE, because after teardown it cannot.
2739    ///
2740    /// `[Option<_>; N]` rather than a `heapless::Vec`, deliberately: the handle
2741    /// a caller holds IS the slot index, so a removal must leave every other
2742    /// index where it was. A `Vec`'s `swap_remove` would silently re-point one
2743    /// live handle at a different callback, and its `remove` would re-point all
2744    /// of them. Clearing a slot to `None` also lets the next registration reuse
2745    /// it, which a fill cursor could not.
2746    pub(crate) pre_shutdown_hooks:
2747        [Option<super::types::ShutdownHook>; crate::config::MAX_SHUTDOWN_CBS],
2748    /// Issue 0790 — hooks that run AFTER the session is closed. rclcpp's
2749    /// `add_on_shutdown_callback` / `rclcpp::on_shutdown`. See
2750    /// [`Self::pre_shutdown_hooks`] for why this is an array.
2751    pub(crate) on_shutdown_hooks:
2752        [Option<super::types::ShutdownHook>; crate::config::MAX_SHUTDOWN_CBS],
2753    /// Issue 2576 — the default backing an `alloc` open took, given back when
2754    /// the executor drops so a re-open reuses it. MUST stay the LAST field:
2755    /// fields drop in declaration order, and it may only drop once nothing
2756    /// else can reach the arena. See [`super::backing::OwnedBacking`].
2757    #[cfg(all(any(has_rmw, test), feature = "alloc", feature = "rmw-cffi"))]
2758    pub(crate) owned_backing: super::backing::OwnedBacking,
2759}
2760
2761impl<'s> Executor<'s> {
2762    /// phase-271 — assemble an executor over already-carved, caller-owned
2763    /// storage (`slices`, from [`super::storage::carve`]). Fills every
2764    /// non-storage field and reserves SC slot 0 for the default Fifo SC (carve
2765    /// left it `None`). The single builder shared by every constructor path.
2766    fn assemble(session: SessionStore, slices: super::storage::ExecutorSlices<'s>) -> Self {
2767        let super::storage::ExecutorSlices {
2768            arena,
2769            entries,
2770            sched_contexts,
2771            sched_context_bindings,
2772            sporadic_states,
2773            #[cfg(feature = "alloc")]
2774            sporadic_atomic_states,
2775            remaps,
2776            nodes,
2777            extra_sessions,
2778            extra_session_ids,
2779            node_sched_table,
2780            component_slots,
2781            active_groups,
2782            group_sched_table,
2783            monitor_violations,
2784            alive_slots,
2785            slot_tags,
2786            params: param_slots,
2787            param_home,
2788        } = slices;
2789        // phase-382 W3' — only an executor that can build a store keeps the
2790        // carved slots; without `param-services` the region (sized by the
2791        // build, not by a feature, so the layout never depends on one) is
2792        // simply never initialised. The services' home (issue 1812) is
2793        // zero-sized without the feature.
2794        #[cfg(not(feature = "param-store"))]
2795        let _ = (param_slots, param_home);
2796        // Slot 0 = the auto-created default Fifo SC (see field doc). carve
2797        // initialised the whole table to `None`; populate the reserved slot.
2798        if let Some(slot0) = sched_contexts.first_mut() {
2799            *slot0 = Some(super::sched_context::SchedContext::default());
2800        }
2801        // phase-412 -- stamp the self-report before anything can fail. `init`
2802        // is idempotent, so an image with two executors need not decide which
2803        // one owns the record, and `note_arena_capacity` records the slice this
2804        // executor was actually handed rather than the compiled constant: the
2805        // arena's placement is the caller's choice (issue 0900), so the two can
2806        // legitimately differ and the difference is worth seeing.
2807        crate::boot_report::init();
2808        crate::boot_report::note_arena_capacity(arena.len());
2809        crate::boot_report::checkpoint(crate::boot_report::Stage::ExecutorReady);
2810        Self {
2811            // `assemble` is reached from session-only entry points that have no
2812            // config, so 0 is the floor rather than a choice; `open_in` and any
2813            // binding that knows better overwrite it via `set_domain_id`.
2814            domain_id: 0,
2815            session,
2816            arena: ArenaRef::new(arena),
2817            arena_used: 0,
2818            arena_free_head: ARENA_FREE_NONE,
2819            pending_region: None,
2820            entries,
2821            sched_contexts,
2822            sched_context_bindings,
2823            sporadic_states,
2824            #[cfg(feature = "alloc")]
2825            sporadic_atomic_states,
2826            major_frame_us: 0,
2827            trigger: Trigger::Any,
2828            semantics: ExecutorSemantics::RclcppExecutor,
2829            node_name: heapless::String::new(),
2830            active_groups,
2831            active_groups_filtering: false,
2832            nodes,
2833            node_sched_table,
2834            group_sched_table,
2835            remap_table: remaps,
2836            remap_len: 0,
2837            launch_remaps: None,
2838            component_slots,
2839            deferred_mask: super::slot_mask::SlotMask::EMPTY,
2840            deferred_pending: super::slot_mask::SlotMask::EMPTY,
2841            defer_notify: None,
2842            extra_sessions,
2843            extra_session_ids,
2844            primary_rmw_name: heapless::String::new(),
2845            primary_locator: heapless::String::new(),
2846            namespace: {
2847                let mut ns = heapless::String::new();
2848                let _ = ns.push_str("/");
2849                ns
2850            },
2851            // Issue 1177 -- the only cfg the halt flag still needs. `HaltFlag`
2852            // is refcounted with an allocator and plain without one, and
2853            // nothing below this line can tell the difference.
2854            #[cfg(feature = "alloc")]
2855            halt_flag: portable_atomic_util::Arc::new(portable_atomic::AtomicBool::new(false)),
2856            #[cfg(not(feature = "alloc"))]
2857            halt_flag: portable_atomic::AtomicBool::new(false),
2858            spinning: portable_atomic::AtomicBool::new(false),
2859            #[cfg(feature = "alloc")]
2860            wake_flag: portable_atomic_util::Arc::new(portable_atomic::AtomicBool::new(false)),
2861            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2862            node_wake: super::node_wake::NodeWake::new().map(portable_atomic_util::Arc::new),
2863            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2864            wake_ctx: None,
2865            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2866            wake_cb_installed: false,
2867            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2868            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2869            wake_membership: None,
2870            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2871            graph_change_target: None,
2872            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2873            has_async_wake: false,
2874            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2875            entity_attributed: super::slot_mask::SlotMask::EMPTY,
2876            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2877            entity_recheck: super::slot_mask::SlotMask::EMPTY,
2878            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2879            entity_status_polled: super::slot_mask::SlotMask::EMPTY,
2880            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
2881            readiness_probes: 0,
2882            // Phase 141.A.3 — alloc-mode wake state init. Constructed
2883            // eagerly (NodeWake allocation) so the runtime cb can be
2884            // installed lazily on first session without a fallible
2885            // alloc inside spin_once. `None` when the platform
2886            // provider reports the primitive unavailable (matches
2887            // the std-RTOS path's `node_wake: Option<...>`).
2888            #[cfg(all(feature = "signal-fd-wake", target_os = "linux"))]
2889            signal_fd: None,
2890            #[cfg(feature = "param-store")]
2891            params: None,
2892            #[cfg(feature = "param-store")]
2893            param_slots,
2894            #[cfg(feature = "param-store")]
2895            param_home,
2896            #[cfg(feature = "param-store")]
2897            param_store_refused: false,
2898            #[cfg(feature = "param-store")]
2899            declared_params: nros_params::DeclaredParams::EMPTY,
2900            #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2901            sim_time_source: None,
2902            #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2903            sim_time_requested: false,
2904            #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2905            sim_time_stated: false,
2906            #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
2907            sim_time_silence: crate::time_source::SilenceWatch::new(),
2908            #[cfg(feature = "lifecycle-services")]
2909            lifecycle: alloc::vec::Vec::new(),
2910            // Initialise the spin endpoint to construction time so the
2911            // very first `spin_once` credits time the caller spent
2912            // *before* it (e.g. setup, an explicit pre-spin sleep) just
2913            // like time spent between later calls.
2914            // One field, one seed now (phase-359 W10): the clock is absolute
2915            // on every flavour, so it is READ here rather than assumed to be
2916            // zero at construction. The std arm used to seed `Some(0)` because
2917            // its epoch WAS construction; with one provider that special case
2918            // is gone.
2919            last_spin_end_us: default_clock_us_fn().map(|clock| clock()),
2920            clock_us_fn: default_clock_us_fn(),
2921            consecutive_io_failures: 0,
2922            session_lost: false,
2923            // RFC-0052 W3b.5 — a build with a wall clock gets one by default so
2924            // age monitors activate without extra wiring; a build with neither a
2925            // platform port nor a host gets `None`, and its board installs
2926            // `config.epoch_us` in `from_session_in`/`open`.
2927            //
2928            // phase-359 W10 — the cfg pair that used to be here moved into
2929            // `default_epoch_us_fn`, beside the `default_clock_us_fn` it
2930            // mirrors. (The old comment pointed at "the `not(std)` blocks
2931            // above" for the board install; those blocks are no longer
2932            // cfg-gated — the config override applies on every flavour now.)
2933            epoch_us_fn: super::types::default_epoch_us_fn(),
2934            component_frame: None,
2935            monitor_table: &[],
2936            monitor_states: [super::monitor::MonitorState::default(); super::monitor::MAX_MONITORS],
2937            age_table: &[],
2938            age_states: [super::monitor::AgeState::default(); super::monitor::MAX_AGE_MONITORS],
2939            hazard_table: &[],
2940            mode_tables: &[],
2941            mode_seen: 0,
2942            mode_checked_ms: None,
2943            mode_applied: 0,
2944            fault_fn: None,
2945            reaction_hook: None,
2946            exec_lock: None,
2947            running: core::ptr::null_mut(),
2948            spin_quantization_checked: false,
2949            reprobe_each_callback: REPROBE_EACH_CALLBACK_DEFAULT,
2950            spin_quantization_us: 0,
2951            max_release_jitter_us: 0,
2952            last_spin_entry_us: None,
2953            grid: ReleaseGrid {
2954                period_us: 0,
2955                next_us: 0,
2956                skipped: 0,
2957            },
2958            jitter_reported_us: 0,
2959            worker: super::scheduler::Worker::one_level(),
2960            spin_nominal_us: 0,
2961            spin_nominal_declared_us: 0,
2962            spin_nominal_wait_paced: false,
2963            late_wakes: 0,
2964            total_wakes: 0,
2965            late_wakes_beyond_granule: 0,
2966            violations: super::monitor::ViolationChannel::new(monitor_violations),
2967            primary_node_hook: None,
2968            alive_slots,
2969            slot_tags,
2970            // Issue 0790 — both phase tables start empty. An image that
2971            // registers nothing pays these `None`s and a two-slot scan at
2972            // teardown, and nothing else.
2973            pre_shutdown_hooks: [None; crate::config::MAX_SHUTDOWN_CBS],
2974            on_shutdown_hooks: [None; crate::config::MAX_SHUTDOWN_CBS],
2975            #[cfg(all(any(has_rmw, test), feature = "alloc", feature = "rmw-cffi"))]
2976            owned_backing: super::backing::OwnedBacking::NONE,
2977        }
2978    }
2979
2980    /// Create an owning executor over caller-supplied `backing`, sized by
2981    /// `sizing`. The core, non-generic, per-entry entry point (the `alloc`
2982    /// [`from_session`](Self::from_session) convenience leaks a default backing
2983    /// and calls this; the macro / C FFI pass an entry-sized backing).
2984    ///
2985    /// # Safety
2986    /// `backing` must be ≥ `sizing.u64_len()` words, stay alive for `'s`, and
2987    /// not be otherwise accessed while the executor lives (it aliases it).
2988    /// A `sizing.cbs` above `MAX_CALLBACK_SLOTS` (the slot masks' width)
2989    /// carves that many slots (`storage::callback_slots`), issue 2541.
2990    pub(crate) unsafe fn from_session_in(
2991        session: session::ConcreteSession,
2992        backing: &'s mut [MaybeUninit<u64>],
2993        sizing: super::storage::ExecutorSizing,
2994    ) -> Self {
2995        let slices = unsafe { super::storage::carve(backing, sizing) };
2996        Self::assemble(SessionStore::owned(session), slices)
2997    }
2998
2999    /// Create a borrowing executor over caller-supplied `backing`, sized by
3000    /// `sizing`. Counterpart to [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in) for
3001    /// the per-sched-task / C model (the session is borrowed, not owned).
3002    ///
3003    /// # Safety
3004    /// - `session_ptr` must point to a valid session that outlives the executor
3005    ///   and is not moved/dropped while it exists.
3006    /// - `backing` obligations as in [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in).
3007    pub(crate) unsafe fn from_session_ptr_in(
3008        session_ptr: *mut session::ConcreteSession,
3009        backing: &'s mut [MaybeUninit<u64>],
3010        sizing: super::storage::ExecutorSizing,
3011    ) -> Self {
3012        let slices = unsafe { super::storage::carve(backing, sizing) };
3013        Self::assemble(SessionStore::Borrowed(session_ptr), slices)
3014    }
3015}
3016
3017impl Executor<'static> {
3018    /// Create an executor from an already-opened session, using the build-time
3019    /// default sizing (`MAX_CBS`/`MAX_SC`/`ARENA_SIZE`). Convenience for
3020    /// std/alloc callers that don't size per-entry: it leaks a default-sized
3021    /// backing (executor-lifetime, one-time) and calls
3022    /// [`from_session_in`](crate::executor::ffi::ExecutorFfi::from_session_in). Per-entry sizing goes through
3023    /// the macro / `open_in` instead.
3024    #[cfg(feature = "alloc")]
3025    pub fn from_session(session: session::ConcreteSession) -> Self {
3026        let sizing = super::storage::ExecutorSizing::DEFAULT;
3027        // SAFETY: the backing is exactly `sizing.u64_len()` words,
3028        // `'static`, and uniquely owned by this executor.
3029        unsafe { Self::from_session_in(session, default_backing(sizing), sizing) }
3030    }
3031
3032    /// [`from_session`](Self::from_session) with an [`ExecutorConfig`], so a
3033    /// caller that brings its own session can also bring its own clock.
3034    ///
3035    /// `from_session` takes no config, and that is
3036    /// the path the no-port population uses: it accepts any `Session`, so a
3037    /// consumer with a non-cffi backend reaches the executor through it and had
3038    /// NO way to install `clock_us`. An earlier change argued the `std`-without-a-
3039    /// port clock fallbacks could go because "a caller with a clock installs it
3040    /// through `ExecutorConfig::clock_us`" — true for `open`, false here, which
3041    /// is half of why that deletion was reverted.
3042    ///
3043    /// Only the timing sources are read from `config`; identity (locator,
3044    /// domain, names) belongs to the session the caller already opened. As in
3045    /// [`open_in`](Self::open_in), a `None` field does NOT clobber the
3046    /// platform default — it means "not specified" (an earlier bug).
3047    #[cfg(feature = "alloc")]
3048    pub fn from_session_with(
3049        session: session::ConcreteSession,
3050        config: &super::types::ExecutorConfig<'_>,
3051    ) -> Self {
3052        let mut executor = Self::from_session(session);
3053        if let Some(clock) = config.clock_us {
3054            executor.clock_us_fn = Some(clock);
3055            executor.last_spin_end_us = Some(clock());
3056        }
3057        if let Some(epoch) = config.epoch_us {
3058            executor.epoch_us_fn = Some(epoch);
3059        }
3060        executor
3061    }
3062
3063    /// Create an executor from a borrowed session pointer, default-sized. The
3064    /// `alloc` convenience wrapper over
3065    /// [`from_session_ptr_in`](Self::from_session_ptr_in) — leaks a default
3066    /// backing so existing callers keep the zero-storage-arg signature.
3067    ///
3068    /// # Safety
3069    /// - `session_ptr` must point to a valid, initialized session that lives at
3070    ///   least as long as this executor.
3071    /// - The caller must not move or drop the session while the executor exists.
3072    #[cfg(feature = "alloc")]
3073    pub(crate) unsafe fn from_session_ptr(session_ptr: *mut session::ConcreteSession) -> Self {
3074        let sizing = super::storage::ExecutorSizing::DEFAULT;
3075        // SAFETY: the backing as in `from_session`; session_ptr contract
3076        // forwarded to `from_session_ptr_in`.
3077        unsafe { Self::from_session_ptr_in(session_ptr, default_backing(sizing), sizing) }
3078    }
3079}
3080
3081/// phase-474 I11 -- the release grid of a `spin_once(timeout)` loop with no
3082/// declared cadence: the period it was built for (`0` = no grid yet), the next
3083/// scheduled release, and the releases skipped because the loop came back a
3084/// whole period or more after they were due (the timer `Skip` policy: the
3085/// latest due point is served once, the older ones are dropped and counted,
3086/// never released in a burst). The park is bounded by `next_us`, so a loop is
3087/// released on `anchor + k * period` instead of `period` after its previous
3088/// spin ended. Scales with no knob; named in the header-size budget.
3089#[derive(Clone, Copy, Debug, Default)]
3090pub(crate) struct ReleaseGrid {
3091    pub(crate) period_us: u64,
3092    pub(crate) next_us: u64,
3093    pub(crate) skipped: u32,
3094}
3095
3096/// The two cadences a `period_us` timer alternates between under a `spin_us`
3097/// spin period, or `None` when the audit (issue #515) has nothing to say.
3098///
3099/// Split out of `audit_spin_quantization` so the decision can be asserted:
3100/// the audit only LOGS, so a regression in what it decides is otherwise
3101/// invisible to a test.
3102///
3103/// `None` for a period of zero, for a period that divides the spin period —
3104/// and, since issue 1321, for a timer whose activations are NOT paced by the
3105/// spin period at all. The warning's arithmetic is wall microseconds on both
3106/// sides; a `Ros` timer's activations are quantised by the `/clock` STEP, so
3107/// the sentence it would print ("activations will alternate between X and Y
3108/// us") is about nothing.
3109pub(crate) fn spin_quantization_span(
3110    clock_source: TimerClockSource,
3111    period_us: u64,
3112    spin_us: u64,
3113) -> Option<(u64, u64)> {
3114    if spin_us == 0 || period_us == 0 || period_us.is_multiple_of(spin_us) {
3115        return None;
3116    }
3117    // phase-521 W6 — an entry's idle budget is no cadence: its park ends at
3118    // each timer's own deadline, so nothing quantizes.
3119    if spin_us >= ENTRY_IDLE_BUDGET.as_micros() as u64 {
3120        return None;
3121    }
3122    if !clock_source.remaining_is_wall_time() {
3123        return None;
3124    }
3125    let early_us = (period_us / spin_us) * spin_us;
3126    Some((early_us, early_us.saturating_add(spin_us)))
3127}
3128
3129/// Which deadline source bounded the last park.
3130///
3131/// Attribution is what turns "why did we wake" from a guess into a number.
3132/// Recording it costs one byte per spin and is the difference between a
3133/// schedulability argument you can audit and one you have to trust.
3134#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3135#[repr(u8)]
3136pub enum WakeSourceId {
3137    /// The `spin_once` caller's own timeout — always a member of the source
3138    /// set, which is why the park is never unbounded.
3139    CallerBudget,
3140    /// A registered timer's next expiry (issue 1192).
3141    Timer,
3142    /// The backend's next internal event (lease keepalive, heartbeat,
3143    /// ACK-NACK). Folded into the same `min` as everything else rather than
3144    /// capping the budget separately upstream, so one rule decides the park
3145    /// and one attribution explains it.
3146    Session,
3147    /// A source the PLATFORM registered: a `k_poll` event set, an `epoll`
3148    /// group, a FreeRTOS queue set, a ThreadX event-flags group, or a
3149    /// bare-metal device ISR. The core never names an RTOS; it only asks each
3150    /// registered source when it will next need the executor.
3151    Platform(u8),
3152    /// phase-503 — the earliest deadline of a pending supervised route: the
3153    /// park ends there so `route-deadline-runtime` judges it on time.
3154    RouteDeadline,
3155}
3156
3157/// How many platform sources one executor can carry. A plain const, not a
3158/// sizing knob: the table is inline, so no allocator is required on the no_std
3159/// targets this seam mainly exists for.
3160pub const MAX_WAKE_SOURCES: usize = 8;
3161
3162/// phase-521 W3 -- the most `ReadinessSource::Waitable` handles one park
3163/// multiplexes: one per session of a sched task, and the POSIX port's own cap.
3164#[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
3165pub(crate) const MAX_WAITABLE_HANDLES: usize = 8;
3166
3167/// When this source will next need the executor, in the executor's clock,
3168/// as microseconds FROM NOW.
3169///
3170/// `u64::MAX` means "nothing pending" — the source does not shorten the park.
3171/// That is how an ASYNC source spells itself: a socket or a DDS listener
3172/// contributes no deadline and instead breaks the park by signalling the wake
3173/// primitive, so async and deadline sources compose without a second
3174/// mechanism.
3175pub type NextDeadlineFn = unsafe extern "C" fn(ctx: *mut core::ffi::c_void) -> u64;
3176
3177/// Park until `deadline_us` from now, or until something signals, whichever
3178/// comes first.
3179///
3180/// Returns [`PARK_SIGNALLED`] (`0`) when woken by an event, [`PARK_EXPIRED`]
3181/// (`1`) when the deadline expired, [`PARK_YIELDED`] (`2`) when the slot did
3182/// not wait but handed the wait to its framework's scheduler, and a negative
3183/// value when this build cannot park at all.
3184///
3185/// The YIELDED answer is
3186/// how a tier that a framework schedules waits: a PX4 tier's slot arms its
3187/// work item's `ScheduleDelayed(deadline_us)` (or `ScheduleClear()` when the
3188/// bound is the caller's budget alone) and returns at once, and `spin_once`
3189/// then returns to the work queue instead of blocking. An arrival reaches the
3190/// sched task through `ScheduleNow()`. No executor API widens for it: the bound the
3191/// slot receives is the one every park receives.
3192///
3193/// A DEADLINE, not a duration, and that distinction is what makes bare metal
3194/// work: `nros-baremetal-common`'s own note says `wfi` with no pending
3195/// interrupt deadlocks, so a board must arm a timer compare BEFORE waiting.
3196/// A `sleep(duration)` seam cannot express that — the sleeper does not know
3197/// whether anyone armed an interrupt. A `ParkUntilFn` does, because the
3198/// deadline is exactly what the compare is armed to.
3199pub type ParkUntilFn = unsafe extern "C" fn(ctx: *mut core::ffi::c_void, deadline_us: u64) -> i8;
3200
3201/// The wake half of a framework's park slot:
3202/// called after every signal of the executor's wake object, from the
3203/// signalling context. A framework whose tier is a scheduled item rather than
3204/// a parked thread (a PX4 work item) re-schedules the sched task here. Must be
3205/// thread-safe, non-blocking and O(1).
3206pub type WakeHookFn = unsafe extern "C" fn(ctx: *mut core::ffi::c_void);
3207
3208/// [`ParkUntilFn`]: woken by an event (`NROS_PLATFORM_PARK_SIGNALLED`).
3209pub const PARK_SIGNALLED: i8 = 0;
3210/// [`ParkUntilFn`]: the deadline expired (`NROS_PLATFORM_PARK_EXPIRED`).
3211pub const PARK_EXPIRED: i8 = 1;
3212/// [`ParkUntilFn`]: the slot handed the wait to its framework's scheduler and
3213/// returned without waiting (`NROS_PLATFORM_PARK_YIELDED`); `spin_once`
3214/// returns without dispatching. See [`ParkUntilFn`].
3215pub const PARK_YIELDED: i8 = 2;
3216
3217/// A registered deadline contributor.
3218#[derive(Clone, Copy)]
3219pub(crate) struct WakeSourceSlot {
3220    pub(crate) next: NextDeadlineFn,
3221    pub(crate) ctx: *mut core::ffi::c_void,
3222}
3223
3224impl<'s> Executor<'s> {
3225    /// Construct a sched task's executor that **shares**
3226    /// a session opened once by the orchestration `main()`.
3227    ///
3228    /// In the per-sched-task execution model `main()` opens one RMW session, then
3229    /// spawns one RTOS task per priority sched task; each task calls this to get an
3230    /// [`Executor`] over the *same* session (the `Borrowed` session store — this
3231    /// executor neither owns nor closes it), registers its sched task's callback
3232    /// groups, and spins. Thin alias over [`ExecutorFfi::from_session_ptr`](crate::executor::ffi::ExecutorFfi::from_session_ptr).
3233    ///
3234    /// # Safety
3235    /// `session` must outlive every executor/task built from it (the
3236    /// orchestration `main()` holds it and never returns / WFIs), and must not
3237    /// be mutated except through these executors' spin calls.
3238    #[cfg(feature = "alloc")]
3239    pub unsafe fn open_with_session(session: *mut session::ConcreteSession) -> Executor<'static> {
3240        #[allow(unused_mut)]
3241        let mut exec = unsafe { Executor::<'static>::from_session_ptr(session) };
3242        // phase-436 — join the session's wake fan-out, so this sched task is woken
3243        // by its arrivals instead of sleeping out its whole bound.
3244        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
3245        exec.install_wake_signal_on_primary();
3246        exec
3247    }
3248
3249    /// phase-271 — per-sched-task borrowed-session constructor over caller-supplied,
3250    /// per-sched-task-sized `backing`. The sized counterpart to
3251    /// [`open_with_session`](Self::open_with_session): each RTOS sched task owns
3252    /// its own backing so sched tasks size independently.
3253    ///
3254    /// # Safety
3255    /// `session` obligations as in [`open_with_session`](Self::open_with_session);
3256    /// `backing`/`sizing` as in [`from_session_ptr_in`](Self::from_session_ptr_in).
3257    pub(crate) unsafe fn open_with_session_in(
3258        session: *mut session::ConcreteSession,
3259        backing: &'s mut [MaybeUninit<u64>],
3260        sizing: super::storage::ExecutorSizing,
3261    ) -> Self {
3262        #[allow(unused_mut)]
3263        let mut exec = unsafe { Self::from_session_ptr_in(session, backing, sizing) };
3264        // phase-436 — as `open_with_session`.
3265        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
3266        exec.install_wake_signal_on_primary();
3267        exec
3268    }
3269
3270    // Phase-573 W3 -- the `None` case below.
3271    /// Raw pointer to this executor's RMW session, for the per-sched-task model:
3272    /// the boot task opens the one session via [`Executor::open`] (the RMW
3273    /// session is a process-wide singleton — opening twice fails), then hands
3274    /// this pointer to each spawned sched task's
3275    /// [`Executor::open_with_session`]. The boot task's executor owns the
3276    /// session and outlives every borrower, so the pointer stays valid for the
3277    /// program's life.
3278    ///
3279    /// `None` when the session may not be shared: an owned session held inline
3280    /// because its own allocation failed. A pointer into the
3281    /// owner would be disabled by the owner's next write, so a sched task gets
3282    /// no session rather than a dangling one.
3283    ///
3284    /// # Safety
3285    /// The returned pointer aliases `self.session`. Callers must keep `self`
3286    /// alive (not dropped) for as long as any sched task executor uses the
3287    /// pointer, and must only touch the session through executor spin calls
3288    /// (the RMW backend serializes concurrent access through its own locks).
3289    pub fn session_ptr(&mut self) -> Option<*mut session::ConcreteSession> {
3290        let ptr = self.session.shareable_ptr()?;
3291        // phase-436 — the owner of an OWNED session claimed its wake fan-out
3292        // while this executor value could still move (inside `open*`). The
3293        // address handed out here is the one every sched task is opened over, so
3294        // the entry is keyed by it from now on.
3295        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
3296        if let (true, Some(m)) = (self.session.is_owned(), self.wake_membership) {
3297            m.fanout().rekey(ptr as *mut core::ffi::c_void);
3298        }
3299        Some(ptr)
3300    }
3301
3302    /// Opaque, `Send` form of [`session_ptr`](Self::session_ptr) — the per-sched-task
3303    /// model hands this to each spawned sched task (it can cross the RTOS task /
3304    /// thread boundary, which a bare `*mut` cannot). See [`SessionHandle`].
3305    ///
3306    /// # Safety
3307    /// Same contract as [`session_ptr`](Self::session_ptr): `self` (the session
3308    /// owner) must outlive every executor built from the handle. `None` where
3309    /// `session_ptr` is.
3310    pub fn session_handle(&mut self) -> Option<SessionHandle> {
3311        self.session_ptr().map(SessionHandle)
3312    }
3313
3314    /// Open an [`Executor`] over the session a [`SessionHandle`] refers to (the
3315    /// `Borrowed` store — neither owns nor closes it). The sched-task counterpart
3316    /// to [`session_handle`](Self::session_handle).
3317    ///
3318    /// # Safety
3319    /// The handle's session must still be alive (its owning executor not moved
3320    /// or dropped); access only through executor spin calls.
3321    #[cfg(feature = "alloc")]
3322    pub unsafe fn open_with_session_handle(handle: SessionHandle) -> Executor<'static> {
3323        unsafe { Executor::<'static>::open_with_session(handle.0) }
3324    }
3325
3326    /// phase-271 — sized counterpart to
3327    /// [`open_with_session_handle`](Self::open_with_session_handle) (per-sched-task
3328    /// backing).
3329    ///
3330    /// # Safety
3331    /// As [`open_with_session_handle`](Self::open_with_session_handle) +
3332    /// [`from_session_ptr_in`](Self::from_session_ptr_in).
3333    pub(crate) unsafe fn open_with_session_handle_in(
3334        handle: SessionHandle,
3335        backing: &'s mut [MaybeUninit<u64>],
3336        sizing: super::storage::ExecutorSizing,
3337    ) -> Self {
3338        unsafe { Self::open_with_session_in(handle.0, backing, sizing) }
3339    }
3340
3341    /// issue 1571 — a SPAWNED sched task's executor over its slot of the entry's
3342    /// [`SchedTaskExecutorBacking`](super::SchedTaskExecutorBacking) — the road every
3343    /// board's `run_sched_tasks` takes for each sched task but the boot one.
3344    ///
3345    /// The slot's TYPE is the size: it is `ExecutorSizing::DEFAULT.u64_len()`
3346    /// words and this opens with `ExecutorSizing::DEFAULT`, so the pairing is
3347    /// exact by construction and lives here, once, rather than at five boards.
3348    /// [`open_with_session`](Self::open_with_session) is the heap twin this
3349    /// replaced on those roads.
3350    ///
3351    /// # Safety
3352    /// `session` obligations as in [`open_with_session`](Self::open_with_session).
3353    #[cfg(feature = "alloc")]
3354    pub(crate) unsafe fn open_with_session_slot(
3355        session: *mut session::ConcreteSession,
3356        slot: &'s mut super::SchedTaskExecutorBackingSlot,
3357    ) -> Self {
3358        unsafe {
3359            Self::open_with_session_in(
3360                session,
3361                &mut slot[..],
3362                super::storage::ExecutorSizing::DEFAULT,
3363            )
3364        }
3365    }
3366
3367    /// issue 1571 — [`open_with_session_slot`](Self::open_with_session_slot)
3368    /// over a [`SessionHandle`], for the boards whose sched tasks carry one.
3369    ///
3370    /// # Safety
3371    /// As [`open_with_session_handle`](Self::open_with_session_handle).
3372    #[cfg(feature = "alloc")]
3373    pub(crate) unsafe fn open_with_session_handle_slot(
3374        handle: SessionHandle,
3375        slot: &'s mut super::SchedTaskExecutorBackingSlot,
3376    ) -> Self {
3377        unsafe { Self::open_with_session_slot(handle.0, slot) }
3378    }
3379
3380    /// Set this sched task executor's active callback-group filter. The
3381    /// generated per-sched task calls this before registering nodes; afterwards
3382    /// only callbacks whose `.callback_group()` is in `groups` register here.
3383    /// An empty slice (or never calling it) leaves the wildcard — register all
3384    /// callbacks (the single-sched-task degenerate case + today's behaviour).
3385    pub fn set_active_groups(
3386        &mut self,
3387        groups: &[(&str, &str, &str)],
3388    ) -> Result<(), super::types::BindError> {
3389        // phase-409 — the table is CARVED and reused, so clear before refilling;
3390        // the old `Option<heapless::Vec>` got a fresh empty vector each call.
3391        self.active_groups.clear();
3392        if groups.is_empty() {
3393            self.active_groups_filtering = false;
3394            return Ok(());
3395        }
3396        for (name, ns, group) in groups {
3397            // issue 1172 — this used to be `if s.push_str(g).is_ok()`, which
3398            // DROPPED an oversized group name and left the sched task filtering on a
3399            // set that silently lacked it. It fails closed (the entity is never
3400            // created), so the symptom is a missing entity with nothing to read
3401            // that says why. Same contract as `declare_remap` below: too long,
3402            // or table full, is the caller's error.
3403            let key = super::storage::node_identity_hash(name, ns);
3404            let mut s = heapless::String::new();
3405            let why = if s.push_str(group).is_err() {
3406                Some(super::types::BindError::NameTooLong)
3407            } else if self.active_groups.push((key, s)).is_err() {
3408                Some(super::types::BindError::TableFull)
3409            } else {
3410                None
3411            };
3412            if let Some(why) = why {
3413                // FAIL CLOSED, and say so. Returning here with a PARTIAL table
3414                // would leave the sched task filtering on a subset — the same silent
3415                // narrowing, one step later. An empty table with filtering ON
3416                // accepts NOTHING (`group_filter_accepts` matches on an empty
3417                // slice), so the sched task registers no entities at all: visible in
3418                // behaviour, where a missing entry is not. The `Err` is for the
3419                // caller that can report it; the state is safe for the one that
3420                // cannot.
3421                self.active_groups.clear();
3422                self.active_groups_filtering = true;
3423                return Err(why);
3424            }
3425        }
3426        self.active_groups_filtering = true;
3427        Ok(())
3428    }
3429
3430    /// The current callback-group filter, or `None` for the wildcard.
3431    fn active_group_filter(&self) -> Option<&[super::storage::ActiveGroup]> {
3432        self.active_groups_filtering
3433            .then(|| self.active_groups.as_slice())
3434    }
3435
3436    /// Whether a callback in `group` should register in this
3437    /// executor under the current filter. The wildcard accepts everything.
3438    pub fn group_active(&self, node_name: &str, node_namespace: &str, group: &str) -> bool {
3439        group_filter_accepts(
3440            self.active_group_filter(),
3441            super::storage::node_identity_hash(node_name, node_namespace),
3442            group,
3443        )
3444    }
3445
3446    /// Set the node name and namespace used for liveliness tokens.
3447    ///
3448    /// Called by `open()` to propagate config values. When the executor
3449    /// creates entities, these values are attached to the
3450    /// Phase 156 — record the primary session's backend identity
3451    /// (rmw name + locator) so `NodeBuilder::resolve_session_slot`
3452    /// can detect when a `.rmw(name)` matches the primary instead
3453    /// of opening a SECOND backend session against the same
3454    /// singleton (zenoh-pico's `g_session` is process-wide;
3455    /// opening twice fails). `Executor::open*` calls this
3456    /// automatically; the C surface (`rclc_executor_init`) calls
3457    /// it manually because it constructs via `from_session_ptr`
3458    /// which doesn't know the open metadata. Empty strings = "no
3459    /// primary identity tracked"; the cache check degrades to
3460    /// always-miss.
3461    pub(crate) fn set_primary_identity(&mut self, rmw_name: &str, locator: &str) {
3462        self.primary_rmw_name.clear();
3463        let _ = self.primary_rmw_name.push_str(rmw_name);
3464        self.primary_locator.clear();
3465        let _ = self.primary_locator.push_str(locator);
3466    }
3467
3468    /// `TopicInfo`/`ServiceInfo` so the zenoh backend can declare liveliness.
3469    /// Set the ROS domain for entities this executor declares.
3470    ///
3471    /// For bindings that build an executor from an existing session
3472    /// (`from_session_ptr_in`), where no `ExecutorConfig` is available and the
3473    /// domain would otherwise stay at its 0 floor.
3474    pub fn set_domain_id(&mut self, domain_id: u32) {
3475        self.domain_id = domain_id;
3476    }
3477
3478    /// The ROS domain this executor declares entities on.
3479    pub fn domain_id(&self) -> u32 {
3480        self.domain_id
3481    }
3482
3483    /// RFC-0128 D8 (phase-554 W3) -- the node an entity is announced under,
3484    /// as `(name, namespace, session index)`.
3485    ///
3486    /// `Some(id)` is that node. `None` -- an entity created on the executor
3487    /// rather than on a node -- belongs to the image's PRIMARY node, the first
3488    /// declared one (`NodeId::PRIMARY`, the rule executor-level parameters
3489    /// already follow), so nothing is announced under the executor's own
3490    /// label. Only an image that declares no node at all (a direct-API image)
3491    /// keeps the executor identity, which is then its one node.
3492    ///
3493    /// The ONE spelling of this rule: seven registration sites each carried a
3494    /// copy that fell back to the executor label instead.
3495    pub(crate) fn entity_identity(
3496        &self,
3497        node_id: Option<super::node_record::NodeId>,
3498    ) -> Result<(heapless::String<64>, heapless::String<64>, u8), NodeError> {
3499        let id = node_id
3500            .or_else(|| (!self.nodes.is_empty()).then_some(super::node_record::NodeId::PRIMARY));
3501        match id {
3502            Some(id) => {
3503                let r = self
3504                    .nodes
3505                    .get(id.index())
3506                    .ok_or(NodeError::InvalidSchedContextBinding)?;
3507                Ok((r.name.clone(), r.namespace.clone(), r.session_idx))
3508            }
3509            None => Ok((self.node_name.clone(), self.namespace.clone(), 0u8)),
3510        }
3511    }
3512
3513    // RFC-0128 D8 (phase-554 W3 slice B).
3514    /// Run `hook` once this image's
3515    /// primary node exists: now, if a node is already registered, otherwise
3516    /// the moment `NodeId::PRIMARY` is (`NodeBuilder::build`). The hook opens
3517    /// an executor-level entity, so it lands on that node through
3518    /// `entity_identity` rather than on the executor's own label.
3519    ///
3520    /// A failure is the REGISTRATION's failure: returned here when the node
3521    /// exists, or from the `build()` that registers the primary node, which
3522    /// then leaves no node behind. Never logged and dropped.
3523    ///
3524    /// # Safety
3525    /// `ctx` must stay valid until the hook has run or this executor is
3526    /// dropped.
3527    pub unsafe fn open_on_primary_node(
3528        &mut self,
3529        hook: PrimaryNodeHook,
3530        ctx: *mut core::ffi::c_void,
3531        arg: u32,
3532    ) -> Result<(), NodeError> {
3533        if self.nodes.is_empty() {
3534            self.primary_node_hook = Some((hook, ctx as usize, arg));
3535            return Ok(());
3536        }
3537        // SAFETY: forwarded from this fn's contract.
3538        unsafe { hook(ctx, arg, self) }
3539    }
3540
3541    /// Whether an executor-level open still waits for the primary node.
3542    pub fn primary_node_open_pending(&self) -> bool {
3543        self.primary_node_hook.is_some()
3544    }
3545
3546    /// The node table's half of [`Self::open_on_primary_node`]: called right
3547    /// after `NodeId::PRIMARY` is pushed.
3548    pub(crate) fn run_primary_node_hook(&mut self) -> Result<(), NodeError> {
3549        let Some((hook, ctx, arg)) = self.primary_node_hook.take() else {
3550            return Ok(());
3551        };
3552        // SAFETY: `open_on_primary_node`'s contract -- `ctx` is valid until
3553        // the hook has run.
3554        unsafe { hook(ctx as *mut core::ffi::c_void, arg, self) }
3555    }
3556
3557    /// TEMPORARY -- phase-554 W3 slice C deletes this. A zero-node image (a
3558    /// direct-API image that registers no node) never reaches
3559    /// `run_primary_node_hook`, and it published its `/diagnostics` under the
3560    /// executor's configured name before slice B. Losing that silently would
3561    /// be a regression, so at the first spin, if an open still waits and no
3562    /// node was ever registered, it runs here, under that name
3563    /// (`entity_identity(None)` with no nodes). Slice C makes the configured
3564    /// name the image's one node, after which the hook always fires at
3565    /// registration and this path goes.
3566    ///
3567    /// A failure is returned from the spin, never logged.
3568    pub(crate) fn open_pending_on_configured_name(&mut self) -> Result<(), NodeError> {
3569        if !self.nodes.is_empty() {
3570            return Ok(());
3571        }
3572        self.run_primary_node_hook()
3573    }
3574
3575    // RFC-0128 D8.
3576    /// Open a raw publisher for an executor-level entity, on
3577    /// the node `entity_identity` gives `None`: the primary node, or
3578    /// the configured name in an image with no node. The `/diagnostics`
3579    /// reporter's publisher, which used to be a session publisher with no node
3580    /// at all.
3581    ///
3582    /// `domain_id` is the caller's: a Rust entry passes the executor's own,
3583    /// and the C++ context keeps its domain beside the executor.
3584    pub fn create_executor_publisher(
3585        &mut self,
3586        topic: &str,
3587        type_name: &str,
3588        type_hash: &str,
3589        qos: QoSProfile,
3590        domain_id: u32,
3591    ) -> Result<<session::ConcreteSession as nros_rmw::Session>::PublisherHandle, NodeError> {
3592        let (node_name, ns, session_idx) = self.entity_identity(None)?;
3593        let mut info = TopicInfo::new(topic, type_name, type_hash)
3594            .with_domain(domain_id)
3595            .with_namespace(&ns);
3596        if !node_name.is_empty() {
3597            info = info.with_node_name(&node_name);
3598        }
3599        let session = self
3600            .session_at_mut(session_idx)
3601            .ok_or(NodeError::BackendMismatch)?;
3602        session
3603            .create_publisher(&info, qos)
3604            .map_err(NodeError::Transport)
3605    }
3606
3607    pub fn set_node_identity(&mut self, node_name: &str, namespace: &str) {
3608        self.node_name.clear();
3609        let _ = self.node_name.push_str(node_name);
3610        if !namespace.is_empty() {
3611            self.namespace.clear();
3612            let _ = self.namespace.push_str(namespace);
3613        }
3614    }
3615
3616    // =========================================================================
3617    // Phase 305 W3 (issue 0255) — per-node launch remap table
3618    // =========================================================================
3619
3620    /// Record one launch `<remap from= to=/>` rule for the node identified by
3621    /// `(node_name, namespace)`. Rules are matched in declaration order (first
3622    /// wins) by [`Self::resolve_entity_name_for`]. Errors when a string
3623    /// overflows its slot or the table is at `MAX_REMAPS` — callers surface
3624    /// this rather than silently dropping a routing rule.
3625    ///
3626    /// **This declares an AUTHORITATIVE rule.** Declaration order settles
3627    /// which of two launch rules for one name wins; it is not how an argv rule
3628    /// is ranked against a launch rule. The `--ros-args` rules share this table
3629    /// but are tagged as the fallback sched task, and resolution reads both sched tasks
3630    /// through [`crate::names::resolve_name_layered`] — so an argv rule
3631    /// installed BEFORE a launch rule still loses to it.
3632    ///
3633    /// A GENERATED entry no longer calls this: its launch rules
3634    /// are the flash table ([`super::launch_remap::set_launch_remaps`]). This
3635    /// writes the RUNTIME table, for hand-written callers; on bare metal that
3636    /// table is 0 slots by default and the call is refused by name
3637    /// ([`RemapRefused::NoRuntimeTable`]).
3638    pub fn declare_remap(
3639        &mut self,
3640        node_name: &str,
3641        namespace: &str,
3642        from: &str,
3643        to: &str,
3644    ) -> Result<(), RemapRefused> {
3645        if self.remap_table.is_empty() {
3646            return Err(RemapRefused::NoRuntimeTable);
3647        }
3648        let mut rule = RemapRule {
3649            node_name: heapless::String::new(),
3650            namespace: heapless::String::new(),
3651            from: heapless::String::new(),
3652            to: heapless::String::new(),
3653            tier: RemapTier::Launch,
3654        };
3655        let too_long = |_| RemapRefused::TooLong;
3656        rule.node_name.push_str(node_name).map_err(too_long)?;
3657        let ns = if namespace.is_empty() { "/" } else { namespace };
3658        rule.namespace.push_str(ns).map_err(too_long)?;
3659        rule.from.push_str(from).map_err(too_long)?;
3660        rule.to.push_str(to).map_err(too_long)?;
3661        // Same contract as the `heapless::Vec::push` this replaces: full table
3662        // is an error the caller surfaces, never a silently dropped rule.
3663        let slot = self
3664            .remap_table
3665            .get_mut(self.remap_len)
3666            .ok_or(RemapRefused::TableFull)?;
3667        *slot = Some(rule);
3668        self.remap_len += 1;
3669        Ok(())
3670    }
3671
3672    /// Resolve a source-level entity name for the node identified by
3673    /// `(node_name, namespace)`: ROS 2 name expansion (`~`/relative → FQN)
3674    /// plus this node's declared remap rules (exact-FQN match, first rule
3675    /// wins). Nodes with no rules still get expansion. Errors on an
3676    /// unexpandable name (see `crate::names::expand_name`).
3677    ///
3678    /// Two tiers, through [`crate::names::resolve_name_layered`]: the rules
3679    /// [`Self::declare_remap`] recorded for this node are AUTHORITATIVE (the
3680    /// generated entry declares the launch projection there), and the
3681    /// `--ros-args` rules `crate::ros_args::install_argv_remaps` put in the
3682    /// same table are the FALLBACK, consulted only when no launch rule
3683    /// matched. rcl does the same with its local and global arguments
3684    /// (`rcl_remap_topic_name`, Humble `rcl/remap.h`).
3685    #[allow(clippy::result_unit_err)]
3686    pub fn resolve_entity_name_for(
3687        &self,
3688        node_name: &str,
3689        namespace: &str,
3690        source: &str,
3691    ) -> Result<crate::names::ResolvedName, ()> {
3692        let ns = if namespace.is_empty() { "/" } else { namespace };
3693        self.remap_view().resolve(source, node_name, ns)
3694    }
3695
3696    /// Give this executor its own launch remap table instead of
3697    /// the image's ([`super::launch_remap::set_launch_remaps`]). A borrow of
3698    /// `.rodata`; nothing is copied.
3699    pub fn set_launch_remaps(&mut self, table: &'static [super::launch_remap::LaunchRemap]) {
3700        self.launch_remaps = Some(table);
3701    }
3702
3703    /// Both remap sources this executor resolves through: the launch table
3704    /// (flash) and the runtime table (RAM).
3705    pub(crate) fn remap_view(&self) -> RemapView<'_> {
3706        RemapView {
3707            launch: self
3708                .launch_remaps
3709                .unwrap_or_else(super::launch_remap::launch_remaps),
3710            runtime: &self.remap_table[..self.remap_len],
3711        }
3712    }
3713
3714    // RFC-0128 D8 (phase-554 W3 slice B).
3715    /// [`Self::resolve_entity_name_for`]
3716    /// against the node the entity is REGISTERED on, as
3717    /// `entity_identity` gives it: `Some(id)` is that node, `None` the
3718    /// primary node (or, in an image with no node, the configured name). The
3719    /// one rule both remap resolution and announcement follow, so a name is
3720    /// never resolved against one node and announced under another.
3721    #[allow(clippy::result_unit_err)]
3722    pub fn resolve_entity_name_on(
3723        &self,
3724        node_id: Option<super::node_record::NodeId>,
3725        source: &str,
3726    ) -> Result<crate::names::ResolvedName, ()> {
3727        let (node_name, ns, _) = self.entity_identity(node_id).map_err(|_| ())?;
3728        self.resolve_entity_name_for(node_name.as_str(), ns.as_str(), source)
3729    }
3730
3731    /// [`Self::resolve_entity_name_for`] against the executor's CURRENT node
3732    /// identity (`set_node_identity`). The registration sites use
3733    /// [`Self::resolve_entity_name_on`], which names the entity's node rather
3734    /// than whichever identity was set last.
3735    #[allow(clippy::result_unit_err)]
3736    pub fn resolve_entity_name(&self, source: &str) -> Result<crate::names::ResolvedName, ()> {
3737        self.resolve_entity_name_for(self.node_name.as_str(), self.namespace.as_str(), source)
3738    }
3739
3740    // =========================================================================
3741    // Phase 272 (RFC-0047) — node-name → sched-context table
3742    // =========================================================================
3743
3744    /// Seed a config-resolved sched task binding by `(name, namespace)` before the
3745    /// node is built. `NodeBuilder::build` consults this table when no
3746    /// explicit `.sched()` override is given — the table entry then wins over
3747    /// the `SchedContextId(0)` default (precedence: explicit > table > 0).
3748    ///
3749    /// Call BEFORE `node_builder(name).build()`. An existing entry for the
3750    /// same `(name, namespace)` key is overwritten (last-write wins). Overflow
3751    /// past `MAX_NODES` is an `Err`, never a dropped binding. An
3752    /// empty `namespace` is normalised
3753    /// to `"/"` to match what `NodeBuilder::build` computes for a root-NS node.
3754    pub fn bind_node_name_sched(
3755        &mut self,
3756        name: &str,
3757        namespace: &str,
3758        sc: super::sched_context::SchedContextId,
3759    ) -> Result<(), super::types::BindError> {
3760        let norm_ns = if namespace.is_empty() { "/" } else { namespace };
3761        // Overwrite if there is already an entry for this (name, ns) pair.
3762        for entry in self.node_sched_table.iter_mut() {
3763            if entry.0.as_str() == name && entry.1.as_str() == norm_ns {
3764                entry.2 = sc;
3765                return Ok(());
3766            }
3767        }
3768        self.push_node_entry(name, norm_ns, sc, 0)
3769    }
3770
3771    /// Seed the contract rank of the node
3772    /// `(name, namespace)` before it is built: 0 is the most urgent, as codegen
3773    /// normalises the derivation's ranks. Every callback the node registers
3774    /// then dispatches at that rank inside its sched context's bucket
3775    /// ([`Priority::dispatch_level`](super::sched_context::Priority::dispatch_level)).
3776    /// A node with no seeded rank holds 0.
3777    ///
3778    /// Shares the node-name table with [`Self::bind_node_name_sched`]: one entry
3779    /// per node carries both, so neither call disturbs the other's half. Same
3780    /// error contract: a binding that does not fit is refused, never dropped.
3781    pub fn bind_node_rank(
3782        &mut self,
3783        name: &str,
3784        namespace: &str,
3785        rank: u8,
3786    ) -> Result<(), super::types::BindError> {
3787        let norm_ns = if namespace.is_empty() { "/" } else { namespace };
3788        for entry in self.node_sched_table.iter_mut() {
3789            if entry.0.as_str() == name && entry.1.as_str() == norm_ns {
3790                entry.3 = rank;
3791                return Ok(());
3792            }
3793        }
3794        self.push_node_entry(name, norm_ns, super::sched_context::SchedContextId(0), rank)
3795    }
3796
3797    /// The rank seeded for `(name, namespace)` by [`Self::bind_node_rank`], 0
3798    /// when none was.
3799    pub(super) fn lookup_node_rank(&self, name: &str, namespace: &str) -> u8 {
3800        self.node_sched_table
3801            .iter()
3802            .find(|e| e.0.as_str() == name && e.1.as_str() == namespace)
3803            .map_or(0, |e| e.3)
3804    }
3805
3806    /// A new node-name table entry.
3807    fn push_node_entry(
3808        &mut self,
3809        name: &str,
3810        norm_ns: &str,
3811        sc: super::sched_context::SchedContextId,
3812        rank: u8,
3813    ) -> Result<(), super::types::BindError> {
3814        // New entry. Too long, or table full, is an ERROR the caller surfaces
3815        // — never a dropped binding. A binding that vanishes leaves the node on
3816        // the wrong sched context with nothing to read that says so.
3817        let mut name_s = heapless::String::<64>::new();
3818        let mut ns_s = heapless::String::<64>::new();
3819        name_s
3820            .push_str(name)
3821            .map_err(|_| super::types::BindError::NameTooLong)?;
3822        ns_s.push_str(norm_ns)
3823            .map_err(|_| super::types::BindError::NameTooLong)?;
3824        self.node_sched_table
3825            .push((name_s, ns_s, sc, rank))
3826            .map_err(|_| super::types::BindError::TableFull)?;
3827        Ok(())
3828    }
3829
3830    /// Look up the seeded sched-context for `(name, namespace)`. Returns
3831    /// `None` when the table has no entry for this pair (unseed → default 0).
3832    /// `pub(super)` — visible only within the `executor` module (sibling
3833    /// `node_record` calls it from `NodeBuilder::build`).
3834    pub(super) fn lookup_node_sched(
3835        &self,
3836        name: &str,
3837        namespace: &str,
3838    ) -> Option<super::sched_context::SchedContextId> {
3839        for entry in self.node_sched_table.iter() {
3840            if entry.0.as_str() == name && entry.1.as_str() == namespace {
3841                return Some(entry.2);
3842            }
3843        }
3844        None
3845    }
3846
3847    // =========================================================================
3848    // Phase 273 (RFC-0047) — per-callback-group → sched-context table
3849    // =========================================================================
3850
3851    /// Seed a config-resolved sched task binding by `(name, namespace, group)` before
3852    /// entities are registered. `apply_node_default_sched` consults this table
3853    /// first (group table > node default > `SchedContextId(0)`).
3854    ///
3855    /// Call BEFORE entity creation. An existing entry for the same
3856    /// `(name, namespace, group)` key is overwritten (last-write wins). Overflow
3857    /// past `MAX_CBS` is an `Err`, never a dropped binding. An
3858    /// empty `namespace` is normalised to
3859    /// `"/"` to match `NodeBuilder::build`. Mirror of `bind_node_name_sched`.
3860    pub fn bind_group_sched(
3861        &mut self,
3862        name: &str,
3863        namespace: &str,
3864        group: &str,
3865        sc: super::sched_context::SchedContextId,
3866    ) -> Result<(), super::types::BindError> {
3867        let norm_ns = if namespace.is_empty() { "/" } else { namespace };
3868        // Overwrite if there is already an entry for this (name, ns, group).
3869        for entry in self.group_sched_table.iter_mut() {
3870            if entry.0.as_str() == name && entry.1.as_str() == norm_ns && entry.2.as_str() == group
3871            {
3872                entry.3 = sc;
3873                return Ok(());
3874            }
3875        }
3876        // Same contract as the two above.
3877        let mut name_s = heapless::String::<64>::new();
3878        let mut ns_s = heapless::String::<64>::new();
3879        let mut grp_s = heapless::String::<32>::new();
3880        name_s
3881            .push_str(name)
3882            .map_err(|_| super::types::BindError::NameTooLong)?;
3883        ns_s.push_str(norm_ns)
3884            .map_err(|_| super::types::BindError::NameTooLong)?;
3885        grp_s
3886            .push_str(group)
3887            .map_err(|_| super::types::BindError::NameTooLong)?;
3888        self.group_sched_table
3889            .push((name_s, ns_s, grp_s, sc))
3890            .map_err(|_| super::types::BindError::TableFull)?;
3891        Ok(())
3892    }
3893
3894    /// Look up the seeded sched-context for `(name, namespace, group)`. Returns
3895    /// `None` when the table has no entry for this triple.
3896    fn lookup_group_sched(
3897        &self,
3898        name: &str,
3899        namespace: &str,
3900        group: &str,
3901    ) -> Option<super::sched_context::SchedContextId> {
3902        for entry in self.group_sched_table.iter() {
3903            if entry.0.as_str() == name
3904                && entry.1.as_str() == namespace
3905                && entry.2.as_str() == group
3906            {
3907                return Some(entry.3);
3908            }
3909        }
3910        None
3911    }
3912
3913    // =========================================================================
3914    // Phase 110.B — SchedContext API
3915    // =========================================================================
3916
3917    /// Identifier of the auto-created default `Fifo`-class scheduling
3918    /// context. Every callback registered without an explicit
3919    /// [`Self::bind_handle_to_sched_context`] binds to this SC.
3920    pub fn default_sched_context_id(&self) -> super::sched_context::SchedContextId {
3921        super::sched_context::SchedContextId(0)
3922    }
3923
3924    /// Register a new scheduling context. Returns a [`SchedContextId`](crate::executor::sched_context::SchedContextId)
3925    /// callers pass to [`Self::bind_handle_to_sched_context`] to attach
3926    /// callbacks.
3927    pub fn create_sched_context(
3928        &mut self,
3929        sc: super::sched_context::SchedContext,
3930    ) -> Result<super::sched_context::SchedContextId, NodeError> {
3931        // Slot 0 is reserved for the default Fifo SC; search 1..MAX_SC.
3932        for (i, slot) in self.sched_contexts.iter_mut().enumerate().skip(1) {
3933            if slot.is_none() {
3934                *slot = Some(sc);
3935                // Phase 110.E — Sporadic-class SCs get a sibling
3936                // `SporadicState` entry that the spin_once dispatch
3937                // path consults each cycle to refill the budget at
3938                // period boundaries and skip dispatch when budget
3939                // is exhausted.
3940                if matches!(sc.class, super::sched_context::SchedClass::Sporadic) {
3941                    let budget = sc.budget_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
3942                    let period = sc.period_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
3943                    self.sporadic_states[i] =
3944                        Some(super::sched_context::SporadicState::new(budget, period));
3945                }
3946                return Ok(super::sched_context::SchedContextId(i as u8));
3947            }
3948        }
3949        Err(NodeError::NoSchedContextSlot)
3950    }
3951
3952    /// Wall-clock µs since the UNIX epoch, when this
3953    /// target has an epoch source (config `epoch_us`, defaulted from
3954    /// `SystemTime` on hosted configs). `None` = no wall clock; age
3955    /// monitors must not have been baked (the emitter refuses).
3956    pub fn epoch_now_us(&self) -> Option<u64> {
3957        self.epoch_us_fn.map(|f| f())
3958    }
3959
3960    /// Install the baked contract-monitor table. Call
3961    /// BEFORE entity creation so `create_publisher` can attach each
3962    /// contracted endpoint's counter cell. Mirrors `set_qos_overrides`:
3963    /// `&'static`, codegen-baked, empty by default.
3964    ///
3965    /// The executor watches at most
3966    /// [`MAX_MONITORS`](super::monitor::MAX_MONITORS) rows
3967    /// (`NROS_EXECUTOR_MAX_MONITORS`). A generated entry cannot reach this with
3968    /// more: its table carries a compile-time assertion that names the knob,
3969    /// and the C++ installer refuses at runtime. A hand-written longer table is
3970    /// a debug-build panic naming the knob, because in release the spin loop
3971    /// would inspect only the first `MAX_MONITORS` and leave the rest silently
3972    /// unwatched.
3973    pub fn set_monitor_table(&mut self, table: &'static [super::monitor::MonitorSpec]) {
3974        if let Err(full) = super::monitor::check_table_capacity(table.len(), 0)
3975            && cfg!(debug_assertions)
3976        {
3977            panic!("set_monitor_table: {full}");
3978        }
3979        self.monitor_table = table;
3980    }
3981
3982    /// Install BOTH baked monitor tables, or neither.
3983    ///
3984    /// The refusing installer: a table longer than this executor watches
3985    /// (`MAX_MONITORS` / `MAX_AGE_MONITORS`) is `Err`, and its `Display` names
3986    /// the knob to raise, before anything is installed. Nothing is truncated:
3987    /// the spin loop inspects only the first `MAX_*` specs, so accepting a
3988    /// longer table would boot with its tail silently unwatched. The C ABI's
3989    /// `nros_cpp_install_monitors` refuses on the same check.
3990    pub fn try_set_monitor_tables(
3991        &mut self,
3992        table: &'static [super::monitor::MonitorSpec],
3993        ages: &'static [super::monitor::AgeMonitorSpec],
3994    ) -> Result<(), super::monitor::MonitorTableFull> {
3995        super::monitor::check_table_capacity(table.len(), ages.len())?;
3996        self.monitor_table = table;
3997        self.age_table = ages;
3998        Ok(())
3999    }
4000
4001    /// The installed monitor table (empty unless the entry set one).
4002    #[must_use]
4003    pub fn monitor_table(&self) -> &'static [super::monitor::MonitorSpec] {
4004        self.monitor_table
4005    }
4006
4007    /// Issue 1676 — the counter cell a publisher on `topic_name` bumps, by
4008    /// exact topic match against the installed table (`None` = uncontracted).
4009    pub(crate) fn publisher_monitor_cell(
4010        &self,
4011        topic_name: &str,
4012    ) -> Option<&'static super::monitor::PubMonitorCell> {
4013        self.monitor_table
4014            .iter()
4015            .find(|m| m.topic == topic_name)
4016            .map(|m| m.cell)
4017    }
4018
4019    /// W3b.5 — install the baked subscriber age-contract table. Call
4020    /// BEFORE entity creation so `create_subscription` can attach each
4021    /// contracted endpoint's age cell (needs an epoch source — see
4022    /// `ExecutorConfig::epoch_us`; without one the take path records
4023    /// nothing and age monitors stay silent).
4024    ///
4025    /// At most
4026    /// [`MAX_AGE_MONITORS`](super::monitor::MAX_AGE_MONITORS) rows
4027    /// (`NROS_EXECUTOR_MAX_AGE_MONITORS`), on the same terms as
4028    /// [`Self::set_monitor_table`].
4029    pub fn set_age_table(&mut self, table: &'static [super::monitor::AgeMonitorSpec]) {
4030        if let Err(full) = super::monitor::check_table_capacity(0, table.len())
4031            && cfg!(debug_assertions)
4032        {
4033            panic!("set_age_table: {full}");
4034        }
4035        self.age_table = table;
4036    }
4037
4038    /// The installed age table (empty unless the entry set one).
4039    #[must_use]
4040    pub fn age_table(&self) -> &'static [super::monitor::AgeMonitorSpec] {
4041        self.age_table
4042    }
4043
4044    /// Install the baked hazard table. Each row's guards name
4045    /// rows of the tables [`Self::set_monitor_table`] and
4046    /// [`Self::set_age_table`] install, so install those first; a guard whose
4047    /// row is absent never faults. The observer runs after the monitor rows on
4048    /// every monitor tick and reports `hazard-detected`, `hazard-reaction` and
4049    /// `hazard-recovered` on the same drain.
4050    pub fn set_hazard_table(&mut self, table: &'static [super::monitor::HazardSpec]) {
4051        self.hazard_table = table;
4052    }
4053
4054    /// Install the contract's mode variants of the two monitor
4055    /// tables; entry `i` is mode `i`, and entry 0 must be the base tables
4056    /// already installed. A switch is asked for with
4057    /// [`super::monitor::request_mode`] and applied at the next spin.
4058    ///
4059    /// # Errors
4060    ///
4061    /// [`super::monitor::ModeTablesMismatch`] when an entry's tables are not the base's
4062    /// length: a variant shares the base's cells and the per-row monitor
4063    /// state by index, so a variant of another length would judge one row
4064    /// by another's requirement. Nothing is installed.
4065    pub fn set_mode_tables(
4066        &mut self,
4067        modes: &'static [super::monitor::ModeTables],
4068    ) -> Result<(), super::monitor::ModeTablesMismatch> {
4069        for (id, m) in modes.iter().enumerate() {
4070            if m.monitors.len() != self.monitor_table.len() || m.ages.len() != self.age_table.len()
4071            {
4072                return Err(super::monitor::ModeTablesMismatch {
4073                    mode: id as u16,
4074                    monitors: (m.monitors.len(), self.monitor_table.len()),
4075                    ages: (m.ages.len(), self.age_table.len()),
4076                    missing_sc: None,
4077                });
4078            }
4079            if let Some(d) = m
4080                .deadlines
4081                .iter()
4082                .find(|d| !matches!(self.sched_contexts.get(usize::from(d.sc)), Some(Some(_))))
4083            {
4084                return Err(super::monitor::ModeTablesMismatch {
4085                    mode: id as u16,
4086                    monitors: (m.monitors.len(), self.monitor_table.len()),
4087                    ages: (m.ages.len(), self.age_table.len()),
4088                    missing_sc: Some(d.sc),
4089                });
4090            }
4091        }
4092        self.mode_tables = modes;
4093        Ok(())
4094    }
4095
4096    /// The mode whose tables this executor judges by (0 = the base).
4097    #[must_use]
4098    pub fn current_mode(&self) -> u16 {
4099        self.mode_applied
4100    }
4101
4102    /// phase-462 W4 -- once per spin, before any rule runs: enter the mode the
4103    /// application asked for, if this executor has tables for it.
4104    fn update_mode(&mut self, now_us: Option<u64>) {
4105        if self.mode_tables.is_empty() {
4106            return;
4107        }
4108        // phase-462 W4c -- a request seen now arrived after the previous
4109        // check, so this gap bounds how long it waited.
4110        let now_ms = now_us.map(|us| (us / 1_000) as u32);
4111        let waited_ms = match (now_ms, self.mode_checked_ms) {
4112            (Some(now), Some(prev)) => Some(now.wrapping_sub(prev)),
4113            _ => None,
4114        };
4115        self.mode_checked_ms = now_ms;
4116        let want = super::monitor::requested_mode();
4117        if want == self.mode_seen {
4118            return;
4119        }
4120        self.mode_seen = want;
4121        match self.mode_tables.get(usize::from(want)) {
4122            Some(t) => {
4123                self.monitor_table = t.monitors;
4124                self.age_table = t.ages;
4125                for d in t.deadlines {
4126                    if let Some(Some(sc)) = self.sched_contexts.get_mut(usize::from(d.sc)) {
4127                        sc.deadline_us = super::sched_context::OptUs::from_us(d.deadline_us);
4128                    }
4129                }
4130                if let Some(v) = super::monitor::check_mode_switch(t, waited_ms) {
4131                    self.violations.record(v);
4132                }
4133                self.mode_applied = want;
4134                nros_log::log_info!(
4135                    nros_log::get_logger("nros"),
4136                    "contract mode {} entered",
4137                    want
4138                );
4139            }
4140            None => nros_log::log_warn!(
4141                nros_log::get_logger("nros"),
4142                "contract mode {} requested, but this executor bakes {} mode table(s); \
4143                 staying in mode {}",
4144                want,
4145                self.mode_tables.len(),
4146                self.mode_applied
4147            ),
4148        }
4149    }
4150
4151    /// The installed hazard table (empty unless the entry set one).
4152    #[must_use]
4153    pub fn hazard_table(&self) -> &'static [super::monitor::HazardSpec] {
4154        self.hazard_table
4155    }
4156
4157    /// W3b.5 — override the wall-clock (epoch µs) source age monitors take
4158    /// message stamps against. Hosted builds default to `SystemTime`; a
4159    /// board with a synced RTC installs its own here (or via
4160    /// `ExecutorConfig::epoch_us`). Call BEFORE entity creation — the age
4161    /// hook captures this at `create_subscription` time.
4162    pub fn set_epoch_clock(&mut self, epoch_us: fn() -> u64) {
4163        self.epoch_us_fn = Some(epoch_us);
4164    }
4165
4166    /// W3b.5 — resolve a subscription's age hook at registration time:
4167    /// exact topic match against the baked age table, only for stamped
4168    /// types (`M::STAMP_OFFSET`). Issue 2215: with no epoch source the hook
4169    /// still records the stamped take (the silence rule's evidence), and the
4170    /// age is judged only once an epoch is installed.
4171    fn age_lookup<M: RosMessage>(&self, topic: &str) -> Option<super::arena::AgeMon> {
4172        M::STAMP_OFFSET?;
4173        self.age_table
4174            .iter()
4175            .find(|a| a.topic == topic)
4176            .map(|a| (a.cell, self.epoch_us_fn))
4177    }
4178
4179    /// Bind a C/C++ callback subscription to its topic's
4180    /// contracted age row, so its stamped takes feed the silence rule (and,
4181    /// with an epoch source, the age rule) as the Rust typed paths' do.
4182    /// `stamp_offset` is the CDR byte offset of the type's `stamp.sec`
4183    /// (encapsulation header included; the C++ message type states it as
4184    /// `STAMP_OFFSET`). Returns `true` when a row was bound; `false` when the
4185    /// topic has no age row or `handle` is not a C callback subscription,
4186    /// which is not an error: such a subscription has nothing to feed.
4187    pub fn bind_raw_subscription_stamp(
4188        &mut self,
4189        handle: HandleId,
4190        topic: &str,
4191        stamp_offset: u16,
4192    ) -> bool {
4193        let Some(row) = self.age_table.iter().find(|a| a.topic == topic) else {
4194            return false;
4195        };
4196        let mon = Some(super::arena::RawAgeMon {
4197            cell: row.cell,
4198            epoch: self.epoch_us_fn,
4199            stamp_offset,
4200        });
4201        let i = self.live_slot(handle);
4202        let Some(meta) = self.entries.get(i).and_then(|m| m.as_ref()) else {
4203            return false;
4204        };
4205        let offset = meta.offset;
4206        type TryProcess = unsafe fn(*mut u8, u64, u8) -> Result<bool, TransportError>;
4207        let inplace = core::ptr::fn_addr_eq(
4208            meta.try_process,
4209            super::arena::sub_inplace_raw_c_try_process as TryProcess,
4210        );
4211        let buffered = core::ptr::fn_addr_eq(
4212            meta.try_process,
4213            super::arena::sub_buffered_raw_c_try_process as TryProcess,
4214        );
4215        // SAFETY: the entry at `offset` was written by
4216        // `add_arena_subscription_c_callback_with_capture` as the type its
4217        // `try_process` names, which is what the two tests above select on.
4218        unsafe {
4219            let ptr = (self.arena.as_mut_ptr() as *mut u8).add(offset);
4220            if inplace {
4221                (*(ptr as *mut super::arena::SubInplaceRawCEntry)).age_mon = mon;
4222            } else if buffered {
4223                (*(ptr as *mut SubBufferedRawCEntry)).age_mon = mon;
4224            } else {
4225                return false;
4226            }
4227        }
4228        true
4229    }
4230
4231    /// W3b.5 — install the `DeadlineAction::Fault` hook. Without one a
4232    /// fault-class deadline miss panics (watchdog-visible stop on
4233    /// embedded targets).
4234    /// Plan one `spin_once` against the caller's intended cadence, and return
4235    /// the park budget in microseconds.
4236    ///
4237    /// phase-474 I11 -- two cases:
4238    ///
4239    /// * **No declared cadence, non-zero timeout** (the generated entries'
4240    ///   `spin_once(10)` loop, `spin`, `spin_period`): the timeout is the
4241    ///   period and the loop runs on an absolute RELEASE GRID. The budget is
4242    ///   the time to the next grid point, not a whole period from now, so the
4243    ///   previous spin's work no longer pushes every later release back. A
4244    ///   loop that comes back after its next point was due is released at
4245    ///   once, late by the difference; one that comes back a whole period or
4246    ///   more after it is released once for the LATEST due point and the
4247    ///   older ones are skipped and counted -- the timer `Skip` policy, never
4248    ///   a burst. Lateness is judged at the release (`record_grid_release`).
4249    ///   A change of timeout re-anchors the grid at this entry.
4250    /// * **A declared cadence** (`set_spin_nominal_us`, the tier loops that
4251    ///   sleep between spins themselves): unchanged. Late is
4252    ///   `(now - last_entry) - cadence`, clamped at zero, and the budget is
4253    ///   the timeout.
4254    ///
4255    /// A zero timeout claims no cadence and is skipped entirely, which keeps
4256    /// `Future::wait`-style busy spins out of the statistic and off the grid.
4257    fn record_release_jitter(&mut self, timeout: core::time::Duration) -> u64 {
4258        let timeout_us = timeout.as_micros().min(u64::MAX as u128) as u64;
4259        if !self.spin_nominal_self_paced() {
4260            if timeout_us == 0 {
4261                return 0;
4262            }
4263            let Some(now) = self.now_us() else {
4264                return timeout_us;
4265            };
4266            // phase-436 A2b -- a wait-paced declaration supplies the grid's
4267            // period; otherwise the timeout stands in for it.
4268            let period_us = if self.spin_nominal_declared_us != 0 {
4269                self.spin_nominal_declared_us
4270            } else {
4271                timeout_us
4272            };
4273            self.spin_nominal_us = period_us;
4274            if self.grid.period_us != period_us {
4275                // First periodic spin, or a new period: anchor here, so the
4276                // first park is a whole period exactly as before.
4277                self.grid.period_us = period_us;
4278                self.grid.next_us = now.saturating_add(period_us);
4279            } else if now >= self.grid.next_us.saturating_add(period_us) {
4280                // The loop came back a whole period or more after its next
4281                // release was due: serve the latest due point once and drop
4282                // the ones before it. The first dropped point is a release
4283                // that never happened, so its lateness at this moment (a
4284                // period or more) is what the jitter rule judges.
4285                let missed = (now - self.grid.next_us) / period_us;
4286                self.note_dropped_release(now - self.grid.next_us);
4287                self.grid.skipped = self
4288                    .grid
4289                    .skipped
4290                    .saturating_add(missed.min(u32::MAX as u64) as u32);
4291                self.grid.next_us = self
4292                    .grid
4293                    .next_us
4294                    .saturating_add(missed.saturating_mul(period_us));
4295            }
4296            // The timeout still bounds the wait. With a declared period it
4297            // may be shorter than the period (a caller that passes whole
4298            // milliseconds for a 1.5 ms cadence); a wake before the grid
4299            // point is then not a release, and the next spin parks again.
4300            return self.grid.next_us.saturating_sub(now).min(timeout_us);
4301        }
4302        // phase-474 I7 -- the violation reporter's own time since the last
4303        // sample is not a late release (see `flush_violation_reports`). Taken
4304        // first, so a spin that judges nothing does not carry it forward.
4305        let report_us = core::mem::take(&mut self.violations.reports.debt_us);
4306        let nominal_us = self.spin_nominal_declared_us;
4307        let Some(now) = self.now_us() else {
4308            return timeout_us;
4309        };
4310        self.spin_nominal_us = nominal_us;
4311        if let Some(last) = self.last_spin_entry_us {
4312            let interval = now.saturating_sub(last).saturating_sub(report_us);
4313            self.total_wakes = self.total_wakes.saturating_add(1);
4314            if let Some(late) = interval.checked_sub(nominal_us)
4315                && late > 0
4316            {
4317                self.count_late_wake(late);
4318            }
4319        }
4320        self.last_spin_entry_us = Some(now);
4321        timeout_us
4322    }
4323
4324    /// phase-474 I11 -- judge a grid release, at the clock read after the
4325    /// park. A spin that wakes before its grid point (data arrived, a timer
4326    /// or another source was due first) is not a release: it dispatches and
4327    /// leaves the grid where it was. One that wakes at or after it is THE
4328    /// release of that point, late by `now - grid.next_us` (less the
4329    /// violation reporter's own time, phase-474 I7), and the grid advances by
4330    /// one period. Points the park itself overslept by a whole period are
4331    /// skipped at the next entry, not served in a burst.
4332    fn record_grid_release(&mut self, now: u64) {
4333        if self.spin_nominal_self_paced() || self.grid.period_us == 0 {
4334            return;
4335        }
4336        if now < self.grid.next_us {
4337            return;
4338        }
4339        let report_us = core::mem::take(&mut self.violations.reports.debt_us);
4340        let late = now
4341            .saturating_sub(self.grid.next_us)
4342            .saturating_sub(report_us);
4343        self.total_wakes = self.total_wakes.saturating_add(1);
4344        if late > 0 {
4345            self.count_late_wake(late);
4346        }
4347        self.grid.next_us = self.grid.next_us.saturating_add(self.grid.period_us);
4348        if now >= self.grid.next_us {
4349            // The park overslept the following point(s) too. This wake serves
4350            // one release; the points it ran past are skipped, not released
4351            // back to back on the next spins.
4352            let missed = (now - self.grid.next_us) / self.grid.period_us + 1;
4353            self.grid.skipped = self
4354                .grid
4355                .skipped
4356                .saturating_add(missed.min(u32::MAX as u64) as u32);
4357            self.grid.next_us = self
4358                .grid
4359                .next_us
4360                .saturating_add(missed.saturating_mul(self.grid.period_us));
4361        }
4362    }
4363
4364    /// One wake that came back `late_us` (> 0) after its release was due.
4365    fn count_late_wake(&mut self, late_us: u64) {
4366        self.late_wakes = self.late_wakes.saturating_add(1);
4367        if late_us > self.release_jitter_granularity_us() {
4368            self.late_wakes_beyond_granule = self.late_wakes_beyond_granule.saturating_add(1);
4369        }
4370        if late_us > self.max_release_jitter_us {
4371            self.max_release_jitter_us = late_us;
4372        }
4373    }
4374
4375    /// A cadence the caller meets with its own sleep between spins.
4376    fn spin_nominal_self_paced(&self) -> bool {
4377        self.spin_nominal_declared_us != 0 && !self.spin_nominal_wait_paced
4378    }
4379
4380    /// The lateness of a grid release that was dropped rather than served,
4381    /// into the high-water the jitter rule reads (not into the wake counts:
4382    /// no wake happened).
4383    fn note_dropped_release(&mut self, late_us: u64) {
4384        let late = late_us.saturating_sub(core::mem::take(&mut self.violations.reports.debt_us));
4385        if late > self.max_release_jitter_us {
4386            self.max_release_jitter_us = late;
4387        }
4388    }
4389
4390    /// Grid releases skipped since the last
4391    /// `clear_release_jitter_stats`, because the loop came back after they
4392    /// were due. Zero for a declared-cadence or zero-timeout caller.
4393    pub fn skipped_releases(&self) -> u32 {
4394        self.grid.skipped
4395    }
4396
4397    /// Release-jitter statistics from the spin loop: worst lateness in
4398    /// microseconds, the number of wakes that were already late, and the
4399    /// number of wakes total.
4400    ///
4401    /// The maximum is the figure of merit, and the ratio is what tells the
4402    /// two failures apart: one late wake in ten thousand is a glitch, ten
4403    /// thousand in ten thousand means the period cannot be met at all.
4404    ///
4405    /// Zero on a build with no clock -- `spin_period` refuses to run at all
4406    /// there, so there is nothing to have measured.
4407    pub fn release_jitter(&self) -> (u64, u32, u32) {
4408        (
4409            self.max_release_jitter_us,
4410            self.late_wakes,
4411            self.total_wakes,
4412        )
4413    }
4414
4415    /// Of the `late` wakes `release_jitter` counts, those
4416    /// late by more than [`Self::release_jitter_granularity_us`].
4417    ///
4418    /// A wake is late at one microsecond past its release. A loop paced by a
4419    /// tick-granular park comes back up to a tick past it on every wake, by
4420    /// design, so `late` approaches `total` on a loop that is keeping its
4421    /// period perfectly well. This count leaves that rounding out: it is the
4422    /// lateness the measurement can actually resolve. Cleared with the rest.
4423    pub fn late_wakes_beyond_granularity(&self) -> u32 {
4424        self.late_wakes_beyond_granule
4425    }
4426
4427    /// Reset the release-jitter statistics. For monitoring code that logs
4428    /// and clears per window, so a single early outlier does not pin the
4429    /// maximum for the life of the process.
4430    pub fn clear_release_jitter_stats(&mut self) {
4431        self.max_release_jitter_us = 0;
4432        self.late_wakes = 0;
4433        self.late_wakes_beyond_granule = 0;
4434        self.total_wakes = 0;
4435        self.last_spin_entry_us = None;
4436        self.jitter_reported_us = 0;
4437        self.grid.skipped = 0;
4438    }
4439
4440    pub fn set_fault_handler(&mut self, f: fn(&super::monitor::Violation)) {
4441        self.fault_fn = Some(f);
4442    }
4443
4444    /// Install the REACTION hook: `f(event, ctx)` is called on the
4445    /// spin thread when a supervised route passes its deadline
4446    /// (`route-deadline-runtime`), with the row's reaction id, row index and
4447    /// mechanism. It also stands in for [`Self::set_fault_handler`] on a
4448    /// `DeadlineAction::Fault` when no fault handler is set (reaction id 0,
4449    /// the sched-context slot as the row), so a C or C++ image has a fault
4450    /// path that does not panic. Replaces any earlier hook; `None` removes it.
4451    ///
4452    /// The hook must not block and must not re-enter this executor: it starts
4453    /// the fallback, or hands it to another thread, and returns.
4454    pub fn set_reaction_hook(
4455        &mut self,
4456        hook: Option<(super::monitor::ReactionHookFn, *mut core::ffi::c_void)>,
4457    ) {
4458        self.reaction_hook = hook;
4459    }
4460
4461    /// Install the lock every
4462    /// FFI entry and every worker pass takes on this executor (`None` removes
4463    /// it). Call it while no second thread can reach the executor: a runner
4464    /// installs it before it spawns a level.
4465    pub fn set_exec_lock(&mut self, lock: Option<super::exec_lock::ExecLock>) {
4466        self.exec_lock = lock;
4467    }
4468
4469    /// phase-509 P9b -- the installed lock, if any.
4470    pub(crate) fn exec_lock(&self) -> Option<super::exec_lock::ExecLock> {
4471        self.exec_lock
4472    }
4473
4474    /// phase-509 P9b item 2 -- whether the callback of `slot` runs in a window
4475    /// on a thread other than the calling one. An operation on such an entry
4476    /// would race the callback, so the entry accessors answer as for a stale
4477    /// handle and cancel / reset are deferred to the end of the dispatch.
4478    /// `false` with no window open, which is every one-level image.
4479    pub(crate) fn running_elsewhere(&self, slot: usize) -> bool {
4480        if self.running.is_null() {
4481            return false;
4482        }
4483        let Some(me) = self.exec_lock.and_then(|l| l.current_thread()) else {
4484            return false;
4485        };
4486        let mut r = self.running;
4487        while !r.is_null() {
4488            // SAFETY: a record is linked only for its window and unlinked
4489            // under the lock before its frame ends (`pass`), and the caller
4490            // holds the lock.
4491            let rec = unsafe { &*r };
4492            if rec.slot == slot {
4493                return rec.thread != me;
4494            }
4495            r = rec.next;
4496        }
4497        false
4498    }
4499
4500    /// phase-509 P9b item 2 -- link `rec` into the open windows.
4501    ///
4502    /// # Safety
4503    /// `rec` stays alive and unmoved until [`Self::unlink_running`] removes
4504    /// it, under the lock.
4505    unsafe fn link_running(&mut self, rec: *mut super::exec_lock::Running) {
4506        // SAFETY: the caller's contract.
4507        unsafe { (*rec).next = self.running };
4508        self.running = rec;
4509    }
4510
4511    /// phase-509 P9b item 2 -- unlink `rec`, linked by
4512    /// [`Self::link_running`].
4513    fn unlink_running(&mut self, rec: *mut super::exec_lock::Running) {
4514        let mut at: *mut *mut super::exec_lock::Running = &mut self.running;
4515        // SAFETY: every linked record is alive (`link_running`'s contract),
4516        // and the list is touched only under the lock.
4517        unsafe {
4518            while !(*at).is_null() {
4519                if *at == rec {
4520                    *at = (*rec).next;
4521                    return;
4522                }
4523                at = &mut (**at).next;
4524            }
4525        }
4526    }
4527
4528    /// phase-509 P9b item 2 -- the dispatch level of `slot`'s occupant: its
4529    /// sched context's bucket, and inside `Normal` its rank.
4530    fn slot_level(&self, slot: usize) -> u8 {
4531        let sc_idx = self.sched_context_bindings[slot].0 as usize;
4532        let priority = self
4533            .sched_contexts
4534            .get(sc_idx)
4535            .and_then(|s| s.as_ref())
4536            .map_or(super::sched_context::Priority::Normal, |sc| sc.priority);
4537        let rank = self.slot_tags.get(slot).map_or(0, |t| t.rank);
4538        priority.dispatch_level(rank)
4539    }
4540
4541    /// phase-509 P9b item 2 -- the slots whose dispatch level is in `band`.
4542    /// Every slot for [`super::scheduler::Band::ALL`], the one-level worker's
4543    /// band, without looking at one.
4544    fn band_slots(&self, level: u8, band: super::scheduler::Band) -> super::slot_mask::SlotMask {
4545        // Issue 2541 -- every slot of the table: the carve caps it at the
4546        // mask's capacity, so the old `.min(64)` dropped nothing here any more.
4547        let slots = self.entries.len().min(MAX_CALLBACK_SLOTS);
4548        // phase-509 P9b item 4 -- levels that own their slots by
4549        // registration (a level runner): the worker of `level` runs exactly
4550        // what its level's setup registered, whatever the ranks say.
4551        if self.worker.registering_level != super::scheduler::NO_OWNING_LEVEL {
4552            let mut mask = super::slot_mask::SlotMask::EMPTY;
4553            for i in 0..slots {
4554                if self.entries[i].is_some()
4555                    && self.slot_tags.get(i).is_some_and(|t| t.level == level)
4556                {
4557                    mask.set(i);
4558                }
4559            }
4560            return mask;
4561        }
4562        if band == super::scheduler::Band::ALL {
4563            return super::slot_mask::SlotMask::ALL;
4564        }
4565        let mut mask = super::slot_mask::SlotMask::EMPTY;
4566        for i in 0..slots {
4567            if self.entries[i].is_some() && band.contains(self.slot_level(i)) {
4568                mask.set(i);
4569            }
4570        }
4571        mask
4572    }
4573
4574    /// The callbacks registered from now on belong
4575    /// to level `level`: its worker runs them, and no other does. The first
4576    /// call switches the executor to levels that own their slots by
4577    /// registration (a level runner sets each level up in turn); until then,
4578    /// and on every image that never calls it, a worker's band of dispatch
4579    /// levels decides.
4580    pub fn set_registering_level(&mut self, level: u8) {
4581        self.worker.registering_level = level.min(super::scheduler::NO_OWNING_LEVEL - 1);
4582        // Issue 2018 -- a level's own scheduling context is set after it
4583        // becomes the registering level, never inherited from the last one.
4584        self.worker.registering_sched = 0;
4585    }
4586
4587    /// Give the registering level its own
4588    /// scheduling context: the one its sched task's policy lowers to
4589    /// ([`SchedContext::from_sched_task_policy`](super::sched_context::SchedContext::from_sched_task_policy)).
4590    /// Callbacks registered from now on, until the registering level
4591    /// changes, bind to it unless a node or callback-group binding names
4592    /// another. A level's budget is then charged to that level alone, never
4593    /// to the executor's default context, which every level shares.
4594    ///
4595    /// A `Sporadic` context is created with the executor's cooperative
4596    /// budget (it skips the level's callbacks once the budget is spent, until
4597    /// the period refills it). A runner whose kernel enforces the same
4598    /// budget on the level's thread hands it to the kernel with
4599    /// [`Self::defer_budget_to_kernel`], so the budget is enforced exactly
4600    /// once.
4601    pub fn set_level_sched_context(
4602        &mut self,
4603        sc: super::sched_context::SchedContext,
4604    ) -> Result<super::sched_context::SchedContextId, NodeError> {
4605        let id = self.create_sched_context(sc)?;
4606        self.worker.registering_sched = id.0;
4607        Ok(id)
4608    }
4609
4610    /// The kernel enforces `sc`'s budget on the level's thread
4611    /// (NuttX `SCHED_SPORADIC`, Linux `SCHED_DEADLINE`), so the executor
4612    /// stops enforcing it: the context keeps its class, budget, period and
4613    /// deadline, and its callbacks are no longer skipped for want of budget.
4614    /// One enforcer per level, with one set of numbers. `false` when `sc`
4615    /// carries no cooperative budget (nothing to hand over).
4616    pub fn defer_budget_to_kernel(&mut self, sc: super::sched_context::SchedContextId) -> bool {
4617        match self.sporadic_states.get_mut(sc.0 as usize) {
4618            Some(st @ Some(_)) => {
4619                *st = None;
4620                true
4621            }
4622            _ => false,
4623        }
4624    }
4625
4626    /// Whether `sc`'s budget is enforced by this executor
4627    /// (a cooperative `Sporadic` context the kernel was not handed).
4628    pub fn enforces_budget(&self, sc: super::sched_context::SchedContextId) -> bool {
4629        self.sporadic_states
4630            .get(sc.0 as usize)
4631            .is_some_and(|s| s.is_some())
4632    }
4633
4634    /// The level that owns what is registered now, `None` until
4635    /// a level runner first calls [`Self::set_registering_level`].
4636    pub fn registering_level(&self) -> Option<u8> {
4637        (self.worker.registering_level != super::scheduler::NO_OWNING_LEVEL)
4638            .then_some(self.worker.registering_level)
4639    }
4640
4641    /// Whether a pass ticks a component (or anything else
4642    /// registered) owned by `owner`, the level recorded at registration
4643    /// (`None`: no level owned it).
4644    ///
4645    /// `band_level` is the level of a band pass ([`Self::spin_band_once`]),
4646    /// `None` for a pass of the executor's own worker. When the levels own
4647    /// their slots by registration, a band pass ticks only its level's, and
4648    /// the executor's own worker (the boot level) ticks its own level's and
4649    /// any registered before a level was set. Otherwise the executor's own
4650    /// worker ticks everything and a band pass nothing, as before levels.
4651    pub fn pass_ticks_owner(&self, band_level: Option<u8>, owner: Option<u8>) -> bool {
4652        let owning = self.worker.registering_level != super::scheduler::NO_OWNING_LEVEL;
4653        match band_level {
4654            Some(l) => owning && owner == Some(l),
4655            None => !owning || owner.is_none() || owner == Some(self.worker.level),
4656        }
4657    }
4658
4659    /// The band the executor's own worker runs:
4660    /// every level by default. With band workers over the same executor
4661    /// ([`Self::spin_band_once`]), the bands must partition the levels, so
4662    /// each callback has one worker.
4663    pub fn set_worker_band(&mut self, band: super::scheduler::Band) {
4664        self.worker.band = band;
4665    }
4666
4667    /// One pass of the executor's own worker, through
4668    /// a raw pointer: `spin_once`, except that with a lock that has a thread
4669    /// identity installed ([`super::exec_lock::ExecLock::with_thread_id`]) the
4670    /// lock is released around each user callback, so other threads (band
4671    /// workers, FFI callers) reach the executor while it runs.
4672    ///
4673    /// # Safety
4674    /// `this` points at a live executor. If any other thread can reach it, a
4675    /// lock is installed and the calling thread holds it exactly once, and
4676    /// every other thread takes it before touching the executor. No reference
4677    /// to the executor is live in the caller across this call.
4678    pub unsafe fn spin_once_shared(
4679        this: *mut Self,
4680        timeout: core::time::Duration,
4681    ) -> SpinOnceResult {
4682        let mut discarded = None;
4683        // SAFETY: the caller's contract is `pass`'s.
4684        unsafe { Self::pass(this, PassMode::Shared, timeout, &mut discarded) }
4685    }
4686
4687    /// One pass of a band worker over an executor it
4688    /// shares: the readiness of `worker`'s band, then its callbacks, most
4689    /// urgent level first, the lock released around each one as in
4690    /// [`Self::spin_once_shared`]. A band pass does not park, drive the
4691    /// transport or run the executor-wide chores (parameter and lifecycle
4692    /// services, the monitors' rules): the executor's own worker does.
4693    /// It does tick the components its level registered
4694    /// ([`Self::pass_ticks_owner`]), and the executor's own worker then does
4695    /// not.
4696    ///
4697    /// A worker with a waiter
4698    /// ([`super::scheduler::BandWorker::with_waiter`]) first parks, the lock
4699    /// released, for at most `timeout`: until its band's next timer is due or
4700    /// an arrival in its band signals it. Without one, `timeout` is unused
4701    /// and the pass polls.
4702    ///
4703    /// # Safety
4704    /// As [`Self::spin_once_shared`].
4705    pub unsafe fn spin_band_once(
4706        this: *mut Self,
4707        worker: &mut super::scheduler::BandWorker,
4708        timeout: core::time::Duration,
4709    ) -> SpinOnceResult {
4710        let mut discarded = None;
4711        // SAFETY: the caller's contract is `pass`'s.
4712        unsafe { Self::pass(this, PassMode::Band(worker), timeout, &mut discarded) }
4713    }
4714
4715    /// Link `worker`'s waiter into this executor's
4716    /// arrival routing: an arrival attributed to a slot of its
4717    /// band then wakes it alone, an unattributed one wakes it with the rest.
4718    /// A worker with no waiter polls; this is then a no-op, as on a build
4719    /// with no arrival path. Attach each waiter to one executor, once.
4720    pub fn attach_band_worker(&mut self, worker: &super::scheduler::BandWorker) {
4721        let Some(waiter) = worker.waiter else {
4722            return;
4723        };
4724        waiter
4725            .slots
4726            .store(self.band_slots(worker.level, worker.band));
4727        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
4728        if let Some(ctx) = self.wake_ctx.as_ref() {
4729            let w = waiter as *const super::scheduler::BandWaiter as *mut _;
4730            let head = &ctx.band_waiters;
4731            let mut cur = head.load(portable_atomic::Ordering::Acquire);
4732            loop {
4733                waiter.next.store(cur, portable_atomic::Ordering::Release);
4734                match head.compare_exchange(
4735                    cur,
4736                    w,
4737                    portable_atomic::Ordering::AcqRel,
4738                    portable_atomic::Ordering::Acquire,
4739                ) {
4740                    Ok(_) => break,
4741                    Err(now) => cur = now,
4742                }
4743            }
4744        }
4745    }
4746
4747    /// phase-509 P9b item 2 -- a band pass's prelude: check in as its level,
4748    /// read the clock, and credit its timers with the time since ITS previous
4749    /// pass. Item 3: with a waiter and a positive `timeout`, park first, with
4750    /// the lock released, until the band's next timer is due, an arrival in
4751    /// the band signals the waiter, or `timeout` passes.
4752    ///
4753    /// # Safety
4754    /// As [`Self::owned_prelude`].
4755    unsafe fn band_prelude(
4756        this: *mut Self,
4757        window_lock: Option<super::exec_lock::ExecLock>,
4758        w: &mut super::scheduler::BandWorker,
4759        timeout: core::time::Duration,
4760    ) -> (Option<u64>, u64) {
4761        // SAFETY: the caller's contract; derived again after the park.
4762        let mut s: &mut Self = unsafe { &mut *this };
4763        if let Some(waiter) = w.waiter {
4764            let mask = s.band_slots(w.level, w.band);
4765            waiter.slots.store(mask);
4766            let budget_us = timeout.as_micros().min(u64::MAX as u128) as u64;
4767            // A band timer's remainder is as of the worker's last pass; the
4768            // time since is already spent.
4769            let since_us = match (s.now_us(), w.last_spin_end_us) {
4770                (Some(now), Some(prev)) => now.saturating_sub(prev),
4771                _ => 0,
4772            };
4773            let bound_us = s
4774                .next_timer_deadline_in_us(mask)
4775                .map_or(budget_us, |t| t.saturating_sub(since_us).min(budget_us));
4776            if bound_us > 0 && !s.band_has_arrivals(mask) {
4777                let window = window_lock.map(super::exec_lock::Window::open);
4778                waiter.wait_us(bound_us);
4779                drop(window);
4780                // SAFETY: the lock is held again.
4781                s = unsafe { &mut *this };
4782            }
4783        }
4784        let now = s.now_us();
4785        super::level_liveness::LEVELS.check_in(w.level, now);
4786        match now {
4787            Some(now) => {
4788                let prev = w.last_spin_end_us.unwrap_or(now);
4789                w.last_spin_end_us = Some(now);
4790                (Some(now), now.saturating_sub(prev))
4791            }
4792            None => (None, 0),
4793        }
4794    }
4795
4796    /// phase-509 P9b item 3 -- whether an arrival for one of `mask`'s slots
4797    /// is already in the ready word (it then does not park).
4798    fn band_has_arrivals(&self, mask: super::slot_mask::SlotMask) -> bool {
4799        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
4800        if let Some(ctx) = self.wake_ctx.as_ref() {
4801            return ctx.ready.intersects(mask);
4802        }
4803        let _ = mask;
4804        false
4805    }
4806
4807    /// Microseconds from now to the earliest deadline of a pending
4808    /// supervised route (0 when one is due), or `None` when none is waiting or
4809    /// the executor has no clock. A port that supervises with its own timer
4810    /// (`MECHANISM_TIMER`) re-arms it from this after each spin.
4811    pub fn route_next_due_us(&self) -> Option<u64> {
4812        // No table, no clock read: this runs on every park.
4813        if self.monitor_table.is_empty() {
4814            return None;
4815        }
4816        let clock = self.clock_us_fn?;
4817        super::monitor::route_next_due_us(self.monitor_table, clock())
4818    }
4819
4820    /// Wall microseconds since the last spin ended, the origin every timer's
4821    /// `elapsed_us` is credited from; 0 without a clock.
4822    fn since_last_spin_end_us(&self) -> u64 {
4823        match (self.clock_us_fn, self.last_spin_end_us) {
4824            (Some(clock), Some(prev)) => clock().saturating_sub(prev),
4825            _ => 0,
4826        }
4827    }
4828
4829    /// A [`RouteWatch`](super::monitor::RouteWatch) over this
4830    /// executor's supervised routes, which a port's timer or reaction thread
4831    /// reads from outside the spin thread: at its expiry it sees a route the
4832    /// running spin has already answered, without waiting for the spin to
4833    /// return. `None` without a monitor table or a clock. Take it after
4834    /// `set_monitor_table` and any clock change.
4835    pub fn route_watch(&self) -> Option<super::monitor::RouteWatch> {
4836        if self.monitor_table.is_empty() {
4837            return None;
4838        }
4839        let clock = self.clock_us_fn?;
4840        Some(super::monitor::RouteWatch::new(self.monitor_table, clock))
4841    }
4842
4843    /// Issue #515 — warn about periods the spin cadence cannot express.
4844    ///
4845    /// A timer fires on the first spin at or after its period elapses, so
4846    /// a period that is not an integer multiple of the executor's spin
4847    /// period lands on the spin grid instead of the declared cadence: a
4848    /// 33 ms timer on a 5 ms spin alternates 35 ms / 30 ms, mean 33.0.
4849    /// The rate is preserved and no activation is dropped, so every
4850    /// runtime rule is (correctly) silent — the jitter stays invisible
4851    /// until someone measures cadence on target.
4852    ///
4853    /// Runs ONCE, on the first spin carrying a non-zero timeout, because
4854    /// that timeout is where the sched task's declared spin period becomes
4855    /// visible down here. A resolve-time diagnostic would be better
4856    /// still — the toolchain holds both numbers before the image is
4857    /// built — but this backstop needs no board or codegen change and
4858    /// catches hand-written spin loops too.
4859    /// phase-436 W1 (issue 1192) — how long the executor may park, in
4860    /// microseconds, given the caller's budget.
4861    ///
4862    /// The park used to be bounded by the caller's timeout narrowed by exactly
4863    /// one input, the BACKEND's `next_deadline_ms`. A registered timer is a
4864    /// deadline the EXECUTOR owns, and nothing let it shorten the sleep — so
4865    /// ~~`spin_default`~~'s 50 ms slept straight past a 10 ms timer, and the
4866    /// activations then arrived in the burst issue 0505 describes.
4867    ///
4868    /// This is the `min` over the deadline sources phase-436 names. The
4869    /// caller's budget is always a member, so the result is never unbounded
4870    /// and never zero-by-omission: with no timers registered the budget
4871    /// stands, which keeps a long idle wait a wait rather than a poll.
4872    ///
4873    /// Distinct from issue 0515's audit, which warns that a period does not
4874    /// divide the spin grid. That takes the grid as given; this moves it.
4875    ///
4876    /// `#[cfg(test)]`-gated (matching `mod tests`'s own gate in `mod.rs`):
4877    /// production code calls `next_wake_bound_attributed_us` directly to get
4878    /// the source alongside the bound, so this `.0`-only convenience has no
4879    /// caller outside the test module and is dead code in any build that
4880    /// does not compile it (every `cargo check`/`cargo doc`, and `cargo test
4881    /// --features rmw-cffi`, which excludes `mod tests` too).
4882    #[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
4883    pub(crate) fn next_wake_bound_us(&self, budget_us: u64) -> u64 {
4884        self.next_wake_bound_attributed_us(budget_us, None).0
4885    }
4886
4887    /// Contribute a deadline source.
4888    ///
4889    /// The core never names an RTOS: a port registers `k_poll`, `epoll`, a
4890    /// queue set or a device ISR here, and the executor only ever asks "when
4891    /// will you next need me?".
4892    ///
4893    /// Refuses past capacity rather than dropping silently. A source that was
4894    /// quietly discarded would leave the executor sleeping past a deadline it
4895    /// had been told about, which is the failure this whole phase exists to
4896    /// remove.
4897    pub fn register_wake_source(
4898        &mut self,
4899        next: NextDeadlineFn,
4900        ctx: *mut core::ffi::c_void,
4901    ) -> Result<WakeSourceId, NodeError> {
4902        if self.worker.wake_source_count as usize >= MAX_WAKE_SOURCES {
4903            return Err(NodeError::ExecutorFull);
4904        }
4905        let idx = self.worker.wake_source_count as usize;
4906        self.worker.wake_sources[idx] = Some(WakeSourceSlot { next, ctx });
4907        self.worker.wake_source_count += 1;
4908        Ok(WakeSourceId::Platform(idx as u8))
4909    }
4910
4911    /// Install THE thing that blocks. Singular by nature — only one primitive
4912    /// can actually wait — so this replaces whatever was there.
4913    /// `granularity_us` is the finest park this primitive can actually
4914    /// express. The port states it because only the port knows: the ABI
4915    /// signature is not the limit — an RTOS tick is a second, coarser one, and
4916    /// a timespec primitive is a finer one.
4917    pub(crate) fn set_park_primitive(
4918        &mut self,
4919        park: ParkUntilFn,
4920        ctx: *mut core::ffi::c_void,
4921        granularity_us: u64,
4922    ) {
4923        self.worker.park_primitive = Some((park, ctx));
4924        self.worker.park_granularity_declared_us = granularity_us;
4925    }
4926
4927    /// Issue 2225 (RFC-0113 D9) -- install (`Some`) or clear (`None`) the hook
4928    /// the executor's wake object calls after every signal: a backend's
4929    /// arrival callback, an attributed entity wake, the signal-fd worker. The
4930    /// wake half of a yielding park slot, for a sched task that never waits on the
4931    /// object itself. Returns `false` when this build has no wake object.
4932    ///
4933    /// `ctx` must outlive the hook: clear it before `ctx` goes away.
4934    pub(crate) fn set_wake_hook(
4935        &mut self,
4936        hook: Option<WakeHookFn>,
4937        ctx: *mut core::ffi::c_void,
4938    ) -> bool {
4939        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
4940        if let Some(w) = self.node_wake.as_ref() {
4941            w.set_hook(hook, ctx);
4942            return true;
4943        }
4944        let _ = (hook, ctx);
4945        false
4946    }
4947
4948    /// The wake primitive a port must hand its `ParkUntilFn` as `ctx`, or NULL
4949    /// when this build has none.
4950    ///
4951    /// phase-436 W7 — a park that waits on its own fresh object is NOT
4952    /// breakable by the backend's listener, and installing one makes latency
4953    /// worse: once a port has parked, the transport drain drops to
4954    /// non-blocking, so an unbreakable park sleeps out its full deadline with
4955    /// data already waiting. Waiting on THIS object keeps the async break.
4956    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
4957    pub(crate) fn wake_raw_ptr(&self) -> *mut core::ffi::c_void {
4958        match self.node_wake.as_ref() {
4959            Some(w) => w.raw_ptr(),
4960            None => core::ptr::null_mut(),
4961        }
4962    }
4963
4964    /// The level this executor runs, 0 the
4965    /// most urgent. An executor's runner sets it ([`Self::set_level`]); one it
4966    /// never set is level 0, which is every executor of a one-level image.
4967    /// It matches the generated `NROS_ENTRY_LEVEL_OF_<node>` of the nodes the
4968    /// executor hosts.
4969    pub fn level(&self) -> u8 {
4970        self.worker.level
4971    }
4972
4973    /// Set the level this executor runs; its spins check in
4974    /// as that level. `false`, and nothing changed, at or past
4975    /// [`MAX_LEVELS`](super::MAX_LEVELS).
4976    pub fn set_level(&mut self, level: u8) -> bool {
4977        if level as usize >= super::level_liveness::MAX_LEVELS {
4978            return false;
4979        }
4980        self.worker.level = level;
4981        true
4982    }
4983
4984    /// Whether a platform park primitive is installed.
4985    pub fn has_park_primitive(&self) -> bool {
4986        self.worker.park_primitive.is_some()
4987    }
4988
4989    /// The bound and the source that produced it: the `min` over every
4990    /// deadline source, with the caller's budget as an ordinary member.
4991    ///
4992    /// The budget being a member is what makes the result never unbounded and
4993    /// never zero-by-omission, and it is why "no sources registered" needs no
4994    /// special case.
4995    pub(crate) fn next_wake_bound_attributed_us(
4996        &self,
4997        budget_us: u64,
4998        session_us: Option<u64>,
4999    ) -> (u64, WakeSourceId) {
5000        let mut best = (budget_us, WakeSourceId::CallerBudget);
5001
5002        // The backend's next internal event is a MEMBER, not a pre-cap. It was
5003        // folded into the budget upstream, which meant a park the session
5004        // actually won reported `CallerBudget` — the attribution named the
5005        // wrong source, and "why did we wake" is the question attribution
5006        // exists to answer.
5007        if let Some(s) = session_us
5008            && s < best.0
5009        {
5010            best = (s, WakeSourceId::Session);
5011        }
5012
5013        // Issue 2143 -- a timer's remainder is as of the last spin's END, the
5014        // point its `elapsed_us` was last credited; the time the host spent
5015        // since (a sleep between spins, the work of its own loop) is already
5016        // spent. Without this the bound was measured from a stale origin and
5017        // overslept the timer by exactly that gap -- the band prelude makes the
5018        // same correction for its own worker.
5019        if let Some(timer_us) = self
5020            .next_timer_deadline_us()
5021            .map(|t| t.saturating_sub(self.since_last_spin_end_us()))
5022            && timer_us < best.0
5023        {
5024            best = (timer_us, WakeSourceId::Timer);
5025        }
5026
5027        // phase-503 — a supervised route's deadline is the executor's own, like
5028        // a timer's: the park must end there, or a route whose output never
5029        // comes is judged only when something else wakes the loop.
5030        if let Some(due_us) = self.route_next_due_us()
5031            && due_us < best.0
5032        {
5033            best = (due_us, WakeSourceId::RouteDeadline);
5034        }
5035
5036        for (i, slot) in self.worker.wake_sources.iter().enumerate() {
5037            let Some(slot) = slot else { continue };
5038            // SAFETY: the callback and ctx were supplied together by the port
5039            // through `register_wake_source` and outlive the executor by its
5040            // contract; the call takes no ownership.
5041            let due = unsafe { (slot.next)(slot.ctx) };
5042            // `u64::MAX` is "nothing pending" — an async source spells itself
5043            // this way and breaks the park by signalling instead.
5044            if due != u64::MAX && due < best.0 {
5045                best = (due, WakeSourceId::Platform(i as u8));
5046            }
5047        }
5048
5049        best
5050    }
5051
5052    /// The bound the last park used, and which source won it.
5053    pub fn last_park(&self) -> (u64, WakeSourceId) {
5054        (self.worker.last_park_bound_us, self.worker.last_park_source)
5055    }
5056
5057    /// The park the platform was actually asked for, after
5058    /// rounding the request up to an expressible value.
5059    ///
5060    /// Differs from `last_park().0` exactly when the request did not land on
5061    /// the platform's grid. Both are reported because a cadence that cannot be
5062    /// waited in must not be presented as if it were met.
5063    pub fn last_park_achieved_us(&self) -> u64 {
5064        self.worker.last_park_achieved_us
5065    }
5066
5067    /// The granularity the release-jitter
5068    /// measurement was actually made at, in microseconds.
5069    ///
5070    /// The jitter statistic is reported in microseconds, but the mechanism
5071    /// that PACES the loop decides how fine it can honestly be, and there are
5072    /// two mechanisms:
5073    ///
5074    /// * **No declared cadence** — the loop is paced by the blocking wait
5075    ///   itself, so it cannot come round more precisely than one park granule.
5076    ///   Reporting µs there is precision the wait cannot deliver.
5077    /// * **A declared cadence** (`set_spin_nominal_us`) — the caller paces
5078    ///   itself, as nros-cpp's sched tasks do with `platform_sleep_us` between
5079    ///   spins. That sleep is finer than the wait, so the measurement really
5080    ///   is good to a microsecond and coarsening it would understate it.
5081    ///
5082    /// Reported rather than applied: this does not change what the monitor
5083    /// judges, because silently coarsening a bound could mask real lateness.
5084    /// It says what the number is worth.
5085    pub fn release_jitter_granularity_us(&self) -> u64 {
5086        if self.spin_nominal_self_paced() {
5087            1
5088        } else {
5089            self.park_granularity_us()
5090        }
5091    }
5092
5093    /// The finest park this build can actually express, in microseconds.
5094    ///
5095    /// Comes from the INSTALLED primitive, because only the port knows. The
5096    /// exported ABI signature is not the limit in either direction (issue
5097    /// 1242):
5098    ///
5099    /// * an RTOS tick is a COARSER limit — ThreadX pins
5100    ///   `TX_TIMER_TICKS_PER_SECOND = 100`, a 10 ms tick, so a 1 ms park is not
5101    ///   achievable there however the ABI is spelled;
5102    /// * a timespec primitive is a FINER one — POSIX's `sem_timedwait` and
5103    ///   `pthread_cond_timedwait` are nanosecond-native, and only the
5104    ///   `uint32_t timeout_ms` signature floors them at a millisecond.
5105    ///
5106    /// This was a hardcoded `1_000` justified by "every `nros_platform_wake_*`
5107    /// port takes `uint32_t timeout_ms`". That was right for FreeRTOS by
5108    /// coincidence and wrong for the other two, and it made the W3 jitter
5109    /// report over-claim on ThreadX — the failure W3 exists to prevent,
5110    /// reproduced one layer below W3 in its own dependency.
5111    ///
5112    /// With nothing installed the fallback is 1 ms, which IS the honest floor
5113    /// of the `wake_wait_ms` ABI every port exports today.
5114    ///
5115    /// The declared granularity counts only while the park is USABLE. An
5116    /// executor whose backend has no live wake (XRCE, or a session whose
5117    /// callback is gone) never parks: `spin_once` waits in the transport's
5118    /// own receive instead, whose timeout is whole milliseconds. Claiming a
5119    /// POSIX park's 1 us there over-claimed the jitter report, and worse,
5120    /// rounded the bound to microseconds that the millisecond wait then
5121    /// truncated, so a sub-millisecond deadline became a non-blocking receive
5122    /// and the loop spun hot until it passed.
5123    pub fn park_granularity_us(&self) -> u64 {
5124        if self.worker.park_granularity_declared_us != 0
5125            && self.worker.park_primitive.is_some()
5126            && self.park_can_be_woken()
5127        {
5128            self.worker.park_granularity_declared_us
5129        } else {
5130            1_000
5131        }
5132    }
5133
5134    /// phase-436 — whether a park could be ended early by data arriving.
5135    ///
5136    /// A park ends on its bound or on the wake object. With a poll-only
5137    /// backend (XRCE), or a session whose wake callback is gone, nothing
5138    /// signals that object, so a park would be a blind sleep and data
5139    /// arriving mid-park would wait out the whole bound — the Phase 127.C.4
5140    /// stall (a reliable stream whose ACK lands in a session nobody drives).
5141    /// Builds without `alloc` + `rmw-cffi` have no wake callback at all and
5142    /// park as they always did.
5143    pub(crate) fn park_can_be_woken(&self) -> bool {
5144        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
5145        {
5146            self.async_wake_live()
5147        }
5148        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
5149        {
5150            true
5151        }
5152    }
5153
5154    /// The budget an entry's spin loop passes to
5155    /// [`spin_once`](Self::spin_once).
5156    ///
5157    /// An entry loop is `loop { spin_once(budget) }`, and each park already
5158    /// ends at the next deadline the executor knows (a timer, a backend's next
5159    /// internal event, a platform source) or on the wake object. So the
5160    /// budget is not a cadence: it bounds only a park nothing else bounds.
5161    /// Every entry used to pass 10 ms, which woke an idle tier 100 times a
5162    /// second whatever its park could do.
5163    ///
5164    /// [`ENTRY_IDLE_BUDGET`] when every session can end the wait itself: it
5165    /// states `Notify` with its wake callback live, or `Waitable` (whose
5166    /// handle the port multiplexes with the wake object). A cancel and a
5167    /// hosted termination post the same wake object. Otherwise
5168    /// [`ENTRY_POLL_BUDGET`]: what is left can wait on the wake object without
5169    /// its data posting it (a wake fan-out with no free member, more waitable
5170    /// sessions than one park multiplexes, a port with no wake object), so the
5171    /// short budget bounds how long its data waits. A session with no
5172    /// readiness form never gets here: it is refused at open.
5173    /// An enrolled component whose `tick` does work (it polls a service reply
5174    /// or completes action goals once per spin) also keeps the slice, so its
5175    /// tick rate does not change under it.
5176    pub fn entry_spin_budget(&self) -> core::time::Duration {
5177        if self.every_session_ends_the_wait() && !self.has_ticking_component() {
5178            ENTRY_IDLE_BUDGET
5179        } else {
5180            ENTRY_POLL_BUDGET
5181        }
5182    }
5183
5184    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
5185    fn every_session_ends_the_wait(&self) -> bool {
5186        use nros_rmw::{ReadinessSource, Session as _};
5187        if self.node_wake.is_none() {
5188            return false;
5189        }
5190        let notify_live = self.async_wake_live();
5191        let primary = core::iter::once(self.session.readiness_source());
5192        let extra = self.extra_sessions.iter().map(|e| e.readiness_source());
5193        let mut waitable = 0usize;
5194        for source in primary.chain(extra) {
5195            match source {
5196                ReadinessSource::Waitable(_) => waitable += 1,
5197                ReadinessSource::Notify if notify_live => {}
5198                _ => return false,
5199            }
5200        }
5201        // More waitable sessions than one park multiplexes cannot be parked
5202        // on at all (`waitable_handles`).
5203        waitable <= MAX_WAITABLE_HANDLES
5204    }
5205
5206    #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
5207    fn every_session_ends_the_wait(&self) -> bool {
5208        false
5209    }
5210
5211    /// phase-521 W3 (RFC-0113 D3) -- write the `ReadinessSource::Waitable`
5212    /// handles of this executor's sessions (primary first, then the extra
5213    /// ones) into `out`, and return how many. Asked every spin: a session's
5214    /// handle exists only once its transport is connected.
5215    ///
5216    /// More waitable sessions than `out` holds is answered with ZERO, not a
5217    /// truncated set: parking on some handles but not others would be a missed
5218    /// wake. Zero leaves the executor on the short entry budget, whose drain
5219    /// sees all of them.
5220    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
5221    pub(crate) fn waitable_handles(&self, out: &mut [i32; MAX_WAITABLE_HANDLES]) -> usize {
5222        use nros_rmw::{ReadinessSource, Session as _};
5223        let mut n = 0;
5224        let primary = core::iter::once(self.session.readiness_source());
5225        let extra = self.extra_sessions.iter().map(|e| e.readiness_source());
5226        for source in primary.chain(extra) {
5227            if let ReadinessSource::Waitable(fd) = source {
5228                if n == out.len() {
5229                    return 0;
5230                }
5231                out[n] = fd;
5232                n += 1;
5233            }
5234        }
5235        n
5236    }
5237
5238    /// Drive the primary session for `timeout_ms`, the transport-side half of
5239    /// the wait.
5240    ///
5241    /// phase-521 W6 (RFC-0113 D2) — after a park this is always a zero, so it
5242    /// drains rather than waits. The guard slices phase-436 cut a poll-only
5243    /// backend's receive into are gone with that backend: a session that
5244    /// states no readiness form is refused at open (D5), so nothing waits
5245    /// inside a transport's `recv` for a trigger that cannot end it.
5246    fn drive_primary(&mut self, timeout_ms: i32) -> Result<(), TransportError> {
5247        self.session.drive_io(timeout_ms)
5248    }
5249
5250    pub(crate) fn round_park_up_us(&self, requested_us: u64) -> u64 {
5251        if requested_us == 0 {
5252            return 0;
5253        }
5254        let g = self.park_granularity_us();
5255        if g <= 1 {
5256            return requested_us;
5257        }
5258        requested_us.div_ceil(g).saturating_mul(g)
5259    }
5260
5261    /// Microseconds until the soonest live timer is due, or `None` when no
5262    /// timer is pending.
5263    ///
5264    /// A timer that is cancelled, or a one-shot that already fired, owes
5265    /// nothing and must not hold the park short — otherwise the executor keeps
5266    /// waking on a deadline nobody is waiting for.
5267    ///
5268    /// So does a timer whose remainder is not WALL microseconds
5269    /// ([`TimerClockSource::remaining_is_wall_time`], issue 1321): the number
5270    /// this returns is handed to the port's park primitive, so a ROS-time
5271    /// timer's simulated remainder would be a units error — and on a paused
5272    /// `/clock` a frozen one, waking the image once per timer period forever.
5273    /// Its wake source is a `/clock` message, which reaches `drive_io` like
5274    /// any sample.
5275    ///
5276    /// phase-509 P9b item 3 -- the executor's own worker's timers: those of
5277    /// its band (every timer for the one-level worker), so it does not wake
5278    /// for a timer another band's worker runs.
5279    pub(crate) fn next_timer_deadline_us(&self) -> Option<u64> {
5280        self.next_timer_deadline_in_us(self.band_slots(self.worker.level, self.worker.band))
5281    }
5282
5283    // phase-562 W10.
5284    /// The earliest timer deadline of `level`'s band, in
5285    /// microseconds after that level's most recent pass. `None` when the band
5286    /// arms no timer.
5287    ///
5288    /// A band's timers are credited their elapsed time only by that band's own
5289    /// pass, so the number is exact only when read at the end of the pass:
5290    /// that is where a level runner reads it, to arm a board timer whose
5291    /// interrupt wakes the level. An RTIC level cannot park on a timed wait of
5292    /// its own (its software task runs to completion, and a high-priority task
5293    /// that blocked would starve every level below it), and the boot worker's
5294    /// park is bounded by its own band only (`next_timer_deadline_us`),
5295    /// so without that timer a higher band's due timer would wait out the boot
5296    /// level's whole idle park.
5297    pub fn next_timer_deadline_of_level_us(&self, level: u8) -> Option<u64> {
5298        self.next_timer_deadline_in_us(self.band_slots(level, super::scheduler::Band::ALL))
5299    }
5300
5301    /// phase-509 P9b item 3 -- [`Self::next_timer_deadline_us`] over the
5302    /// timers in `mask`'s slots.
5303    pub(crate) fn next_timer_deadline_in_us(
5304        &self,
5305        mask: super::slot_mask::SlotMask,
5306    ) -> Option<u64> {
5307        let arena_ptr = self.arena.as_ptr() as *const u8;
5308        let mut soonest: Option<u64> = None;
5309        for (i, meta) in self.entries.iter().enumerate() {
5310            let Some(meta) = meta else { continue };
5311            if i < MAX_CALLBACK_SLOTS && !mask.test(i) {
5312                continue;
5313            }
5314            // phase-509 P9b item 2 -- not a timer running in another worker's
5315            // window: its header is that worker's while it runs, and a
5316            // running timer is not the one to wait for.
5317            if !matches!(meta.kind, EntryKind::Timer) || Self::slot_held(self.slot_tags, i) {
5318                continue;
5319            }
5320            // SAFETY: a Timer entry's arena slot holds a `TimerEntry<F>`, whose
5321            // leading layout is `TimerHeader` — the same projection
5322            // `audit_spin_quantization` relies on.
5323            let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
5324            if header.cancelled || header.period_us == 0 {
5325                continue;
5326            }
5327            if header.oneshot && header.fired {
5328                continue;
5329            }
5330            // Issue 1321 — the park is WALL microseconds, so only a timer
5331            // whose own clock runs in them may bound it.
5332            if !header.clock_source.remaining_is_wall_time() {
5333                continue;
5334            }
5335            // Already due: the bound is zero, and no other timer can beat it.
5336            let remaining = header.period_us.saturating_sub(header.elapsed_us);
5337            soonest = Some(match soonest {
5338                Some(cur) => cur.min(remaining),
5339                None => remaining,
5340            });
5341            if remaining == 0 {
5342                break;
5343            }
5344        }
5345        soonest
5346    }
5347
5348    fn audit_spin_quantization(&mut self, spin_us: u64) {
5349        self.spin_quantized_timers(spin_us, |period_us, early_us, late_us| {
5350            nros_log::log_warn!(
5351                nros_log::get_logger("nros"),
5352                "timer period {} us is not a multiple of the {} us spin period: activations will alternate between {} us and {} us (mean cadence preserved)",
5353                period_us,
5354                spin_us,
5355                early_us,
5356                late_us
5357            );
5358        });
5359    }
5360
5361    /// Each timer the executor's own worker runs whose period `spin_us`
5362    /// quantizes, as `(period_us, early_us, late_us)`. Split out of
5363    /// [`Self::audit_spin_quantization`], which only logs, so the choice of
5364    /// timers can be asserted.
5365    ///
5366    /// Issue 2050 -- only the timers in the worker's own band
5367    /// ([`Self::band_slots`], the same mask its pass dispatches from). In a
5368    /// level runner the executor's own worker is the boot level, paced at the
5369    /// boot level's spin period, while a spawned level's timers run on that
5370    /// level's band worker, whose park is bounded by its next timer deadline.
5371    /// Auditing every timer judged a 1 ms timer on a spawned level against a
5372    /// 10 ms boot spin it never ran under.
5373    pub(crate) fn spin_quantized_timers(&self, spin_us: u64, mut f: impl FnMut(u64, u64, u64)) {
5374        if spin_us == 0 {
5375            return;
5376        }
5377        let mask = self.band_slots(self.worker.level, self.worker.band);
5378        let arena_ptr = self.arena.as_ptr() as *const u8;
5379        for (i, meta) in self.entries.iter().enumerate() {
5380            let Some(meta) = meta.as_ref() else {
5381                continue;
5382            };
5383            if i < MAX_CALLBACK_SLOTS && !mask.test(i) {
5384                continue;
5385            }
5386            if !matches!(meta.kind, EntryKind::Timer) || Self::slot_held(self.slot_tags, i) {
5387                continue;
5388            }
5389            // SAFETY: a Timer entry's arena slot holds a `TimerEntry<F>`,
5390            // whose leading layout is `TimerHeader`.
5391            let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
5392            let period_us = header.period_us;
5393            let Some((early_us, late_us)) =
5394                spin_quantization_span(header.clock_source, period_us, spin_us)
5395            else {
5396                continue;
5397            };
5398            f(period_us, early_us, late_us);
5399        }
5400    }
5401
5402    /// Whether the executor logs each violation as it is
5403    /// detected (the default).
5404    ///
5405    /// Turn this off in an application that reports violations its own
5406    /// way via [`Self::drain_violations`]; the ring is unaffected
5407    /// either way.
5408    pub fn set_report_violations(&mut self, enabled: bool) {
5409        self.violations.report = enabled;
5410    }
5411
5412    /// The drain-and-report hook: at the end of every spin,
5413    /// drain the ring and log each entry with its sequence number and the
5414    /// `total` / `dropped` counters (`contract violation #N: <rule> <fqn>
5415    /// measured=.. declared=.. (total=.. dropped=..)`).
5416    ///
5417    /// While on it REPLACES the log line at detection, so one verdict is one
5418    /// line, and an application that wanted to drain the ring itself sees an
5419    /// empty one. The generated C/C++ entries turn it on when the image sets
5420    /// `CONFIG_NROS_VIOLATION_DRAIN_REPORT` (off by default). The trace marker
5421    /// (`callback_trace::MARKER_VIOLATION`) and the SWD record do not depend
5422    /// on it: both are written at detection.
5423    pub fn set_violation_drain_report(&mut self, enabled: bool) {
5424        self.violations.drain_report = enabled;
5425    }
5426
5427    /// Violations evicted from the full ring
5428    /// before any drain took them.
5429    ///
5430    /// The ring keeps the LATEST `MAX_VIOLATIONS`, so non-zero means the
5431    /// OLDEST verdicts were lost, never the newest. (Before, a full
5432    /// ring refused the push, which kept the first verdicts since boot and
5433    /// lost every later one.)
5434    pub fn violations_dropped(&self) -> u32 {
5435        self.violations.counts.dropped
5436    }
5437
5438    /// Contract violations this executor stored since boot
5439    /// (wrapping). The newest entry in the ring is number `violations_total()`;
5440    /// `total - dropped - pending` is how many drains have taken.
5441    pub fn violations_total(&self) -> u32 {
5442        self.violations.counts.total
5443    }
5444
5445    /// Drain pending contract violations, OLDEST first.
5446    /// Draining clears the ring. Call between spins, never from a callback.
5447    pub fn drain_violations(&mut self, mut f: impl FnMut(&super::monitor::Violation)) {
5448        self.violations.drain(|_, v| f(v));
5449    }
5450
5451    /// [`Self::drain_violations`] with each entry's sequence number (1-based,
5452    /// per executor; the same number the drain-and-report line and the trace
5453    /// marker carry), so a reader can tell a gap from a quiet interval.
5454    pub fn drain_violations_numbered(&mut self, f: impl FnMut(u32, &super::monitor::Violation)) {
5455        self.violations.drain(f);
5456    }
5457
5458    /// Choose when this executor's contract monitors arm,
5459    /// overriding the build default (`NROS_MONITOR_ARM_ON_CALL`,
5460    /// `NROS_MONITOR_ARM_GRACE_MS`). Call before the first spin (an
5461    /// `arm_monitors` made before it is undone by this); after the first spin
5462    /// an executor that already armed stays armed.
5463    ///
5464    /// `on_call`: wait for [`Self::arm_monitors`] or
5465    /// [`super::monitor::request_monitor_arming`] (`rclc_monitors_arm()`).
5466    /// `grace_ms`: arm anyway that long after the first spin (0 = never by
5467    /// deadline; with `on_call == false`, 0 means "at the first spin").
5468    pub fn set_monitor_arming(&mut self, on_call: bool, grace_ms: u32) {
5469        let v = &mut self.violations.counts;
5470        v.arm_on_call = on_call;
5471        v.arm_grace_ms = grace_ms;
5472        if !v.spun {
5473            // Before the first spin, "armed" is just the policy's answer (no
5474            // rule has run yet); the first spin counts the arming once.
5475            v.armed = super::monitor::MonitorArming { on_call, grace_ms }.armed_at_first_spin();
5476        }
5477    }
5478
5479    /// The application says its start-up is over: this
5480    /// executor's monitors start judging now. Idempotent.
5481    ///
5482    /// Judgement restarts at arming: every rate/age/silence window reopens,
5483    /// a latency or age measured before arming is discarded, the release-
5484    /// jitter statistics are cleared (so the figure after RUN is RUN's), and a
5485    /// stack low-water mark already past the declared minimum is reported
5486    /// again, because stack depth reached at start-up is a real fault, not
5487    /// start-up noise.
5488    pub fn arm_monitors(&mut self) {
5489        self.arm_now("the application armed them");
5490    }
5491
5492    /// Whether this executor's monitors are armed.
5493    pub fn monitors_armed(&self) -> bool {
5494        self.violations.counts.armed
5495    }
5496
5497    /// Verdicts reached before the monitors armed: counted,
5498    /// never stored, logged, sunk or traced.
5499    pub fn violations_suppressed_before_arm(&self) -> u32 {
5500        self.violations.counts.suppressed_before_arm
5501    }
5502
5503    fn arm_now(&mut self, why: &str) {
5504        if self.violations.counts.armed {
5505            return;
5506        }
5507        self.violations.counts.armed = true;
5508        for st in self.monitor_states.iter_mut() {
5509            *st = super::monitor::MonitorState::default();
5510        }
5511        for st in self.age_states.iter_mut() {
5512            *st = super::monitor::AgeState::default();
5513        }
5514        for spec in self.monitor_table.iter() {
5515            spec.cell
5516                .max_latency_us
5517                .store(0, core::sync::atomic::Ordering::Relaxed);
5518        }
5519        // phase10-B3 -- a take waiting since start-up is not a route of RUN's.
5520        super::monitor::route_reset(self.monitor_table);
5521        for spec in self.age_table.iter() {
5522            spec.cell
5523                .max_age_ms
5524                .store(0, core::sync::atomic::Ordering::Relaxed);
5525            spec.cell
5526                .takes
5527                .store(0, core::sync::atomic::Ordering::Relaxed);
5528            spec.cell
5529                .arrivals
5530                .store(0, core::sync::atomic::Ordering::Relaxed);
5531        }
5532        self.clear_release_jitter_stats();
5533        self.worker.stack_headroom_reported = usize::MAX;
5534        self.worker.stack_headroom_last_check_us = None;
5535        // Counted once per executor: here once it has spun, else by the first
5536        // spin (which counts an executor that is armed by then either way).
5537        #[cfg(nros_boot_report)]
5538        if self.violations.counts.spun {
5539            super::monitor::NROS_VIOLATION_RECORD
5540                .armed
5541                .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
5542        }
5543        nros_log::log_info!(
5544            nros_log::get_logger("nros"),
5545            "contract monitors armed ({}); {} verdict(s) before arming suppressed",
5546            why,
5547            self.violations.counts.suppressed_before_arm
5548        );
5549    }
5550
5551    /// phase-474 I2 -- once per spin, before any rule runs: note the first
5552    /// spin, and arm when the policy says so.
5553    fn update_monitor_arming(&mut self, now_us: Option<u64>) {
5554        // Milliseconds in a wrapping `u32`, like the silence rule's lease
5555        // (`AgeState::last_take_ms`): this state is inline in the `Executor`
5556        // value, whose size is budgeted (issue 0961).
5557        let now_ms = now_us.map(|us| (us / 1_000) as u32);
5558        let v = &mut self.violations.counts;
5559        if !v.spun {
5560            v.spun = true;
5561            v.first_spin_ms = now_ms.unwrap_or(0);
5562            if v.armed {
5563                // Armed from the start (the default), or by a call made before
5564                // the first spin: count it in the record so a reader sees how
5565                // many executors are judging.
5566                #[cfg(nros_boot_report)]
5567                super::monitor::NROS_VIOLATION_RECORD
5568                    .armed
5569                    .fetch_add(1, core::sync::atomic::Ordering::Relaxed);
5570                return;
5571            }
5572            if (super::monitor::MonitorArming {
5573                on_call: v.arm_on_call,
5574                grace_ms: v.arm_grace_ms,
5575            })
5576            .armed_at_first_spin()
5577            {
5578                self.arm_now("at the first spin");
5579                return;
5580            }
5581        }
5582        if v.armed {
5583            return;
5584        }
5585        if super::monitor::arm_requests() != v.arm_requests_seen {
5586            self.arm_now("the application asked: rclc_monitors_arm");
5587            return;
5588        }
5589        let grace_ms = v.arm_grace_ms;
5590        if grace_ms == 0 {
5591            return;
5592        }
5593        match now_ms {
5594            Some(now) if now.wrapping_sub(v.first_spin_ms) >= grace_ms => {
5595                self.arm_now("the grace period after the first spin elapsed");
5596            }
5597            // No clock: a grace period cannot elapse, and waiting forever would
5598            // leave the image unmonitored. Arm rather than guess a duration.
5599            None if !v.arm_on_call => {
5600                self.arm_now("no clock to time the grace period");
5601            }
5602            _ => {}
5603        }
5604    }
5605
5606    /// Hand every stored violation to `sink`, beside the log line
5607    /// (the floor every image keeps) and the ring push.
5608    ///
5609    /// Not at detection any more: the verdict is queued and
5610    /// leaves from `Executor::flush_violation_reports` at the end of a spin with
5611    /// slack, so the report never costs the dispatch it judges.
5612    ///
5613    /// Before this nothing in a generated image drained the ring, so the log
5614    /// line was the only output and `/diagnostics` stayed silent on every C
5615    /// and C++ road. A report point the RUNTIME owns reaches every road at
5616    /// once — every board's spin loop goes through the executor — where one
5617    /// per entry template would have to be rebuilt for each board runner. The
5618    /// ring is still filled, so an application (or a fixture) that drains it
5619    /// with [`Self::drain_violations`] sees exactly what it did before.
5620    /// `None` removes the sink.
5621    ///
5622    /// # Safety
5623    /// `ctx` must stay valid for every call of the sink until it is replaced
5624    /// or this executor is dropped (see [`super::monitor::ViolationSink`]).
5625    pub unsafe fn set_violation_sink(
5626        &mut self,
5627        sink: Option<(super::monitor::ViolationSink, *mut core::ffi::c_void)>,
5628    ) {
5629        self.violations.sink = sink.map(|(f, ctx)| (f, ctx as usize));
5630        if self.violations.sink.is_none() {
5631            // Nothing is left to send them to.
5632            self.violations.reports.pending.clear();
5633            self.violations.reports.since_us = None;
5634        }
5635    }
5636
5637    /// phase-474 I7 -- hand the queued verdicts to the sink, if this is a slot
5638    /// for it. Called at the end of every spin, after its dispatches and its
5639    /// rules, so the report never runs inside the tick being judged.
5640    ///
5641    /// A slot is a spin end whose next timer is due no sooner than the last
5642    /// report took (`ReportQueue::last_cost_us`; 0 before the first report, so
5643    /// the first goes at the first spin end with no timer already due), or
5644    /// any spin end once the oldest pending verdict has waited
5645    /// [`REPORT_DEFER_MAX_US`](super::monitor::REPORT_DEFER_MAX_US). Without a
5646    /// clock there is nothing to measure slack with, so every spin end is a
5647    /// slot. The sink takes as many as it coalesces into one message; the rest
5648    /// wait for the next slot.
5649    ///
5650    /// The time the sink takes is the reporter's own and is stated by
5651    /// [`Self::violation_report_cost_us`]; the release-jitter rule does not
5652    /// charge it to the spin's cadence (it is not a late release of any
5653    /// application work), which is what used to turn one verdict into a
5654    /// `release-jitter-runtime` verdict of its own on the safety island.
5655    pub(crate) fn flush_violation_reports(&mut self) {
5656        let Some((sink, ctx)) = self.violations.sink else {
5657            return;
5658        };
5659        if self.violations.reports.pending.is_empty() {
5660            return;
5661        }
5662        let now = self.now_us();
5663        if let Some(now) = now {
5664            let since = *self.violations.reports.since_us.get_or_insert(now);
5665            let overdue = now.saturating_sub(since) >= super::monitor::REPORT_DEFER_MAX_US;
5666            let cost = self.violations.reports.last_cost_us as u64;
5667            let slack = match self.next_timer_deadline_us() {
5668                None => true,
5669                Some(remaining) => remaining > 0 && remaining >= cost,
5670            };
5671            if !slack && !overdue {
5672                return;
5673            }
5674        }
5675        // SAFETY: `Executor::set_violation_sink`'s contract -- `ctx` is valid
5676        // for every call until the sink is replaced or the executor dropped.
5677        let taken = unsafe {
5678            sink(
5679                ctx as *mut core::ffi::c_void,
5680                &self.violations.reports.pending[..],
5681            )
5682        };
5683        let q = &mut self.violations.reports;
5684        if taken == 0 {
5685            // The sink counted its failure; drop the oldest so a report that
5686            // can never be sent does not stall the queue. It stays in the ring
5687            // and the record.
5688            q.pending.remove(0);
5689            q.failed = q.failed.saturating_add(1);
5690        } else {
5691            let n = taken.min(q.pending.len());
5692            for _ in 0..n {
5693                q.pending.remove(0);
5694            }
5695        }
5696        q.since_us = None;
5697        if let (Some(t0), Some(t1)) = (now, self.now_us()) {
5698            let q = &mut self.violations.reports;
5699            let cost = t1.saturating_sub(t0);
5700            q.last_cost_us = cost.min(u32::MAX as u64) as u32;
5701            q.max_cost_us = q.max_cost_us.max(q.last_cost_us);
5702            q.debt_us = q.debt_us.saturating_add(cost);
5703        }
5704    }
5705
5706    /// What handing verdicts to the violation sink has cost
5707    /// this executor: `(last_us, max_us, pending, overflowed)`. `overflowed`
5708    /// counts verdicts evicted from the report queue by newer ones before a
5709    /// slot came (they are still in the ring and the SWD record).
5710    pub fn violation_report_cost_us(&self) -> (u32, u32, usize, u32) {
5711        let q = &self.violations.reports;
5712        (q.last_cost_us, q.max_cost_us, q.pending.len(), q.overflowed)
5713    }
5714
5715    /// THE monotonic-µs read. phase-359 W4 — every consumer goes through here.
5716    ///
5717    /// Before this there were FIVE spellings of "what time is it": this one,
5718    /// ~~`last_spin_end: Instant`~~, and two ad-hoc `static EPOCH: OnceLock<Instant>`
5719    /// blocks — plus `PlatformClock`, which nothing called because `Executor` is
5720    /// deliberately non-generic and the trait's methods are associated fns.
5721    ///
5722    /// `None` means no clock is available (no_std with no injected hook).
5723    /// Callers must degrade, not guess: a missing clock is why the sporadic
5724    /// refill and the major-frame phase behaved differently on no_std.
5725    fn now_us(&mut self) -> Option<u64> {
5726        self.clock_us_fn.map(|clock| clock())
5727    }
5728
5729    /// Run the rate/latency/age checks over the baked tables (single
5730    /// branch each when empty).
5731    fn run_contract_monitors(&mut self) {
5732        if !self.monitor_table.is_empty()
5733            && let Some(now_us) = self.now_us()
5734        {
5735            {
5736                for (i, spec) in self
5737                    .monitor_table
5738                    .iter()
5739                    .take(super::monitor::MAX_MONITORS)
5740                    .enumerate()
5741                {
5742                    if let Some(v) =
5743                        super::monitor::check_rate(spec, &mut self.monitor_states[i], now_us)
5744                    {
5745                        self.violations.record(v);
5746                    }
5747                    if let Some(v) =
5748                        super::monitor::check_latency(spec, &mut self.monitor_states[i])
5749                    {
5750                        self.violations.record(v);
5751                    }
5752                }
5753            }
5754        }
5755        if !self.age_table.is_empty() {
5756            // phase-462 W2 -- the age loop needs the clock now: `silence-runtime`
5757            // judges how long an endpoint has taken NOTHING, and `None` (a
5758            // build with no clock) makes that rule abstain rather than guess.
5759            // Read before the loop because the borrow of `age_states` below
5760            // outlives the `&mut self` the reader wants.
5761            let now_us = self.now_us();
5762            for (i, spec) in self
5763                .age_table
5764                .iter()
5765                .take(super::monitor::MAX_AGE_MONITORS)
5766                .enumerate()
5767            {
5768                if let Some(v) = super::monitor::check_age(spec, &mut self.age_states[i], now_us) {
5769                    self.violations.record(v);
5770                }
5771            }
5772        }
5773        // phase-462 W3b -- the hazard observer reads the verdict STATE the rows
5774        // above just updated, so it runs after them and on the same tick.
5775        if !self.hazard_table.is_empty()
5776            && let Some(now_us) = self.now_us()
5777        {
5778            let now_ms = (now_us / 1_000) as u32;
5779            // phase-462 W3c -- a detected hazard whose reacting path states a
5780            // `safe_state` asks the reaction hook to start it, once per
5781            // detection. Not before arming: a start-up verdict is only
5782            // counted (phase-474 I2), and it starts nothing either.
5783            let hook = self.reaction_hook.filter(|_| self.violations.counts.armed);
5784            // play_launch phase 96 W4.2 -- the mode this executor judges by
5785            // says which rung of each hazard's ladder is active.
5786            let mode = self.mode_applied;
5787            let violations = &mut self.violations;
5788            for (row, spec) in self.hazard_table.iter().enumerate() {
5789                super::monitor::check_hazard(
5790                    spec,
5791                    self.monitor_table,
5792                    &self.monitor_states,
5793                    &self.age_states,
5794                    mode,
5795                    now_ms,
5796                    |v| {
5797                        if v.rule == "hazard-detected" && spec.reaction_id != 0 {
5798                            call_hazard_reaction(hook, spec, row, &v, now_us);
5799                        }
5800                        violations.record(v);
5801                    },
5802                );
5803            }
5804        }
5805        self.check_route_deadlines();
5806    }
5807
5808    /// phase-503 — `route-deadline-runtime`: every pending supervised route
5809    /// past `take + route_deadline_ms` is reported (once until a route is
5810    /// within budget again) and its reaction requested through the hook.
5811    /// Runs right after the park, whose bound includes the earliest due time
5812    /// ([`WakeSourceId::RouteDeadline`]), so a route whose output never comes
5813    /// is judged within one park granule of its deadline. A callback that does
5814    /// not return holds this check too: that is `MECHANISM_TIMER`'s case.
5815    fn check_route_deadlines(&mut self) {
5816        let table = self.monitor_table;
5817        if table.is_empty() || !super::monitor::route_deadline_active(table) {
5818            return;
5819        }
5820        let Some(now_us) = self.now_us() else {
5821            return;
5822        };
5823        // Start-up is not RUN (phase-474 I2): before arming a verdict is only
5824        // counted, and no reaction is requested for it either.
5825        let hook = self.reaction_hook.filter(|_| self.violations.counts.armed);
5826        let violations = &mut self.violations;
5827        super::monitor::route_overdue(table, now_us, |row, v, first| {
5828            call_route_reaction(hook, table, row, &v, now_us);
5829            if first {
5830                violations.record(v);
5831            }
5832        });
5833    }
5834
5835    /// Report activations dropped by
5836    /// [`TimerOverrunPolicy::Skip`](super::arena::TimerOverrunPolicy)
5837    /// since the last check.
5838    ///
5839    /// Unlike the rate/age/latency rules this needs no baked spec table:
5840    /// every periodic timer counts its own overruns, and a dropped
5841    /// activation is a contract failure for any declared period. It runs
5842    /// on the same tick so violations land in the same ring the entry
5843    /// glue drains.
5844    /// Declare the minimum stack headroom this executor's thread must keep,
5845    /// in bytes. `0` (the default) disables the `stack-headroom-runtime`
5846    /// rule.
5847    ///
5848    /// Set by the entry that spawned the thread, because it is the only
5849    /// party that knows what stack it handed over: the executor never sees
5850    /// `stack_bytes`, and no portable query returns a task's total stack, so
5851    /// neither an absolute floor nor a percentage can be inferred here.
5852    /// Declare how often this executor's loop intends to come round, in
5853    /// microseconds. `0` (the default) falls back to the `spin_once` timeout.
5854    ///
5855    /// Needed because a driver's pacing and its blocking bound are separate
5856    /// numbers. nros-cpp's sched task loops sleep `spin_period_us` between spins but
5857    /// pass a fixed 10 ms timeout, so the release-jitter rule judged every
5858    /// sched task against 10 ms regardless of what the contract declared -- too lax
5859    /// for a 1 ms sched task and far too strict for a 30 ms one.
5860    ///
5861    /// This also says the CALLER paces the loop (a sleep finer than the
5862    /// park), so the measurement is reported at 1 us. A loop paced by the
5863    /// `spin_once` wait itself declares with
5864    /// [`Self::set_spin_nominal_wait_paced_us`] instead.
5865    pub fn set_spin_nominal_us(&mut self, us: u64) {
5866        self.spin_nominal_declared_us = us;
5867        self.spin_nominal_wait_paced = false;
5868    }
5869
5870    /// Declare the loop's cadence, in microseconds, for a
5871    /// loop paced by the `spin_once` wait itself. `0` withdraws it.
5872    ///
5873    /// [`Self::set_spin_nominal_us`] couples two facts: the period to judge
5874    /// against, and that the caller paces the loop with its own sleep. A loop
5875    /// like `for (;;) spin_once(period_ms)` has the first without the second.
5876    /// Declaring through the coupled setter would report its jitter at 1 us
5877    /// when the park it waits on is tick-granular (a failure seen in practice); not
5878    /// declaring at all makes the timeout the period, which is wrong whenever
5879    /// the timeout is not the period (a cadence that is not whole
5880    /// milliseconds, or one raised to a floor).
5881    ///
5882    /// Here the cadence is the period of the release grid that a
5883    /// `spin_once(timeout)` loop already runs on, and the timeout stays a
5884    /// bound on each wait. The jitter is judged at grid releases and reported
5885    /// at the park granularity.
5886    pub fn set_spin_nominal_wait_paced_us(&mut self, us: u64) {
5887        self.spin_nominal_declared_us = us;
5888        self.spin_nominal_wait_paced = us != 0;
5889    }
5890
5891    pub fn set_min_stack_headroom_bytes(&mut self, bytes: usize) {
5892        self.worker.min_stack_headroom_bytes = bytes;
5893        // phase-436 E4 — a new bound is checked on the next spin, not up to an
5894        // interval later.
5895        self.worker.stack_headroom_last_check_us = None;
5896        // phase-436 E3 — `check_stack_headroom_rule` treats a 0 from the port as
5897        // "not instrumented" and skips, which is right for the rule and wrong
5898        // for the reader: an armed rule that can never judge reports nothing,
5899        // exactly like one that judged and found the stack healthy. Ask the
5900        // port once, here. Entries set the bound at boot on the thread it
5901        // describes, so the answer is about the right stack and the warning
5902        // lands once per sched task, next to the sched task's other boot lines.
5903        // phase-436 E5 -- "does the port answer at all?" needs one byte, not
5904        // the whole unused region the full query would scan.
5905        self.worker.stack_headroom_blind =
5906            bytes != 0 && nros_platform_api::stack_unused_bytes_upto(1) == 0;
5907        if self.worker.stack_headroom_blind {
5908            nros_log::log_warn!(
5909                nros_log::get_logger("nros"),
5910                "stack-headroom-runtime: a {} B minimum is set but this port reports no stack \
5911                 data, so the rule will never check (Zephyr: enable CONFIG_INIT_STACKS)",
5912                bytes
5913            );
5914        }
5915    }
5916
5917    /// Whether `stack-headroom-runtime` is armed on a port that
5918    /// cannot measure, and so will never report a violation.
5919    ///
5920    /// `true` means the rule's silence is not evidence of headroom. Zephyr
5921    /// answers only with `CONFIG_INIT_STACKS && CONFIG_THREAD_STACK_INFO`;
5922    /// POSIX never does.
5923    pub fn stack_headroom_blind(&self) -> bool {
5924        self.worker.stack_headroom_blind
5925    }
5926
5927    /// Report a spin thread that has come closer to the end of its stack
5928    /// than `set_min_stack_headroom_bytes` allows.
5929    ///
5930    /// Runs on the same tick as the other rules and feeds the same ring.
5931    /// Queries the port at most once per `STACK_HEADROOM_CHECK_INTERVAL_US`
5932    /// (phase-436 E4): on a painted Zephyr stack the full query scans every
5933    /// unused byte, so an every-spin query put that scan inside the control
5934    /// loop. Since E5 the query is capped at the declared minimum, so a scan
5935    /// reads at most that many bytes.
5936    /// Nothing at all when no minimum was declared.
5937    fn check_stack_headroom_rule(&mut self) {
5938        if self.worker.min_stack_headroom_bytes == 0 {
5939            return;
5940        }
5941        self.worker.stack_headroom_spins_since_check = self
5942            .worker
5943            .stack_headroom_spins_since_check
5944            .saturating_add(1);
5945        let now_us = self.now_us();
5946        if !super::monitor::stack_headroom_check_due(
5947            now_us,
5948            self.worker.stack_headroom_last_check_us,
5949            self.worker.stack_headroom_spins_since_check,
5950        ) {
5951            return;
5952        }
5953        self.worker.stack_headroom_last_check_us = Some(now_us.unwrap_or(0));
5954        self.worker.stack_headroom_spins_since_check = 0;
5955        self.worker.stack_headroom_checks = self.worker.stack_headroom_checks.saturating_add(1);
5956        // phase-436 E5 -- the CAPPED query. The rule only asks whether
5957        // `min_stack_headroom_bytes` are unused, and a port that scans for
5958        // paint answers that by reading those bytes alone. Below the cap the
5959        // answer is the exact headroom, which is what a breach reports, so
5960        // no second, full scan is needed. E4's throttle still applies.
5961        let unused =
5962            nros_platform_api::stack_unused_bytes_upto(self.worker.min_stack_headroom_bytes);
5963        // 0 means the port does not instrument stacks, not that the stack is
5964        // full. Reporting a violation there would be a fault invented from an
5965        // absence of data.
5966        if unused == 0 {
5967            return;
5968        }
5969        if let Some(v) = super::monitor::check_stack_headroom(
5970            unused,
5971            self.worker.min_stack_headroom_bytes,
5972            &mut self.worker.stack_headroom_reported,
5973        ) {
5974            self.violations.record(v);
5975        }
5976    }
5977
5978    /// AUTOSAR-style ALIVE supervision: report a SchedContext that produced
5979    /// no dispatch at all over a full window while declaring a period.
5980    ///
5981    /// Every other rule here fires when something happens and is wrong. This
5982    /// one fires when nothing happens, which is the failure a watchdog
5983    /// exists for and the one `rate-hierarchy-runtime` cannot see: that rule
5984    /// counts publishes on an endpoint, so a callback that stops firing while
5985    /// its topic is published from elsewhere leaves it satisfied.
5986    fn check_alive_supervision(&mut self) {
5987        let Some(now_us) = self.now_us() else {
5988            // No clock, no windows. Silence here is honest: the rule cannot
5989            // tell a stalled context from a fast one without time.
5990            return;
5991        };
5992        let n = self.alive_slots.len().min(self.sched_contexts.len());
5993        for i in 0..n {
5994            let period_us = match self.sched_contexts[i].as_ref() {
5995                Some(sc) => sc.period_us.get().map(|nz| nz.get() as u64).unwrap_or(0),
5996                None => continue,
5997            };
5998            let slot = &mut self.alive_slots[i];
5999            if let Some(v) =
6000                super::monitor::check_alive(period_us, slot.dispatches, &mut slot.state, now_us)
6001            {
6002                self.violations.record(v);
6003            }
6004        }
6005    }
6006
6007    /// Issue #515 — report a spin wake a whole period late.
6008    ///
6009    /// Runs on the same tick as `check_timer_overruns` and feeds the same
6010    /// ring, so the entry glue drains it with the other rules and no caller
6011    /// needs to know this one exists. Like that rule it needs no spec table:
6012    /// the bound is the spin period the caller already passes in.
6013    fn check_release_jitter_rule(&mut self) {
6014        let (max_us, _late, _total) = self.release_jitter();
6015        let period_us = self.spin_nominal_us;
6016        if let Some(v) =
6017            super::monitor::check_release_jitter(max_us, &mut self.jitter_reported_us, period_us)
6018        {
6019            self.violations.record(v);
6020        }
6021    }
6022
6023    fn check_timer_overruns(&mut self) {
6024        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
6025        for i in 0..self.entries.len() {
6026            let Some(meta) = self.entries[i].as_ref() else {
6027                continue;
6028            };
6029            // phase-509 P9b item 2 -- a timer whose callback runs in another
6030            // worker's window is that worker's to touch; its overrun is
6031            // reported by the next pass that finds it idle.
6032            if !matches!(meta.kind, EntryKind::Timer) || Self::slot_held(self.slot_tags, i) {
6033                continue;
6034            }
6035            // SAFETY: a Timer entry's arena slot holds a `TimerEntry<F>`,
6036            // which shares its leading layout with `TimerHeader`. The
6037            // baseline lives in the header too, so this needs no state
6038            // parallel to `entries` (whose capacity is a runtime slice
6039            // length, not a const).
6040            let header = unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
6041            if let Some(v) = super::monitor::check_timer_overrun(
6042                header.overruns,
6043                &mut header.overruns_reported,
6044                0,
6045            ) {
6046                self.violations.record(v);
6047            }
6048        }
6049    }
6050
6051    /// Replace the DEFAULT scheduling context
6052    /// (slot 0, the SC every unbound callback dispatches through).
6053    ///
6054    /// The run_sched_tasks model runs one Executor per sched task, so a sched-task-wide
6055    /// scheduling policy (`[tasks.<t>] class/budget_us/period_us` and the
6056    /// TT window) is exactly "this executor's default SC". Boards call
6057    /// this once, before entity creation; explicit per-handle/per-group
6058    /// bindings still take precedence (they never resolve to slot 0).
6059    ///
6060    /// Sporadic-class SCs get the same sibling `SporadicState` the
6061    /// `create_sched_context` path builds, so budget refill/exhaustion
6062    /// applies to the default queue too.
6063    pub fn set_default_sched_context(&mut self, sc: super::sched_context::SchedContext) {
6064        self.sched_contexts[0] = Some(sc);
6065        if matches!(sc.class, super::sched_context::SchedClass::Sporadic) {
6066            let budget = sc.budget_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
6067            let period = sc.period_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
6068            self.sporadic_states[0] =
6069                Some(super::sched_context::SporadicState::new(budget, period));
6070        } else {
6071            self.sporadic_states[0] = None;
6072        }
6073    }
6074
6075    /// Bind a registered callback to a scheduling context. The next
6076    /// `spin_once` cycle dispatches the callback through that SC's
6077    /// queue (FIFO bitmap or EDF heap).
6078    pub fn bind_handle_to_sched_context(
6079        &mut self,
6080        handle: HandleId,
6081        sc_id: super::sched_context::SchedContextId,
6082    ) -> Result<(), NodeError> {
6083        let i = self.live_slot(handle);
6084        if i >= self.entries.len() {
6085            return Err(NodeError::InvalidSchedContextBinding);
6086        }
6087        if self.entries[i].is_none() {
6088            return Err(NodeError::InvalidSchedContextBinding);
6089        }
6090        let sc_idx = sc_id.0 as usize;
6091        if sc_idx >= self.sched_contexts.len() || self.sched_contexts[sc_idx].is_none() {
6092            return Err(NodeError::InvalidSchedContextBinding);
6093        }
6094        self.sched_context_bindings[i] = sc_id;
6095        Ok(())
6096    }
6097
6098    /// Enable time-triggered dispatch by setting the
6099    /// executor's major-frame length. Once set, every `spin_once`
6100    /// cycle gates dispatch through each entry's bound SC's
6101    /// `tt_window_offset_us` / `tt_window_duration_us` fields:
6102    /// dispatch only fires when the current monotonic time falls
6103    /// inside the window `[off, off + duration) mod major_frame`.
6104    ///
6105    /// `major_frame_us = 0` disables the TT gate (default state).
6106    /// Setting a non-zero major frame after callbacks are already
6107    /// registered is allowed — TT gates take effect on the next
6108    /// `spin_once` cycle.
6109    pub fn register_time_triggered_dispatcher(&mut self, major_frame_us: u32) {
6110        self.major_frame_us = major_frame_us;
6111    }
6112
6113    /// Apply a declarative cyclic schedule.
6114    ///
6115    /// One-shot helper that wraps the underlying primitives:
6116    /// validates the schedule (major_frame > 0, no overlapping
6117    /// windows, every window fits inside the major frame), sets the
6118    /// executor's major-frame length, then materialises one
6119    /// `SchedContext` per window with `class = TimeTriggered` +
6120    /// the window's offset / duration. Returns the per-window
6121    /// [`SchedContextId`](crate::executor::sched_context::SchedContextId) array so callers can immediately
6122    /// `bind_handle_to_sched_context(handle, sc_id)` for their
6123    /// subscription / timer handles.
6124    ///
6125    /// `N` is the schedule's *declared* maximum window count;
6126    /// `schedule.window_count` gates how many SCs are actually
6127    /// created. Unused trailing slots return
6128    /// `SchedContextId::default()` (sentinel — callers must respect
6129    /// `window_count`).
6130    pub fn apply_time_triggered_schedule<const N: usize>(
6131        &mut self,
6132        schedule: &super::sched_context::TimeTriggeredSchedule<N>,
6133    ) -> Result<
6134        [super::sched_context::SchedContextId; N],
6135        super::sched_context::TimeTriggeredScheduleError,
6136    > {
6137        schedule.validate()?;
6138        self.major_frame_us = schedule.major_frame_us;
6139        // SC slot 0 is the auto-created default; reusing it as a
6140        // sentinel for unused trailing slots is safe because the
6141        // caller respects `schedule.window_count`.
6142        let mut ids: [super::sched_context::SchedContextId; N] =
6143            [super::sched_context::SchedContextId(0); N];
6144        for (i, window) in schedule.windows[..schedule.window_count].iter().enumerate() {
6145            // TT is not a scheduling class (phase-482 W6 deleted the
6146            // `SchedClass::TimeTriggered` variant): it is a per-SC *window gate* on top of
6147            // the existing class-based dispatch (Fifo here keeps
6148            // the EDF / Sporadic budgets out of the picture for
6149            // pure cyclic schedules). The window-gate fields set
6150            // below are what `spin_once`'s 110.G runtime gate
6151            // actually reads.
6152            let sc = super::sched_context::SchedContext {
6153                tt_window_offset_us: super::sched_context::OptUs::from_us(window.offset_us),
6154                tt_window_duration_us: super::sched_context::OptUs::from_us(window.duration_us),
6155                ..super::sched_context::SchedContext::new_fifo()
6156            };
6157            ids[i] = self.create_sched_context(sc).map_err(|_| {
6158                super::sched_context::TimeTriggeredScheduleError::WindowCountOverflow
6159            })?;
6160        }
6161        Ok(ids)
6162    }
6163
6164    /// Register an ISR-driven refill timer for an
6165    /// already-created Sporadic SC. The caller invokes their
6166    /// platform's `PlatformTimer::create_periodic` with the returned
6167    /// `Arc<AtomicSporadicState>` as `user_data` and the
6168    /// `atomic_sporadic_refill_thunk` as the callback, then hands
6169    /// the resulting platform handle to this method via
6170    /// `OpaqueTimerHandle::new(handle, destroy_fn)`.
6171    ///
6172    /// The Executor stores both the Arc and the handle so Drop can
6173    /// clean them up. Calling this on a non-Sporadic SC returns
6174    /// `Err(InvalidSchedContextBinding)`.
6175    #[cfg(feature = "alloc")]
6176    pub fn register_sporadic_timer(
6177        &mut self,
6178        sc_id: super::sched_context::SchedContextId,
6179        timer: OpaqueTimerHandle,
6180    ) -> Result<portable_atomic_util::Arc<super::sched_context::AtomicSporadicState>, NodeError>
6181    {
6182        let i = sc_id.0 as usize;
6183        if i >= self.sched_contexts.len() {
6184            return Err(NodeError::InvalidSchedContextBinding);
6185        }
6186        let sc = self.sched_contexts[i]
6187            .as_ref()
6188            .ok_or(NodeError::InvalidSchedContextBinding)?;
6189        if !matches!(sc.class, super::sched_context::SchedClass::Sporadic) {
6190            return Err(NodeError::InvalidSchedContextBinding);
6191        }
6192        let budget = sc.budget_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
6193        let period = sc.period_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX);
6194        let state = portable_atomic_util::Arc::new(super::sched_context::AtomicSporadicState::new(
6195            budget, period,
6196        ));
6197        self.sporadic_atomic_states[i] = Some((portable_atomic_util::Arc::clone(&state), timer));
6198        Ok(state)
6199    }
6200
6201    /// Inspect a registered scheduling context.
6202    pub fn sched_context(
6203        &self,
6204        sc_id: super::sched_context::SchedContextId,
6205    ) -> Option<&super::sched_context::SchedContext> {
6206        self.sched_contexts.get(sc_id.0 as usize)?.as_ref()
6207    }
6208
6209    /// Start a rclcpp-style Node builder for this
6210    /// Executor. The returned [`NodeBuilder`](super::node_record::NodeBuilder)
6211    /// is chainable:
6212    ///
6213    /// ```ignore
6214    /// let id = exec.node_builder("ingress")
6215    ///     .rmw("zenoh")
6216    ///     .locator("tcp/127.0.0.1:7447")
6217    ///     .sched(my_sc_id)
6218    ///     .build()?;
6219    /// ```
6220    ///
6221    /// For now the Node table is storage-only — all
6222    /// registered Nodes share the Executor's primary session. Per-
6223    /// Node session binding (the bridge feature) lands in Phase
6224    /// 104.C.3 when the session cache is wired.
6225    pub fn node_builder<'a, 'cfg>(
6226        &'a mut self,
6227        name: &'cfg str,
6228    ) -> super::node_record::NodeBuilder<'a, 'cfg, 's> {
6229        super::node_record::NodeBuilder {
6230            executor: self,
6231            name,
6232            namespace: None,
6233            rmw_name: None,
6234            locator: None,
6235            domain_id: None,
6236            sched: None,
6237            session_idx: None,
6238        }
6239    }
6240
6241    /// Return the Node table (read accessor).
6242    pub fn nodes(&self) -> &[super::node_record::NodeRecord] {
6243        &self.nodes
6244    }
6245
6246    /// Borrow a Node's metadata by id, returning `None` if the id
6247    /// is out of range.
6248    pub fn node(&self, id: super::node_record::NodeId) -> Option<&super::node_record::NodeRecord> {
6249        self.nodes.get(id.index())
6250    }
6251
6252    /// An executor-borrowing node handle for the entity builders
6253    /// (`exec.node_mut(id).subscription(t)...` / `.create_subscription(...)`).
6254    /// A short-lived `&mut Executor` borrow — use one at a time; entity handles
6255    /// are owned and outlive it (see `Node`).
6256    /// The component registration frame, for the `nros`
6257    /// facade's declarative constructors. Not a user API.
6258    #[doc(hidden)]
6259    pub fn __component_frame(&self) -> Option<core::ptr::NonNull<()>> {
6260        self.component_frame
6261    }
6262
6263    /// Install or clear the component registration frame.
6264    /// The caller guarantees the pointee outlives the installation.
6265    #[doc(hidden)]
6266    pub fn __set_component_frame(&mut self, frame: Option<core::ptr::NonNull<()>>) {
6267        self.component_frame = frame;
6268    }
6269
6270    pub fn node_mut(&mut self, id: super::node_record::NodeId) -> super::node::Node<'_, 's> {
6271        super::node::Node::new(self, id)
6272    }
6273
6274    /// Issue #52 — install the baked QoS-override table on one node. Every
6275    /// entity created on it AFTERWARDS folds the matching `(topic, role)`
6276    /// entries into its QoS, before the backend-compat check — so an override
6277    /// the active RMW cannot honour still errors loudly rather than silently
6278    /// downgrading.
6279    ///
6280    /// Called by the generated entry (`nros::main!` → the register seam) right
6281    /// after the node is created and before the component declares entities.
6282    /// Unknown `node_id` is a no-op.
6283    pub fn set_node_qos_overrides(
6284        &mut self,
6285        node_id: super::node_record::NodeId,
6286        overrides: &'static [super::node_record::QoSOverrideCode],
6287    ) {
6288        if let Some(r) = self.nodes.get_mut(node_id.index()) {
6289            r.qos_overrides = overrides;
6290        }
6291    }
6292
6293    /// Phase 104.C.3 — resolve a session-slot index to a mutable
6294    /// session reference. Slot 0 = the Executor's primary session;
6295    /// slots 1..=N = the `extra_sessions` vec opened by
6296    /// `node_builder.rmw(name)` calls that named a backend
6297    /// different from the primary.
6298    pub(crate) fn session_at_mut(&mut self, idx: u8) -> Option<&mut session::ConcreteSession> {
6299        if idx == 0 {
6300            Some(&mut *self.session)
6301        } else {
6302            self.extra_sessions.get_mut((idx - 1) as usize)
6303        }
6304    }
6305
6306    /// [`Self::session_at_mut`] plus a shared borrow of the remap table, for
6307    /// building a [`NodeHandle`] — which needs both at once, and gets them
6308    /// here as two disjoint field borrows rather than through two `&mut self`
6309    /// calls the borrow checker could not split.
6310    pub(crate) fn session_and_remaps_at_mut(
6311        &mut self,
6312        idx: u8,
6313    ) -> Option<(&mut session::ConcreteSession, RemapView<'_>)> {
6314        let remaps = RemapView {
6315            launch: self
6316                .launch_remaps
6317                .unwrap_or_else(super::launch_remap::launch_remaps),
6318            runtime: &self.remap_table[..self.remap_len],
6319        };
6320        let session = if idx == 0 {
6321            Some(&mut *self.session)
6322        } else {
6323            self.extra_sessions.get_mut((idx - 1) as usize)
6324        };
6325        session.map(|s| (s, remaps))
6326    }
6327
6328    /// Phase 104.C.9.b — resolve the per-Node session for direct
6329    /// entity creation paths (C++ FFI publisher / subscription /
6330    /// service that bypass the `register_*_on` arena dispatch).
6331    /// Returns `None` when `node_id` is out of range or the Node's
6332    /// `session_idx` lands outside the executor's session table.
6333    pub(crate) fn node_session_mut(
6334        &mut self,
6335        node_id: super::node_record::NodeId,
6336    ) -> Option<&mut session::ConcreteSession> {
6337        let session_idx = self.nodes.get(node_id.index())?.session_idx;
6338        self.session_at_mut(session_idx)
6339    }
6340
6341    /// Create a typed publisher bound to a node's session.
6342    /// Backs `node.publisher(t).typed::<M>().build()` on the
6343    /// executor-borrowing [`Node`](super::node::Node); the returned
6344    /// handle is owned and outlives the `Node`.
6345    pub fn create_publisher_on<M: crate::rmw_type_registry::MessageForRmw>(
6346        &mut self,
6347        node_id: super::node_record::NodeId,
6348        topic_name: &str,
6349        qos: QoSProfile,
6350    ) -> Result<crate::executor::handles::EmbeddedPublisher<M>, NodeError> {
6351        // RFC-0088 / phase-421 W1 — the message's declared format must be the
6352        // one the linked backend speaks. Universal: the const lives on
6353        // `RosMessage`, which `MessageForRmw` requires under every backend.
6354        crate::format_check::assert_message_format::<M>();
6355        // Phase 212.K.7.6.b — register `M`'s cyclonedds descriptor before
6356        // creating the underlying publisher handle. No-op for other RMWs.
6357        crate::rmw_type_registry::register_type::<M>()?;
6358        let handle = self.create_raw_publisher_handle_on(
6359            node_id,
6360            topic_name,
6361            <M as RosMessage>::TYPE_NAME,
6362            <M as RosMessage>::TYPE_HASH,
6363            qos,
6364            super::node::ProfileOrigin::Application,
6365        )?;
6366        // RFC-0052 W3b.4 — attach the contracted endpoint's counter cell.
6367        let monitor = self
6368            .monitor_table
6369            .iter()
6370            .find(|m| m.topic == topic_name)
6371            .map(|m| m.cell);
6372        Ok(crate::executor::handles::EmbeddedPublisher {
6373            handle,
6374            gate: self.publisher_gate(node_id),
6375            event_regs: crate::executor::handles::empty_event_regs(),
6376            monitor,
6377            epoch: self.epoch_us_fn,
6378            _phantom: PhantomData,
6379        })
6380    }
6381
6382    /// Create a generic (type-erased) publisher bound to a
6383    /// node's session. Backs `node.publisher(t).generic(ty, hash).build()`;
6384    /// the bridge re-publishes through this handle on the dest session.
6385    pub fn create_publisher_raw_on(
6386        &mut self,
6387        node_id: super::node_record::NodeId,
6388        topic_name: &str,
6389        type_name: &str,
6390        type_hash: &str,
6391        qos: QoSProfile,
6392    ) -> Result<crate::executor::handles::EmbeddedRawPublisher, NodeError> {
6393        let handle = self.create_raw_publisher_handle_on(
6394            node_id,
6395            topic_name,
6396            type_name,
6397            type_hash,
6398            qos,
6399            super::node::ProfileOrigin::Application,
6400        )?;
6401        Ok(crate::executor::handles::EmbeddedRawPublisher {
6402            handle,
6403            gate: self.publisher_gate(node_id),
6404            arena: crate::executor::handles::TxArena::new(),
6405            event_regs: crate::executor::handles::empty_event_regs(),
6406            // Issue 1676 — attach the contracted endpoint's counter cell by
6407            // exact topic match against the installed table, the rule
6408            // `NodeHandle::create_publisher` applies. This is the publisher
6409            // the Rust component road creates, so without it no contracted
6410            // Rust publisher was ever counted.
6411            monitor: self.publisher_monitor_cell(topic_name),
6412        })
6413    }
6414
6415    // RFC-0128 D3 / phase-554 W6.
6416    /// The gate a publisher of `node` holds: it
6417    /// follows the node's lifecycle state once the node is managed. A node not
6418    /// in the table gets none, and its publisher always sends.
6419    ///
6420    /// The gate reads the executor's node table, so a publisher that holds it
6421    /// must not publish after this executor is closed -- the same life as the
6422    /// RMW handle it sits beside. The C and C++ publishers take theirs here.
6423    pub fn publisher_gate(
6424        &self,
6425        node: super::node_record::NodeId,
6426    ) -> crate::lifecycle::PublisherGate {
6427        match self.nodes.get(node.index()) {
6428            Some(r) => {
6429                crate::lifecycle::PublisherGate::of(core::ptr::NonNull::from(&r.publish_gate))
6430            }
6431            None => crate::lifecycle::PublisherGate::none(),
6432        }
6433    }
6434
6435    /// Shared prelude for the publisher-on-node paths: resolve the node's
6436    /// identity + session slot, build the [`TopicInfo`], validate QoS, and
6437    /// create the backend publisher handle. Mirrors
6438    /// `register_subscription_buffered_raw_on`'s session resolution so a
6439    /// bridge's source sub + dest pub agree on topic construction.
6440    fn create_raw_publisher_handle_on(
6441        &mut self,
6442        node_id: super::node_record::NodeId,
6443        topic_name: &str,
6444        type_name: &str,
6445        type_hash: &str,
6446        qos: QoSProfile,
6447        origin: super::node::ProfileOrigin,
6448    ) -> Result<session::RmwPublisher, NodeError> {
6449        let (node_name, ns, session_idx, overrides) = {
6450            let r = self
6451                .nodes
6452                .get(node_id.index())
6453                .ok_or(NodeError::InvalidSchedContextBinding)?;
6454            (
6455                r.name.clone(),
6456                r.namespace.clone(),
6457                r.session_idx,
6458                r.qos_overrides,
6459            )
6460        };
6461        // Issue 2920 -- the runtime's own base profile is a preference, so it
6462        // is fitted to the backend FIRST; the overrides and the declared
6463        // contract folded on after it are what a person wrote, and those are
6464        // still refused below when the backend cannot honour them.
6465        let qos = match origin {
6466            super::node::ProfileOrigin::Application => qos,
6467            super::node::ProfileOrigin::Runtime => {
6468                let supported = Session::supported_qos_policies(
6469                    self.session_at_mut(session_idx)
6470                        .ok_or(NodeError::BackendMismatch)?,
6471                );
6472                super::node::fit_runtime_qos(qos, supported, "publisher", topic_name)
6473            }
6474        };
6475        // Issue #52 — fold the node's baked overrides for this topic BEFORE
6476        // `validate_against`, so an override the backend cannot honour errors
6477        // loudly instead of being silently dropped.
6478        let qos = super::node_record::apply_qos_override_codes(
6479            qos,
6480            topic_name,
6481            nros_rmw::QoSOverrideRole::Publisher,
6482            overrides,
6483        );
6484        let mut topic = TopicInfo::new(topic_name, type_name, type_hash)
6485            .with_domain(self.domain_id)
6486            .with_namespace(&ns);
6487        if !node_name.is_empty() {
6488            topic = topic.with_node_name(&node_name);
6489        }
6490        // issue 1608 -- the publisher half of the declared-QoS check, before
6491        // validation so a policy the contract raises this publisher to is one
6492        // the backend is asked about. See `declared_qos::honour_publisher`.
6493        let qos = crate::declared_qos::honour_publisher(topic.type_name, topic.name, qos)?;
6494        let session = self
6495            .session_at_mut(session_idx)
6496            .ok_or(NodeError::BackendMismatch)?;
6497        super::node::validate_qos_or_report(
6498            &qos,
6499            Session::supported_qos_policies(session),
6500            "publisher",
6501            topic_name,
6502        )?;
6503        session
6504            .create_publisher(&topic, qos)
6505            .map_err(|_| NodeError::Transport(TransportError::PublisherCreationFailed))
6506    }
6507
6508    /// Phase 124.B.1 — install the executor's wake callback onto the
6509    /// primary session. Best-effort: backends that don't override
6510    /// `Session::set_wake_callback` (poll-only XRCE, bare-metal)
6511    /// ignore the call and continue to be drained on the executor's
6512    /// deadline-bound cv-wait boundary.
6513    ///
6514    /// `pub` for issue 1385, and for the same reason
6515    /// [`set_primary_identity`](Self::set_primary_identity) is: the three
6516    /// `Executor::open*` paths call this automatically, and a binding that
6517    /// builds its executor over a session it BORROWS
6518    /// ([`from_session_ptr_in`](Self::from_session_ptr_in)) reaches none of
6519    /// them, so it has to call it itself. `rclc_executor_init` is that
6520    /// binding, and until 1385 it did not — leaving `has_async_wake` false
6521    /// for the life of every C executor on every backend.
6522    ///
6523    /// Pairs with `clear_wake_signal`, which the
6524    /// executor runs from `close()` and from `drop`. A caller that installs
6525    /// owes nothing further: the teardown is the executor's.
6526    ///
6527    /// phase-436 — the backend's slot holds a `WakeFanout`
6528    /// and this executor JOINS it, so every executor over one session is woken
6529    /// by an arrival: the boot executor and each spawned sched task
6530    /// (`open_with_session*` now installs too), or several C executors over
6531    /// one support context. Idempotent. If the fan-out pool is exhausted the
6532    /// executor installs its own context directly, as before; if the entry's
6533    /// member table is full it joins nothing and reads as having no async
6534    /// wake, so it never parks on a wake nobody will signal.
6535    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6536    pub(crate) fn install_wake_signal_on_primary(&mut self) {
6537        use nros_rmw::Session as _;
6538        if self.wake_membership.is_some() {
6539            return;
6540        }
6541        let ctx = self.wake_ctx_ptr();
6542        // The fan-out key is the session's ADDRESS, needed whether or not the
6543        // session may be shared; nothing is read through it.
6544        let key = &*self.session as *const session::ConcreteSession as *mut core::ffi::c_void;
6545        let supports = self.session.supports_wake_callback();
6546        let fanout = match super::wake_fanout::find(key) {
6547            Some(f) => Some(f),
6548            None => super::wake_fanout::claim(key).inspect(|f| {
6549                f.set_live(supports);
6550                // SAFETY: the context is a `static` pool entry, valid for the
6551                // program's life; `clear_wake_signal` takes the callback off
6552                // before returning the entry to the pool.
6553                unsafe {
6554                    self.session
6555                        .set_wake_callback(Some(nros_rmw_fanout_wake_cb), f.as_ctx());
6556                }
6557            }),
6558        };
6559        match fanout {
6560            Some(f) => {
6561                if let Some(m) = f.join(ctx) {
6562                    self.wake_membership = Some(m);
6563                    // Issue 1385 — this executor now owes a teardown: leaving
6564                    // the fan-out (and, for the session's owner or its last
6565                    // member, taking the callback off the backend).
6566                    self.wake_cb_installed = true;
6567                }
6568            }
6569            None => {
6570                // SAFETY: `ctx` points at executor-owned wake state that
6571                // outlives the installation and is cleared by
6572                // `clear_wake_signal` on `close()`/drop.
6573                unsafe {
6574                    self.session
6575                        .set_wake_callback(Some(nros_rmw_runtime_wake_cb), ctx);
6576                }
6577                self.wake_cb_installed = true;
6578                if supports {
6579                    self.has_async_wake = true;
6580                }
6581            }
6582        }
6583    }
6584
6585    /// phase-436 — does an arrival on any of this executor's sessions signal
6586    /// its wake object? Through the primary's fan-out (live until the
6587    /// session's owner takes the callback down), or a direct install on the
6588    /// primary or an extra session.
6589    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6590    pub(crate) fn async_wake_live(&self) -> bool {
6591        self.has_async_wake || self.wake_membership.is_some_and(|m| m.is_live())
6592    }
6593
6594    /// Phase 124.B.1 — install the wake callback onto an extra
6595    /// session opened by `node_builder.rmw(...)`. Called from
6596    /// `NodeBuilder::build()` right after `extra_sessions.push(...)`.
6597    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6598    pub(crate) fn install_wake_signal_on_extra(&mut self, idx: usize) {
6599        use nros_rmw::Session as _;
6600        let ctx = self.wake_ctx_ptr();
6601        if let Some(s) = self.extra_sessions.get_mut(idx) {
6602            // SAFETY: same executor-owned wake state as the primary session;
6603            // the extra session is owned by this executor.
6604            unsafe {
6605                s.set_wake_callback(Some(nros_rmw_runtime_wake_cb), ctx);
6606            }
6607            // Issue 1385 — as on the primary.
6608            self.wake_cb_installed = true;
6609            if s.supports_wake_callback() {
6610                self.has_async_wake = true;
6611            }
6612        }
6613    }
6614
6615    /// Issue 1385 — the teardown half of `install_wake_signal_on_*`, and the
6616    /// obligation `nros_rmw_runtime_wake_cb`'s own SAFETY comment has asserted
6617    /// since phase 124: *"Executor::drop must clear the callback via
6618    /// `set_wake_callback(None, _)` on all sessions before dropping
6619    /// wake_ctx"*. Nothing did. The string `set_wake_callback(None` occurred
6620    /// exactly once in the tree — in that comment.
6621    ///
6622    /// The context the backend holds is `Arc::as_ptr(&self.wake_ctx)`, freed
6623    /// with this executor. Leaving it installed is a dangling callback the
6624    /// backend may invoke from a worker thread or an ISR. On the Rust `open*`
6625    /// paths the session is `SessionStore::Owned` and dies in the same drop,
6626    /// so the window is narrow; on the C path it is arbitrary —
6627    /// `rclc_executor_fini` drops the executor and zero-fills `_opaque` while
6628    /// the session lives on in `rclc_support_t` until `rclc_support_fini`.
6629    ///
6630    /// Clears the primary and every extra session, then latches off, so
6631    /// `close()` followed by drop clears once.
6632    ///
6633    /// Only fires when THIS executor installed (see
6634    /// `install_wake_signal_on_primary`). Executors sharing one session were
6635    /// last-writer-wins on the backend's single slot until phase-436: the first
6636    /// to tear down cleared the other's wake. The slot now holds a wake
6637    /// fan-out, so a member's teardown is leaving it, and the callback comes
6638    /// off the backend only with the session's owner or its last member.
6639    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6640    pub(crate) fn clear_wake_signal(&mut self) {
6641        use nros_rmw::Session as _;
6642        if !self.wake_cb_installed {
6643            return;
6644        }
6645        self.wake_cb_installed = false;
6646        // phase-436 — a fan-out member leaves first; the callback comes off
6647        // the backend only when the session's OWNER leaves (the session dies
6648        // with it) or the last member does. A membership from an entry the
6649        // owner already released is a no-op, and must not touch the entry's
6650        // next tenant.
6651        let take_off_primary = match self.wake_membership.take() {
6652            Some(m) => {
6653                let fanout = m.fanout();
6654                let current = m.is_current();
6655                m.leave(nros_platform_api::yield_now);
6656                let owned = self.session.is_owned();
6657                if current && (owned || fanout.member_count() == 0) {
6658                    // SAFETY: as below; the entry is released only after the
6659                    // backend can no longer start a callback on it.
6660                    unsafe { self.session.set_wake_callback(None, core::ptr::null_mut()) };
6661                    fanout.release(nros_platform_api::yield_now);
6662                }
6663                false
6664            }
6665            None => true,
6666        };
6667        // SAFETY: clearing takes no context, and both sessions are still live
6668        // here — this runs BEFORE `Session::close` in `close()` and before the
6669        // session field is dropped in `Drop`.
6670        unsafe {
6671            if take_off_primary {
6672                self.session.set_wake_callback(None, core::ptr::null_mut());
6673            }
6674            for s in self.extra_sessions.iter_mut() {
6675                s.set_wake_callback(None, core::ptr::null_mut());
6676            }
6677        }
6678        self.has_async_wake = false;
6679    }
6680
6681    /// phase-467 Row 8 — hand the PRIMARY session a graph-change target it may
6682    /// trigger from a worker thread, and take ownership of that target.
6683    ///
6684    /// The install half of the pair; [`clear_graph_change_signal`] is the
6685    /// other and the executor owes it. `guard` is CLONED, so the caller keeps
6686    /// its own handle to the same arena flag — that is the whole point: the
6687    /// pointer the backend receives is the executor's box, never the caller's
6688    /// storage. Issue 1385 is the same hazard on the wake slot, found after
6689    /// the fact; this is the shape that cannot reach it.
6690    ///
6691    /// PRIMARY only, deliberately. A graph is a property of a session, and the
6692    /// extra sessions of `node_builder.rmw(...)` each have their own — feeding
6693    /// several into one guard would make "the graph changed" unattributable
6694    /// while costing the caller the ability to ask which. A caller wanting a
6695    /// second backend's graph asks that session for its own.
6696    ///
6697    /// Returns `Err(Unsupported)` from a backend with no graph. A previously
6698    /// installed target is retired first, so an executor never has two.
6699    ///
6700    /// [`clear_graph_change_signal`]: Self::clear_graph_change_signal
6701    ///
6702    /// `pub(crate)`, not `pub`: the public verb is
6703    /// [`register_graph_change_guard_on`], which does the probe, the
6704    /// registration and this in the one order that cannot hand back a guard
6705    /// nothing fires. Exposing the install alone would let a caller reach the
6706    /// second step without the first.
6707    ///
6708    /// [`register_graph_change_guard_on`]: Self::register_graph_change_guard_on
6709    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6710    pub(crate) fn install_graph_change_guard(
6711        &mut self,
6712        guard: &GuardCondition<'s>,
6713    ) -> Result<(), NodeError> {
6714        use nros_rmw::Session as _;
6715        self.clear_graph_change_signal();
6716        let boxed = alloc::boxed::Box::new(guard.clone());
6717        let ptr = (&*boxed) as *const GuardCondition as *const core::ffi::c_void;
6718        // SAFETY: `ptr` names heap storage this executor owns and which
6719        // `clear_graph_change_signal` retires from the backend before it is
6720        // freed. `GuardCondition` is `Send + Sync` and its `trigger()` is a
6721        // relaxed store plus the runtime wake hook, which is what a foreign
6722        // thread is allowed to do here.
6723        let rc = unsafe {
6724            self.session
6725                .set_graph_change_callback(Some(nros_rmw_runtime_graph_change_cb), ptr)
6726        };
6727        match rc {
6728            Ok(()) => {
6729                self.graph_change_target = Some(boxed);
6730                Ok(())
6731            }
6732            // `boxed` drops here, and nothing holds its pointer: the backend
6733            // either refused or failed, so there is no installed callback to
6734            // retire first.
6735            Err(e) => Err(NodeError::Transport(e)),
6736        }
6737    }
6738
6739    /// phase-467 Row 8 — can the primary session deliver a graph-change edge?
6740    ///
6741    /// Asked by CLEARING, which is the one probe that costs nothing and cannot
6742    /// lie: a backend with no graph answers `Unsupported` to a `None` install
6743    /// just as it does to a real one, and an idempotent clear on a backend
6744    /// that HAS a graph is a no-op. Nullity of the vtable slot cannot answer
6745    /// it — `rust_adapter.rs` fills the slot for every Rust backend whether or
6746    /// not that backend overrides the trait method, which
6747    /// `check-rmw-slot-producers`'s own report says in as many words.
6748    ///
6749    /// The caller is `register_graph_change_guard_on`, which asks BEFORE it
6750    /// consumes an executor handle slot, so an unsupported backend costs
6751    /// nothing and the caller is never handed a guard nothing fires.
6752    /// `pub(crate)` for the same reason the install is: asking costs a CLEAR,
6753    /// so a caller that asks and then does nothing has silently retired a live
6754    /// target. The public verb asks once, on the caller's behalf.
6755    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6756    pub(crate) fn supports_graph_change_callback(&mut self) -> bool {
6757        use nros_rmw::Session as _;
6758        // Retire whatever is installed first — the probe IS a clear, so doing
6759        // it without this would silently drop a live target.
6760        self.clear_graph_change_signal();
6761        // SAFETY: a `None` install takes no context and installs nothing.
6762        unsafe {
6763            self.session
6764                .set_graph_change_callback(None, core::ptr::null())
6765                .is_ok()
6766        }
6767    }
6768
6769    /// phase-467 Row 8 — the teardown half of
6770    /// [`install_graph_change_guard`](Self::install_graph_change_guard), and
6771    /// the reason that install cannot recreate issue 1385.
6772    ///
6773    /// Order is the whole content: tell the backend to stop FIRST, then drop
6774    /// the box it was pointing at. Reversed, the window between the free and
6775    /// the clear is exactly 1385's dangling callback — and on the C path that
6776    /// window is arbitrary, because the session outlives the executor.
6777    ///
6778    /// Latched on `graph_change_target.is_some()`, not on a separate flag: the
6779    /// box IS the record of having installed, so `close()` followed by drop
6780    /// clears once and an executor that never installed clears nothing. That
6781    /// is the same predicate `clear_wake_signal` needs a bool for only because
6782    /// its context is shared with `signal_fd()` and every guard condition.
6783    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6784    pub(crate) fn clear_graph_change_signal(&mut self) {
6785        use nros_rmw::Session as _;
6786        if self.graph_change_target.is_none() {
6787            return;
6788        }
6789        // SAFETY: clearing takes no context, and the session is still live
6790        // here — this runs BEFORE `Session::close` in `close()` and before the
6791        // session field is dropped in `Drop`.
6792        unsafe {
6793            let _ = self
6794                .session
6795                .set_graph_change_callback(None, core::ptr::null());
6796        }
6797        // Only now. The backend has been told, so nothing can be holding this
6798        // pointer when it is freed.
6799        self.graph_change_target = None;
6800    }
6801
6802    /// Opaque context pointer the runtime wake
6803    /// callback receives. Encodes `(flag, mu, cv)` as a borrowed
6804    /// `&WakeCtx` reference; the callback decodes via
6805    /// `*const WakeCtx`.
6806    ///
6807    /// Lifetime: tied to the Executor instance. WakeCtx storage
6808    /// lives inside Executor (lazy-allocated on first install), so
6809    /// the pointer stays valid as long as the Executor is.
6810    /// POSIX signal-handler-safe wake fd.
6811    ///
6812    /// Returns a Linux `eventfd` that callers (typically POSIX
6813    /// signal handlers) can `write(fd, &1u64, 8)` to from any
6814    /// context, including signal handlers. A runtime-owned worker
6815    /// thread reads the fd and signals the executor's `NodeWake`, unblocking
6816    /// `spin_once`.
6817    ///
6818    /// The worker thread is spawned lazily on first call and
6819    /// joined on Executor drop. Linux-only and gated behind
6820    /// `feature = "signal-fd-wake"`; binaries that don't install
6821    /// signal handlers shouldn't enable it.
6822    ///
6823    /// Returns the raw fd. The Executor retains ownership; do not
6824    /// `close()` it from the caller.
6825    #[cfg(all(feature = "signal-fd-wake", feature = "rmw-cffi", target_os = "linux"))]
6826    /// Was `std::io::Result`. Same values, an error type that
6827    /// does not require `std`.
6828    pub fn signal_fd(&mut self) -> Result<core::ffi::c_int, NodeError> {
6829        let ctx_ptr = self.wake_ctx_ptr() as *const WakeCtx;
6830        if self.signal_fd.is_none() {
6831            self.signal_fd = Some(WakeSignalFd::new(ctx_ptr)?);
6832        }
6833        Ok(self.signal_fd.as_ref().expect("just set").fd())
6834    }
6835
6836    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
6837    fn wake_ctx_ptr(&mut self) -> *mut core::ffi::c_void {
6838        if self.wake_ctx.is_none() {
6839            self.wake_ctx = Some(portable_atomic_util::Arc::new(WakeCtx::new(
6840                self.wake_flag.clone(),
6841                self.node_wake.clone(),
6842            )));
6843        }
6844        let arc = self.wake_ctx.as_ref().expect("just set");
6845        portable_atomic_util::Arc::as_ptr(arc) as *mut core::ffi::c_void
6846    }
6847
6848    /// Phase 104.C.4 — apply a Node's default SchedContext to a
6849    /// freshly-registered handle. Called from every `_inner`
6850    /// register variant after the entry slot is committed. No-op
6851    /// when `node_id` is None (legacy path), when the Node is
6852    /// out of range, or when the Node's `default_sched` is the
6853    /// auto-created Fifo slot (0) which matches the executor's
6854    /// default binding already.
6855    ///
6856    /// Phase 273 (RFC-0047) — extends with an optional `group` name.
6857    /// Precedence: **group table > node default > no binding** (SC 0).
6858    /// When `group` is `Some(g)`, consults `group_sched_table` first;
6859    /// if no entry exists for `(name, namespace, g)` falls back to the
6860    /// node's `default_sched`. When `group` is `None` the group table
6861    /// is not consulted (unchanged phase-272 path).
6862    ///
6863    /// Handles can still override per-call via
6864    /// `bind_handle_to_sched_context(handle, sc_id)` post-register.
6865    pub(crate) fn apply_node_default_sched(
6866        &mut self,
6867        slot: usize,
6868        node_id: Option<super::node_record::NodeId>,
6869        group: Option<&str>,
6870    ) {
6871        let Some(id) = node_id else { return };
6872        // Copy name, namespace, and default_sched out so the borrow on
6873        // `self.nodes` is released before the immutable `lookup_group_sched`
6874        // borrow and the mutable `sched_context_bindings` write below.
6875        let (name, namespace, node_sc, rank) = {
6876            let Some(rec) = self.nodes.get(id.index()) else {
6877                return;
6878            };
6879            (
6880                rec.name.clone(),
6881                rec.namespace.clone(),
6882                rec.default_sched,
6883                rec.rank,
6884            )
6885        };
6886        // phase-509 P2 -- the entry dispatches at its node's rank, whatever
6887        // sched context it ends up bound to.
6888        if let Some(tag) = self.slot_tags.get_mut(slot) {
6889            tag.rank = rank;
6890        }
6891        // Phase 273: group table > node default.
6892        let sc = match group {
6893            Some(g) => self
6894                .lookup_group_sched(name.as_str(), namespace.as_str(), g)
6895                .unwrap_or(node_sc),
6896            None => node_sc,
6897        };
6898        if sc.0 == 0 {
6899            return;
6900        }
6901        if slot >= self.entries.len() {
6902            return;
6903        }
6904        let sc_idx = sc.0 as usize;
6905        if sc_idx >= self.sched_contexts.len() || self.sched_contexts[sc_idx].is_none() {
6906            return;
6907        }
6908        self.sched_context_bindings[slot] = sc;
6909    }
6910
6911    /// Scoped Node-handle access. The closure
6912    /// receives a [`NodeHandle`](crate::executor::NodeHandle) bound to the
6913    /// requested [`NodeId`](crate::executor::NodeId)'s
6914    /// session + identity. Use the standard `Node::create_publisher`,
6915    /// `create_subscription`, etc. APIs inside.
6916    ///
6917    /// rclcpp-aligned bridge pattern:
6918    ///
6919    /// ```ignore
6920    /// let node_in = exec.node_builder("ingress").rmw("zenoh").build()?;
6921    /// let node_out = exec.node_builder("egress").rmw("xrce").build()?;
6922    ///
6923    /// let pub_out = exec.with_node(node_out, |n| {
6924    ///     n.create_publisher::<Int32>("/fwd")
6925    /// })??;
6926    ///
6927    /// exec.with_node(node_in, |n| {
6928    ///     n.create_subscription_buffered::<Int32, _, 1024>(
6929    ///         "/src", qos(), move |m| { let _ = pub_out.publish(m); }
6930    ///     )
6931    /// })??;
6932    /// ```
6933    ///
6934    /// The closure can return any type; double-`?` unwraps the
6935    /// outer `Result<R, NodeError>` from `with_node` and the inner
6936    /// result returned by the closure.
6937    /// Flat-Result variant of
6938    /// [`with_node`](Self::with_node). When the closure already
6939    /// returns `Result<R, NodeError>`, this avoids the double-`?`:
6940    ///
6941    /// ```ignore
6942    /// // Without `with_node_try`:
6943    /// let pub_ = exec.with_node(id, |n| n.create_publisher(...))??;
6944    ///
6945    /// // With `with_node_try`:
6946    /// let pub_ = exec.with_node_try(id, |n| n.create_publisher(...))?;
6947    /// ```
6948    pub fn with_node_try<R>(
6949        &mut self,
6950        id: super::node_record::NodeId,
6951        f: impl FnOnce(&mut NodeHandle<'_>) -> Result<R, NodeError>,
6952    ) -> Result<R, NodeError> {
6953        self.with_node(id, f)?
6954    }
6955
6956    pub fn with_node<R>(
6957        &mut self,
6958        id: super::node_record::NodeId,
6959        f: impl FnOnce(&mut NodeHandle<'_>) -> R,
6960    ) -> Result<R, NodeError> {
6961        let (name, ns, session_idx, gate) = {
6962            let r = self
6963                .nodes
6964                .get(id.index())
6965                .ok_or(NodeError::InvalidSchedContextBinding)?;
6966            (
6967                r.name.clone(),
6968                r.namespace.clone(),
6969                r.session_idx,
6970                core::ptr::NonNull::from(&r.publish_gate),
6971            )
6972        };
6973        let monitors = self.monitor_table;
6974        let age_monitors = self.age_table;
6975        let epoch = self.epoch_us_fn;
6976        let domain_id = self.domain_id;
6977        let (session, remaps) = self
6978            .session_and_remaps_at_mut(session_idx)
6979            .ok_or(NodeError::BackendMismatch)?;
6980        // SAFETY: short-lived scoped reference. `Node::new` takes
6981        // `&mut ConcreteSession`; lifetime is bound to this fn's
6982        // body via the closure's borrow of `node`.
6983        // issue 0801 (second half) — the executor's domain, NOT a literal 0.
6984        // 429d5a581 fixed the ELEVEN arena `TopicInfo`s and left the THREE
6985        // `NodeHandle::new` sites, so an entity created through a node HANDLE
6986        // (`with_node`, `node`, ~~`node_on`~~) still declared on domain 0 while the
6987        // arena path declared on the configured one. Same split the issue is
6988        // about, one constructor over: `loan_e2e` publishes through a handle and
6989        // subscribes through the arena, so it delivered on domain 0 and on
6990        // nothing else.
6991        let mut node = NodeHandle::new(name, ns, session, remaps, domain_id);
6992        node.set_publish_gate(gate);
6993        // RFC-0052 W3b.4/.5 — seed the baked monitor tables so contracted
6994        // publishers/subscribers attach their cells without entry glue.
6995        node.set_monitors(monitors);
6996        node.set_age_monitors(age_monitors, epoch);
6997        Ok(f(&mut node))
6998    }
6999
7000    /// Find a registered executor node by final name and namespace.
7001    pub fn node_id_by_name(
7002        &self,
7003        name: &str,
7004        namespace: &str,
7005    ) -> Option<super::node_record::NodeId> {
7006        self.nodes
7007            .iter()
7008            .enumerate()
7009            .find(|(_, node)| node.name.as_str() == name && node.namespace.as_str() == namespace)
7010            .map(|(index, _)| super::node_record::NodeId::from_raw(index as u8))
7011    }
7012
7013    /// Create a node on this executor.
7014    ///
7015    /// Registers the node in the executor's table, deduplicating on
7016    /// `(name, namespace)`.
7017    ///
7018    /// # This is `rclrs::Executor::create_node`
7019    ///
7020    /// Same name, same
7021    /// place in the sequence — `Context` → executor → node — so a ported rclrs
7022    /// `main` lands here unchanged:
7023    ///
7024    /// ```ignore
7025    /// let context = nros::Context::default_from_env()?;
7026    /// let mut executor = context.create_executor()?;
7027    /// let mut node = executor.create_node("talker")?;
7028    /// ```
7029    ///
7030    /// Two differences from upstream, both structural and both named in the
7031    /// ledger row (`rust:Executor::create_node`): ours takes `&mut self`,
7032    /// because the node is registered in the executor's compile-time-sized
7033    /// table rather than allocated, and it hands back a borrowing
7034    /// [`NodeHandle`] rather than an `Arc<Node>`, because there is no
7035    /// allocator. Neither is silent — the compiler names both.
7036    ///
7037    /// The name comes from HERE, not from
7038    /// [`ExecutorConfig::node_name`](crate::ExecutorConfig::node_name), whose
7039    /// builder spelling is deprecated for exactly this reason: one executor
7040    /// holds several named nodes, so a name on the session config
7041    /// can only ever describe the first of them.
7042    ///
7043    /// Until 2026-08-24 this path registered NOTHING. It built a `NodeHandle`
7044    /// and returned it, so `node_id_by_name` could not find a node the caller
7045    /// had just created, and two calls with one name handed out two handles the
7046    /// executor had never heard of. `create_node_on_with_domain` had the dedup
7047    /// (added there when N bridge endpoints overflowed the table);
7048    /// the plain path never got it.
7049    ///
7050    /// That is a prerequisite for the `create_node` vtable slot, whose contract
7051    /// is that the runtime calls it ONCE per distinct `(name, namespace)`:
7052    /// without a registry to check, the runtime would call it once per
7053    /// `create_node` and every backend would need its own dedup — which is the
7054    /// registry the slot exists to delete (zenoh's `ensure_node_liveliness`
7055    /// linear-scans `per_node_liveliness` for exactly this reason).
7056    ///
7057    /// The table is bounded by `MAX_NODES` (`NROS_EXECUTOR_MAX_NODES`, default
7058    /// 4), so a caller creating a fifth DISTINCT node now gets
7059    /// `NodeError::NodeTableFull` where it previously got a handle. That is the
7060    /// bound doing its job: a node the executor does not know about cannot
7061    /// carry a sched context, a QoS override, or a graph identity. Repeated
7062    /// calls with the SAME name are free.
7063    ///
7064    /// Takes rclrs's `impl IntoNodeOptions`: a bare name
7065    /// (`create_node("talker")`) or a [`NodeOptions`](crate::NodeOptions)
7066    /// (`create_node("talker".namespace("/robot"))`). Here the options'
7067    /// DEFAULTS mean "the executor's": namespace `/` places the node in the
7068    /// executor's own namespace and domain `0` on its own session, as a bare
7069    /// name always did. A non-default value is applied, so an explicit `/`
7070    /// under an executor configured with another namespace, or an explicit
7071    /// domain 0 under another domain, is not expressible here; open a node on
7072    /// another domain with [`create_node_on_with_domain`](Self::create_node_on_with_domain).
7073    pub fn create_node<'o>(
7074        &mut self,
7075        options: impl crate::IntoNodeOptions<'o>,
7076    ) -> Result<super::node::Node<'_, 's>, NodeError> {
7077        let options = options.into_node_options();
7078        let name = options.name;
7079        if name.len() > 64 {
7080            return Err(NodeError::NameTooLong);
7081        }
7082        let namespace = (options.namespace != "/").then_some(options.namespace);
7083        // Dedup against the namespace the node lands in -- the executor's
7084        // own when none is named, which is what `node_builder` gives it.
7085        // phase-483 W2: this returns THE node type (`Node`, re-exported as
7086        // `nros::Node`), the same handle `node_mut` gives a component, where
7087        // it used to return a session-borrowing `NodeHandle` with a different
7088        // method set.
7089        let lookup_ns = match namespace {
7090            Some(ns) => heapless::String::<64>::try_from(ns).map_err(|_| NodeError::NameTooLong)?,
7091            None => self.namespace.clone(),
7092        };
7093        let id = match self.node_id_by_name(name, lookup_ns.as_str()) {
7094            Some(id) => id,
7095            None => {
7096                let mut builder = self.node_builder(name);
7097                if let Some(ns) = namespace {
7098                    builder = builder.namespace(ns);
7099                }
7100                if options.domain_id != 0 {
7101                    builder = builder.domain_id(options.domain_id);
7102                }
7103                builder.build()?
7104            }
7105        };
7106        Ok(super::node::Node::new(self, id))
7107    }
7108
7109    /// Bridge-mode node factory. Registers a Node
7110    /// bound to the named RMW backend by opening (or reusing) an
7111    /// extra session via `node_builder().rmw(rmw).build()`, then
7112    /// returns a [`NodeHandle`](crate::executor::NodeHandle) borrowing that
7113    /// session. Use when the
7114    /// binary intentionally links more than one backend and a Node
7115    /// must speak a specific one.
7116    ///
7117    /// The single-backend common case should keep using
7118    /// [`create_node`](Self::create_node) — this entry costs an
7119    /// extra session lookup and serves no purpose when only one
7120    /// backend is registered.
7121    #[cfg(feature = "rmw-cffi")]
7122    pub fn create_node_on(
7123        &mut self,
7124        name: &str,
7125        rmw: &str,
7126    ) -> Result<super::node::Node<'_, 's>, NodeError> {
7127        self.create_node_on_with_domain(name, rmw, None, None)
7128    }
7129
7130    /// Like [`create_node_on`](Self::create_node_on) but pins the extra
7131    /// session's domain id. Required for a multi-domain config-driven bridge:
7132    /// an extra RMW session's participant domain follows the **node builder's**
7133    /// `domain_id` (`resolve_session_slot` → `domain_id.unwrap_or(0)`), NOT the
7134    /// `SessionSpec`'s — so without this an egress on a non-zero domain silently
7135    /// opens on domain 0 and never matches its receiver.
7136    /// `None` domain preserves the legacy domain-0 default. `locator` pins the
7137    /// extra session's address — REQUIRED for an agent-based backend (xrce: the
7138    /// Micro-XRCE-DDS Agent addr) whose session can't be opened locator-less;
7139    /// `None` keeps the rmw-default (cyclonedds is domain-discovered, no locator).
7140    pub fn create_node_on_with_domain(
7141        &mut self,
7142        name: &str,
7143        rmw: &str,
7144        domain_id: Option<u32>,
7145        locator: Option<&str>,
7146    ) -> Result<super::node::Node<'_, 's>, NodeError> {
7147        if name.len() > 64 {
7148            return Err(NodeError::NameTooLong);
7149        }
7150        // Reuse an existing Node of this name rather than growing the node table
7151        // (phase-267 non-flat): a config-driven bridge calls this once per bridge
7152        // ENDPOINT, and the same session node (`s0`/`s1`) recurs across every
7153        // `[[bridge]]`. Without dedup, N bridges push 2N records and overflow
7154        // `MAX_NODES`. Names are unique per session in a generated bridge config,
7155        // so matching by name is unambiguous.
7156        let id = if let Some(i) = self.nodes.iter().position(|n| n.name.as_str() == name) {
7157            super::node_record::NodeId::from_raw(i as u8)
7158        } else {
7159            let mut builder = self.node_builder(name).rmw(rmw);
7160            if let Some(d) = domain_id {
7161                builder = builder.domain_id(d);
7162            }
7163            if let Some(loc) = locator {
7164                builder = builder.locator(loc);
7165            }
7166            builder.build()?
7167        };
7168        Ok(super::node::Node::new(self, id))
7169    }
7170
7171    /// Drive transport I/O (poll network, dispatch callbacks).
7172    #[allow(dead_code)]
7173    pub(crate) fn drive_io(&mut self, timeout_ms: i32) -> Result<(), NodeError> {
7174        self.session
7175            .drive_io(timeout_ms)
7176            .map_err(|_| NodeError::Transport(TransportError::PollFailed))
7177    }
7178
7179    /// Close the underlying session, running the shutdown hooks around it.
7180    ///
7181    /// The order is the feature:
7182    ///
7183    /// 1. every registered PRE-shutdown hook, while the session is still open
7184    ///    and every entity still works — this is where a node publishes a final
7185    ///    state, answers a last request, parks an actuator or releases a bus;
7186    /// 2. the session close;
7187    /// 3. every registered ON-shutdown hook.
7188    ///
7189    /// A hook runs EXACTLY ONCE: each phase table is emptied before its first
7190    /// hook is invoked, so a second `close()` — or the [`Drop`] sweep after one
7191    /// — finds nothing left to run. Step 2 runs even
7192    /// if a pre-shutdown hook was registered and step 3 even if the close
7193    /// failed — a hook cannot strand the session, and a dead session must not
7194    /// strand the hooks.
7195    ///
7196    /// # This is a CLEAN-STOP facility and nothing more
7197    ///
7198    /// A watchdog reset, a hard fault or a panic does not come through here, so
7199    /// these hooks do not run then. Nothing in a fixed static table can promise
7200    /// otherwise, and an API that implied it would be worse than none: hardware
7201    /// that must be safe across an abnormal stop needs a hardware answer (a
7202    /// pull-down, a watchdog-driven output disable), not a callback.
7203    pub fn close(&mut self) -> Result<(), NodeError> {
7204        self.run_shutdown_hooks(super::types::ShutdownPhase::Pre);
7205        // Issue 1385 — hand the callback back BEFORE closing the session that
7206        // holds it. `close()` leaves the executor alive, so without this a
7207        // later `set_wake_callback` from the drop sweep would reach a session
7208        // the backend has already torn down.
7209        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
7210        self.clear_wake_signal();
7211        // phase-467 Row 8 — the same obligation on the graph-change slot, and
7212        // it has to be discharged in the same place for the same reason.
7213        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
7214        self.clear_graph_change_signal();
7215        // phase-556 W13 -- the runtime's `/rosout` writers go before the
7216        // session that holds them.
7217        #[cfg(feature = "rosout")]
7218        self.release_rosout();
7219        let result = self
7220            .session
7221            .close()
7222            .map_err(|_| NodeError::Transport(TransportError::ConnectionFailed));
7223        self.run_shutdown_hooks(super::types::ShutdownPhase::Post);
7224        result
7225    }
7226
7227    /// Register a hook to run BEFORE the session is closed (issue 0790).
7228    ///
7229    /// rclcpp's `Context::add_pre_shutdown_callback`. Returns the handle
7230    /// [`Self::remove_pre_shutdown_callback`] takes, or
7231    /// [`NodeError::ShutdownCallbacksFull`] when the phase table is full —
7232    /// raise `NROS_EXECUTOR_MAX_SHUTDOWN_CBS` (default 2) at build time.
7233    ///
7234    /// # Safety
7235    /// `callback` must be safe to invoke exactly once with `context`, and
7236    /// `context` must stay valid until the hook runs or is removed. The hook
7237    /// runs on whichever task calls [`Self::close`] (or drops the executor),
7238    /// which is not necessarily the task that registered it.
7239    pub(crate) unsafe fn add_pre_shutdown_callback(
7240        &mut self,
7241        callback: super::types::ShutdownCallbackFn,
7242        context: *mut core::ffi::c_void,
7243    ) -> Result<super::types::ShutdownCallbackHandle, NodeError> {
7244        Self::claim_shutdown_slot(
7245            &mut self.pre_shutdown_hooks,
7246            super::types::ShutdownPhase::Pre,
7247            callback,
7248            context,
7249        )
7250    }
7251
7252    /// Register a hook to run AFTER the session is closed (issue 0790).
7253    ///
7254    /// rclcpp's `Context::add_on_shutdown_callback` / `rclcpp::on_shutdown`.
7255    /// Entities are gone by the time it runs, so anything that needs the wire
7256    /// belongs in [`Self::add_pre_shutdown_callback`] instead.
7257    ///
7258    /// # Safety
7259    /// Same contract as [`Self::add_pre_shutdown_callback`].
7260    pub(crate) unsafe fn add_on_shutdown_callback(
7261        &mut self,
7262        callback: super::types::ShutdownCallbackFn,
7263        context: *mut core::ffi::c_void,
7264    ) -> Result<super::types::ShutdownCallbackHandle, NodeError> {
7265        Self::claim_shutdown_slot(
7266            &mut self.on_shutdown_hooks,
7267            super::types::ShutdownPhase::Post,
7268            callback,
7269            context,
7270        )
7271    }
7272
7273    /// Remove a pre-shutdown hook. `true` if `handle` named a live one.
7274    ///
7275    /// rclcpp's `Context::remove_pre_shutdown_callback`, and `bool` for the
7276    /// same reason: "it was not there" is an ordinary answer (the hook may
7277    /// already have run), not an error. A handle issued for the OTHER phase
7278    /// returns `false` and removes nothing — that is what the phase tag in
7279    /// [`ShutdownCallbackHandle`] buys.
7280    ///
7281    /// [`ShutdownCallbackHandle`]: super::types::ShutdownCallbackHandle
7282    pub(crate) fn remove_pre_shutdown_callback(
7283        &mut self,
7284        handle: super::types::ShutdownCallbackHandle,
7285    ) -> bool {
7286        Self::release_shutdown_slot(
7287            &mut self.pre_shutdown_hooks,
7288            super::types::ShutdownPhase::Pre,
7289            handle,
7290        )
7291    }
7292
7293    /// Remove an on-shutdown hook. See [`Self::remove_pre_shutdown_callback`].
7294    pub(crate) fn remove_on_shutdown_callback(
7295        &mut self,
7296        handle: super::types::ShutdownCallbackHandle,
7297    ) -> bool {
7298        Self::release_shutdown_slot(
7299            &mut self.on_shutdown_hooks,
7300            super::types::ShutdownPhase::Post,
7301            handle,
7302        )
7303    }
7304
7305    /// How many hooks are currently registered for `phase`. Diagnostic /
7306    /// test surface, and what a "did my registration land?" assertion reads.
7307    pub fn shutdown_callback_count(&self, phase: super::types::ShutdownPhase) -> usize {
7308        let table = match phase {
7309            super::types::ShutdownPhase::Pre => &self.pre_shutdown_hooks,
7310            super::types::ShutdownPhase::Post => &self.on_shutdown_hooks,
7311        };
7312        table.iter().flatten().count()
7313    }
7314
7315    /// Claim the first free slot of a phase table.
7316    fn claim_shutdown_slot(
7317        table: &mut [Option<super::types::ShutdownHook>],
7318        phase: super::types::ShutdownPhase,
7319        callback: super::types::ShutdownCallbackFn,
7320        context: *mut core::ffi::c_void,
7321    ) -> Result<super::types::ShutdownCallbackHandle, NodeError> {
7322        for (index, slot) in table.iter_mut().enumerate() {
7323            if slot.is_some() {
7324                continue;
7325            }
7326            let handle = super::types::ShutdownCallbackHandle::new(phase, index)
7327                .ok_or(NodeError::ShutdownCallbacksFull)?;
7328            *slot = Some(super::types::ShutdownHook { callback, context });
7329            return Ok(handle);
7330        }
7331        Err(NodeError::ShutdownCallbacksFull)
7332    }
7333
7334    /// Clear a slot of a phase table, rejecting a handle from the other phase.
7335    fn release_shutdown_slot(
7336        table: &mut [Option<super::types::ShutdownHook>],
7337        phase: super::types::ShutdownPhase,
7338        handle: super::types::ShutdownCallbackHandle,
7339    ) -> bool {
7340        if handle.phase() != Some(phase) {
7341            return false;
7342        }
7343        match table.get_mut(handle.index()) {
7344            Some(slot) => slot.take().is_some(),
7345            None => false,
7346        }
7347    }
7348
7349    /// Run — and consume — every hook registered for `phase`, in registration
7350    /// order.
7351    ///
7352    /// The table is EMPTIED BEFORE the first callback runs, not slot by slot as
7353    /// the loop walks it, and both halves of that matter:
7354    ///
7355    /// * "exactly once" becomes a property of the table rather than of the
7356    ///   caller — a second `close()`, or the `Drop` sweep after one, finds
7357    ///   nothing left to run;
7358    /// * the `&mut self` borrow ENDS before any foreign code is invoked. A hook
7359    ///   is an `extern "C" fn` that may hold a raw pointer back to this
7360    ///   executor (the C and C++ shims hand out exactly that), so a hook that
7361    ///   registers or removes another one must not be running inside a live
7362    ///   `&mut` into the table it is touching.
7363    pub(crate) fn run_shutdown_hooks(&mut self, phase: super::types::ShutdownPhase) {
7364        let table = match phase {
7365            super::types::ShutdownPhase::Pre => &mut self.pre_shutdown_hooks,
7366            super::types::ShutdownPhase::Post => &mut self.on_shutdown_hooks,
7367        };
7368        // `ShutdownHook` is `Copy` (a fn pointer and a raw pointer), so this is
7369        // a register-width move of a table whose default size is two slots —
7370        // not a reason to keep the borrow open across the calls.
7371        let hooks = *table;
7372        *table = [None; crate::config::MAX_SHUTDOWN_CBS];
7373        for hook in hooks.iter().flatten() {
7374            // SAFETY: the `add_*_shutdown_callback` caller promised `callback`
7375            // is safe to invoke once with `context`, and that `context` stays
7376            // valid until the hook runs or is removed. This is that one call,
7377            // and the table is already cleared so it cannot happen again.
7378            unsafe {
7379                (hook.callback)(hook.context);
7380            }
7381        }
7382    }
7383
7384    /// Enroll a component into the executor-owned
7385    /// tick registry. Called by `nros`'s `install`/`register_node_borrowed`
7386    /// after it builds the `Arc<ComponentCell>`: `state` is the leaked
7387    /// `Arc<ComponentCell>` (the slot takes ownership), `tick`/`drop` are the
7388    /// `nros`-side trampolines (see `ComponentSlot`). The slot's `tick`
7389    /// runs at the tail of every [`spin_once`](Self::spin_once); its `drop`
7390    /// runs once on `Executor::drop`. On an executor whose
7391    /// levels own their slots, the component belongs to the registering
7392    /// level, and only that level's pass ticks it.
7393    ///
7394    /// Returns `Err(())` when the registry is full (`MAX_NODES` — raise via
7395    /// `NROS_EXECUTOR_MAX_NODES` at build time). On error the caller still
7396    /// owns `state` (the slot was not stored) and must drop it.
7397    ///
7398    /// # Safety
7399    /// `state` must be a `*mut` produced by leaking the component cell the
7400    /// `tick`/`drop` trampolines expect (an `Arc<ComponentCell>` via
7401    /// `Arc::into_raw` in the canonical `nros` caller), and must remain valid
7402    /// until the matching `drop` runs. `tick` must be safe to invoke with
7403    /// `(state, exec_ctx = *mut Executor)` each spin; `drop` must be safe to
7404    /// invoke exactly once with `state`.
7405    #[doc(hidden)]
7406    #[allow(clippy::result_unit_err)]
7407    pub unsafe fn enroll_component(
7408        &mut self,
7409        state: *mut core::ffi::c_void,
7410        tick: unsafe extern "C" fn(*mut core::ffi::c_void, *mut core::ffi::c_void),
7411        drop: unsafe extern "C" fn(*mut core::ffi::c_void),
7412    ) -> Result<(), ()> {
7413        unsafe { self.enroll_component_ticking(state, tick, drop, true) }
7414    }
7415
7416    /// [`enroll_component`](Self::enroll_component), stating
7417    /// whether the component's `tick` does any work. `ticks == false` lets
7418    /// the entry park past the spin cadence (see
7419    /// [`entry_spin_budget`](Self::entry_spin_budget)).
7420    ///
7421    /// # Safety
7422    /// As [`enroll_component`](Self::enroll_component).
7423    #[doc(hidden)]
7424    #[allow(clippy::result_unit_err)]
7425    pub unsafe fn enroll_component_ticking(
7426        &mut self,
7427        state: *mut core::ffi::c_void,
7428        tick: unsafe extern "C" fn(*mut core::ffi::c_void, *mut core::ffi::c_void),
7429        drop: unsafe extern "C" fn(*mut core::ffi::c_void),
7430        ticks: bool,
7431    ) -> Result<(), ()> {
7432        let level = self.worker.registering_level;
7433        self.component_slots
7434            .push(ComponentSlot {
7435                state,
7436                tick,
7437                drop,
7438                level,
7439                ticks,
7440            })
7441            .map_err(|_| ())
7442    }
7443
7444    /// Whether an enrolled component polls from its `tick`.
7445    pub fn has_ticking_component(&self) -> bool {
7446        self.component_slots.iter().any(|s| s.ticks)
7447    }
7448
7449    /// Current enrolled component-slot count.
7450    /// Diagnostic / test surface.
7451    #[doc(hidden)]
7452    pub fn component_slot_count(&self) -> usize {
7453        self.component_slots.len()
7454    }
7455
7456    /// The enrolled components' opaque `state` pointers, in enroll
7457    /// order. Each is the *leaked* `Arc<ComponentCell>` `enroll_component` was
7458    /// handed (see `ComponentSlot::state`); the `nros` layer re-borrows them
7459    /// to fold per-component dispatch counters into
7460    /// `observed_callback_counts` — install-seam components
7461    /// (`register_node_borrowed`) live ONLY here, not in
7462    /// `ExecutorNodeRuntime::components`, so the hosted-spin counts read zero
7463    /// without this surface.
7464    #[doc(hidden)]
7465    pub fn enrolled_component_states(&self) -> impl Iterator<Item = *mut core::ffi::c_void> + '_ {
7466        self.component_slots.iter().map(|slot| slot.state)
7467    }
7468
7469    /// Get a reference to the underlying session.
7470    pub fn session(&self) -> &session::ConcreteSession {
7471        &self.session
7472    }
7473
7474    /// Get a mutable reference to the underlying session.
7475    pub fn session_mut(&mut self) -> &mut session::ConcreteSession {
7476        &mut self.session
7477    }
7478
7479    /// Session-level connectivity probe. Wire-level
7480    /// round-trip "is the peer / agent / router still reachable?"
7481    /// — cheaper than the service-availability probe (no discovery
7482    /// state required).
7483    ///
7484    /// Returns `Ok(())` on reply within `timeout_ms`,
7485    /// `Err(NodeError::Transport(Timeout))` on no reply,
7486    /// `Err(NodeError::Transport(SessionLost))` when the peer replied and no
7487    /// longer holds this session (an XRCE Agent that restarted),
7488    /// `Err(NodeError::Transport(Unsupported))` when the active
7489    /// backend can't probe.
7490    ///
7491    /// Mirrors micro-ROS's `rmw_uros_ping_agent`. A timeout is not a verdict:
7492    /// the peer may be down and come back to the same session. `SessionLost`
7493    /// is, and stays: drop the executor and open a new one. On XRCE,
7494    /// [`spin_once`](Self::spin_once) reports the same error by itself once a
7495    /// quiet link's probe has heard it, so a loop that spins
7496    /// needs no ping of its own.
7497    pub fn ping(&mut self, timeout_ms: i32) -> Result<(), NodeError> {
7498        use nros_rmw::Session;
7499        self.session
7500            .ping_session(timeout_ms)
7501            .map_err(NodeError::Transport)
7502    }
7503
7504    /// Every node on the graph, with its namespace.
7505    ///
7506    /// `visit(name, namespace, enclave)` is called once per node and returns
7507    /// `false` to stop early. A VISITOR rather than a returned collection
7508    /// because there is no allocator at this layer and the graph has no bound
7509    /// the caller can know; peak extra memory is one entry. Every string is
7510    /// BORROWED for the duration of the call.
7511    ///
7512    /// `enclave` is `None` where the backend does not track one, which is what
7513    /// lets one call answer both `rmw_get_node_names` and
7514    /// `rmw_get_node_names_with_enclaves`.
7515    ///
7516    /// **This reports what has already been DISCOVERED, and never blocks.** The
7517    /// first call after startup legitimately sees a partial graph — the backend
7518    /// keeps a standing query fed by `spin`, so the view fills in over
7519    /// successive calls. Code that waits for a peer should poll, not call once
7520    /// and conclude. An empty result is "nobody seen yet", never "nobody
7521    /// exists".
7522    ///
7523    /// `Err(Transport(Unsupported))` from a backend with no graph — distinct
7524    /// from an empty graph, deliberately.
7525    pub fn get_node_names(
7526        &mut self,
7527        visit: &mut dyn FnMut(&str, &str, Option<&str>) -> bool,
7528    ) -> Result<(), NodeError> {
7529        use nros_rmw::Session;
7530        self.session
7531            .get_node_names(visit)
7532            .map_err(NodeError::Transport)
7533    }
7534
7535    /// Every topic on the graph, with the types on it.
7536    ///
7537    /// `visit(topic_name, types)` is called once per distinct TOPIC — a topic
7538    /// carrying two types is one call with two entries, not two calls. `types`
7539    /// may legitimately be empty on a partially discovered graph: reporting the
7540    /// name without a type beats dropping it.
7541    ///
7542    /// Same discovery caveat as [`Self::get_node_names`].
7543    pub fn get_topic_names_and_types(
7544        &mut self,
7545        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7546    ) -> Result<(), NodeError> {
7547        use nros_rmw::Session;
7548        self.session
7549            .get_topic_names_and_types(visit)
7550            .map_err(NodeError::Transport)
7551    }
7552
7553    /// Every service on the graph, with its types.
7554    /// As [`Self::get_topic_names_and_types`], over servers and clients.
7555    pub fn get_service_names_and_types(
7556        &mut self,
7557        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7558    ) -> Result<(), NodeError> {
7559        use nros_rmw::Session;
7560        self.session
7561            .get_service_names_and_types(visit)
7562            .map_err(NodeError::Transport)
7563    }
7564
7565    /// How many publishers are visible on `topic_name`.
7566    ///
7567    /// `topic_name` is a ROS name (`"/chatter"`). A count reflects what has
7568    /// been DISCOVERED, so it can be low right after startup and is never a
7569    /// proof of absence — see [`Self::get_node_names`].
7570    pub fn count_publishers(&mut self, topic_name: &str) -> Result<usize, NodeError> {
7571        use nros_rmw::Session;
7572        self.session
7573            .count_publishers(topic_name)
7574            .map_err(NodeError::Transport)
7575    }
7576
7577    /// How many subscribers are visible on `topic_name`.
7578    /// See [`Self::count_publishers`] for the caveats.
7579    pub fn count_subscribers(&mut self, topic_name: &str) -> Result<usize, NodeError> {
7580        use nros_rmw::Session;
7581        self.session
7582            .count_subscribers(topic_name)
7583            .map_err(NodeError::Transport)
7584    }
7585
7586    /// How many service CLIENTS are visible on `service_name`,
7587    /// upstream (Jazzy) `rcl_count_clients`. `service_name` is a ROS name
7588    /// (`"/add_two_ints"`); same discovery caveats as
7589    /// [`Self::count_publishers`], and a backend with no graph answers
7590    /// `Unsupported`, never `0`.
7591    pub fn count_clients(&mut self, service_name: &str) -> Result<usize, NodeError> {
7592        use nros_rmw::Session;
7593        self.session
7594            .count_clients(service_name)
7595            .map_err(NodeError::Transport)
7596    }
7597
7598    /// How many service SERVERS are visible on `service_name`,
7599    /// upstream (Jazzy) `rcl_count_services`. See [`Self::count_clients`].
7600    pub fn count_services(&mut self, service_name: &str) -> Result<usize, NodeError> {
7601        use nros_rmw::Session;
7602        self.session
7603            .count_services(service_name)
7604            .map_err(NodeError::Transport)
7605    }
7606
7607    /// What one named node PUBLISHES, with the types.
7608    ///
7609    /// `visit(topic_name, types)` per distinct topic. A node the graph has not
7610    /// discovered yields no visits, which is not an error — see
7611    /// [`Self::get_node_names`] for why an empty answer means "not seen yet".
7612    pub fn get_publisher_names_and_types_by_node(
7613        &mut self,
7614        node_name: &str,
7615        node_namespace: &str,
7616        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7617    ) -> Result<(), NodeError> {
7618        use nros_rmw::{GraphEntityKind, Session};
7619        self.session
7620            .get_names_and_types_by_node(
7621                GraphEntityKind::Publisher,
7622                node_name,
7623                node_namespace,
7624                visit,
7625            )
7626            .map_err(NodeError::Transport)
7627    }
7628
7629    /// What one named node SUBSCRIBES to, with the types.
7630    ///
7631    /// **`subscription`, not `subscriber`** — this is rclrs's spelling
7632    /// (`get_subscription_names_and_types_by_node`), and the Rust surface takes
7633    /// its vocabulary from rclrs so a user porting Rust ROS 2 code types what
7634    /// they already know. The C surface says `subscriber` because rcl does, and
7635    /// the vtable slot says `subscriber` because upstream rmw does. Three
7636    /// layers, three upstreams, one word each — not drift. A separate sweep owns the
7637    /// wider verb sweep.
7638    pub fn get_subscription_names_and_types_by_node(
7639        &mut self,
7640        node_name: &str,
7641        node_namespace: &str,
7642        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7643    ) -> Result<(), NodeError> {
7644        use nros_rmw::{GraphEntityKind, Session};
7645        self.session
7646            .get_names_and_types_by_node(
7647                GraphEntityKind::Subscriber,
7648                node_name,
7649                node_namespace,
7650                visit,
7651            )
7652            .map_err(NodeError::Transport)
7653    }
7654
7655    /// What services one named node SERVES, with the types.
7656    pub fn get_service_names_and_types_by_node(
7657        &mut self,
7658        node_name: &str,
7659        node_namespace: &str,
7660        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7661    ) -> Result<(), NodeError> {
7662        use nros_rmw::{GraphEntityKind, Session};
7663        self.session
7664            .get_names_and_types_by_node(GraphEntityKind::Service, node_name, node_namespace, visit)
7665            .map_err(NodeError::Transport)
7666    }
7667
7668    /// What services one named node CALLS, with the types.
7669    pub fn get_client_names_and_types_by_node(
7670        &mut self,
7671        node_name: &str,
7672        node_namespace: &str,
7673        visit: &mut dyn FnMut(&str, &[&str]) -> bool,
7674    ) -> Result<(), NodeError> {
7675        use nros_rmw::{GraphEntityKind, Session};
7676        self.session
7677            .get_names_and_types_by_node(GraphEntityKind::Client, node_name, node_namespace, visit)
7678            .map_err(NodeError::Transport)
7679    }
7680
7681    /// The publishers on `topic_name`, one visit each.
7682    ///
7683    /// Each `GraphEndpointInfo` BORROWS its strings for the duration of the
7684    /// visit; copy anything kept.
7685    ///
7686    /// It carries no QoS. The granted profile is what would answer "why is
7687    /// nothing arriving", and no backend can read one back yet — reporting the
7688    /// remote's DECLARED profile instead would be a confident wrong answer, so
7689    /// the field is absent rather than misleading.
7690    pub fn get_publishers_info_by_topic(
7691        &mut self,
7692        topic_name: &str,
7693        visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
7694    ) -> Result<(), NodeError> {
7695        use nros_rmw::Session;
7696        self.session
7697            .get_endpoint_info_by_topic(true, topic_name, visit)
7698            .map_err(NodeError::Transport)
7699    }
7700
7701    /// The subscriptions on `topic_name`, one visit each.
7702    /// See [`Self::get_publishers_info_by_topic`].
7703    pub fn get_subscriptions_info_by_topic(
7704        &mut self,
7705        topic_name: &str,
7706        visit: &mut dyn FnMut(&nros_rmw::GraphEndpointInfo<'_>) -> bool,
7707    ) -> Result<(), NodeError> {
7708        use nros_rmw::Session;
7709        self.session
7710            .get_endpoint_info_by_topic(false, topic_name, visit)
7711            .map_err(NodeError::Transport)
7712    }
7713
7714    /// Block until at least `count` publishers are visible on
7715    /// `topic_name`, or `timeout` elapses. Upstream's `rcl_wait_for_publishers`.
7716    ///
7717    /// Returns `Ok(true)` when the graph showed at least `count` inside the
7718    /// budget, `Ok(false)` on timeout. The startup-ordering primitive one
7719    /// entity kind over from [`EmbeddedServiceClient::wait_for_service`](super::handles::EmbeddedServiceClient::wait_for_service),
7720    /// and built the same way: a spin on a discovery read, so other
7721    /// subscriptions and timers keep making progress while it waits.
7722    ///
7723    /// **This is the one blocking member of the graph family, and it does not
7724    /// weaken the family's contract — it composes it.** The query underneath
7725    /// ([`count_publishers`](Self::count_publishers)) still reports only what
7726    /// has been DISCOVERED and still never blocks; what waits is this loop,
7727    /// and it waits by POLLING that query. The blocking-API rules govern
7728    /// it, and that rule does not forbid blocking: it requires a blocking
7729    /// helper to take an executor and drive it, which is what makes the
7730    /// timeout reliable on a single-threaded transport and what makes the
7731    /// reentrancy visible at the call site.
7732    ///
7733    /// **`Unsupported` is propagated IMMEDIATELY, not waited out** — and this
7734    /// is the one place it deliberately differs from `wait_for_service`, which
7735    /// treats a backend that cannot answer as "keep waiting" and reports
7736    /// `Ok(false)` at the deadline. That is right for a service
7737    /// probe, where not-yet-answerable is a transient. It is wrong here: a
7738    /// backend with no graph (XRCE) can never answer, so spending the budget
7739    /// to return `Ok(false)` would report "no publishers appeared" for a
7740    /// backend that cannot see publishers at all — collapsing "cannot tell
7741    /// you" into "not there", which is exactly the distinction the ROS 2 divergence rules exist
7742    /// to keep and which every other method in this family promises to keep.
7743    ///
7744    /// `count == 0` is satisfied immediately and without asking the backend —
7745    /// including on a backend with no graph, because "at least zero" is true
7746    /// of every graph and needs no discovery to establish.
7747    pub fn wait_for_publishers(
7748        &mut self,
7749        topic_name: &str,
7750        count: usize,
7751        timeout: core::time::Duration,
7752    ) -> Result<bool, NodeError> {
7753        self.wait_for_endpoints(true, topic_name, count, timeout)
7754    }
7755
7756    /// Block until at least `count` subscribers are visible on
7757    /// `topic_name`. Upstream's `rcl_wait_for_subscribers`. See
7758    /// [`wait_for_publishers`](Self::wait_for_publishers) for the contract,
7759    /// and for why `Unsupported` returns rather than waits.
7760    pub fn wait_for_subscribers(
7761        &mut self,
7762        topic_name: &str,
7763        count: usize,
7764        timeout: core::time::Duration,
7765    ) -> Result<bool, NodeError> {
7766        self.wait_for_endpoints(false, topic_name, count, timeout)
7767    }
7768
7769    /// The one loop both `wait_for_*` verbs run — a shared helper rather than
7770    /// a second spelling, because the pair differs only in which counter it
7771    /// polls and a copied loop is how the two drift.
7772    fn wait_for_endpoints(
7773        &mut self,
7774        publishers: bool,
7775        topic_name: &str,
7776        count: usize,
7777        timeout: core::time::Duration,
7778    ) -> Result<bool, NodeError> {
7779        if count == 0 {
7780            return Ok(true);
7781        }
7782        // `?`, not a swallow: a backend that cannot see the graph says so now.
7783        if self.count_endpoints(publishers, topic_name)? >= count {
7784            return Ok(true);
7785        }
7786        let spin_interval =
7787            core::time::Duration::from_millis(super::handles::DEFAULT_SPIN_INTERVAL_MS);
7788        let max_spins =
7789            (timeout.as_millis() as u64 / super::handles::DEFAULT_SPIN_INTERVAL_MS).max(1);
7790        let mut budget = super::handles::WaitBudget::new(max_spins, timeout);
7791        loop {
7792            self.spin_once(budget.next_spin_interval(spin_interval));
7793            if self.count_endpoints(publishers, topic_name)? >= count {
7794                return Ok(true);
7795            }
7796            if !budget.tick() {
7797                return Ok(false);
7798            }
7799        }
7800    }
7801
7802    /// Which counter a `wait_for_*` polls. Keeps the boolean's meaning in ONE
7803    /// place instead of at both call sites.
7804    fn count_endpoints(&mut self, publishers: bool, topic_name: &str) -> Result<usize, NodeError> {
7805        if publishers {
7806            self.count_publishers(topic_name)
7807        } else {
7808            self.count_subscribers(topic_name)
7809        }
7810    }
7811
7812    /// Get a mutable reference to an action client core in the arena by entry index.
7813    ///
7814    /// # Safety
7815    /// The caller must ensure that `entry_index` refers to an `ActionClientRawArenaEntry`.
7816    #[doc(hidden)]
7817    pub(crate) unsafe fn action_client_core_mut(
7818        &mut self,
7819        entry_index: usize,
7820    ) -> Option<&mut super::action_core::ActionClientCore> {
7821        let meta = self.entries.get(self.slot_of_raw(entry_index)?)?.as_ref()?;
7822        if !matches!(meta.kind, EntryKind::ActionClient) {
7823            return None;
7824        }
7825        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
7826        unsafe {
7827            let entry_ptr = arena_ptr.add(meta.offset)
7828                as *mut super::arena::ActionClientRawArenaEntry<
7829                    { crate::config::DEFAULT_RX_BUF_SIZE },
7830                    { crate::config::DEFAULT_RX_BUF_SIZE },
7831                    { crate::config::DEFAULT_RX_BUF_SIZE },
7832                >;
7833            Some(&mut (*entry_ptr).core)
7834        }
7835    }
7836
7837    /// Get a mutable reference to a service-client arena entry (Phase 82).
7838    ///
7839    /// Returns `None` if `entry_index` doesn't refer to a service client
7840    /// entry. The default reply buffer size is assumed because the C API
7841    /// always uses the default — the entry was registered via
7842    /// `register_service_client_raw_sized::<DEFAULT_RX_BUF_SIZE>`.
7843    ///
7844    /// # Safety
7845    /// `entry_index` must refer to a `ServiceClientRawArenaEntry`.
7846    pub(crate) unsafe fn service_client_entry_mut(
7847        &mut self,
7848        entry_index: usize,
7849    ) -> Option<&mut super::arena::ServiceClientRawArenaEntry<{ crate::config::DEFAULT_RX_BUF_SIZE }>>
7850    {
7851        let meta = self.entries.get(self.slot_of_raw(entry_index)?)?.as_ref()?;
7852        if !matches!(meta.kind, EntryKind::ServiceClient) {
7853            return None;
7854        }
7855        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
7856        unsafe {
7857            let entry_ptr = arena_ptr.add(meta.offset)
7858                as *mut super::arena::ServiceClientRawArenaEntry<
7859                    { crate::config::DEFAULT_RX_BUF_SIZE },
7860                >;
7861            Some(&mut *entry_ptr)
7862        }
7863    }
7864
7865    // ------------------------------------------------------------------
7866    // issue 1437 / phase-444 — the ARENA half of the granted-QoS read-back.
7867    //
7868    // An entity registered with a callback lives in the executor arena, and
7869    // the C / C++ handle the user holds is then bookkeeping: its inline
7870    // storage is untouched and the only identity it carries is the entry
7871    // index. So an accessor that reads the user's own storage answers for
7872    // the POLL road and returns an absence on the CALLBACK road — which is
7873    // the road a ported `rclcpp` node takes, i.e. the common one. These
7874    // three close that reach.
7875    //
7876    // Each reads the entry's HANDLE and nothing else, which is why one
7877    // function per kind serves every entry SHAPE of that kind: every arena
7878    // entry is `#[repr(C)]` with its handle as the first field (12
7879    // subscription shapes, 2 service-server, 2 service-client), so
7880    // `arena_base + offset` IS the handle pointer whatever buffer sizes and
7881    // callback types the shape was monomorphised with.
7882    // `service_client_entry_mut` above has to name ONE shape because it
7883    // reaches past the handle; these do not, and that is the whole
7884    // difference. `arena::tests::every_arena_entry_begins_with_its_handle`
7885    // pins the invariant.
7886
7887    /// The `RmwSubscriber` of an arena-registered subscription, by entry index.
7888    ///
7889    /// `None` when `entry_index` names no entry, or names one that is not a
7890    /// subscription.
7891    ///
7892    /// # Safety
7893    /// `entry_index` must be an index this executor handed out. The borrow is
7894    /// valid only while the arena is not re-entered.
7895    #[doc(hidden)]
7896    pub(crate) unsafe fn subscription_handle(
7897        &self,
7898        entry_index: usize,
7899    ) -> Option<&session::RmwSubscriber> {
7900        let meta = self.entries.get(self.slot_of_raw(entry_index)?)?.as_ref()?;
7901        if !matches!(meta.kind, EntryKind::Subscription) {
7902            return None;
7903        }
7904        let arena_ptr = self.arena.as_ptr() as *const u8;
7905        // SAFETY: `meta.offset` is inside the arena by construction, and every
7906        // subscription entry shape begins with its `RmwSubscriber`.
7907        Some(unsafe { &*(arena_ptr.add(meta.offset) as *const session::RmwSubscriber) })
7908    }
7909
7910    /// [`Executor::subscription_handle`], mutably — issue 1972: registering a
7911    /// status-event callback (`Subscription::register_event_callback`) takes
7912    /// `&mut`, and the C API's subscription is arena-owned.
7913    ///
7914    /// Issue 2060 — taking it also makes the readiness scan probe this
7915    /// subscription's `has_data` on every pass, where its backend polls the
7916    /// status events (see `entity_status_polled`).
7917    ///
7918    /// # Safety
7919    /// See [`Executor::subscription_handle`]; in addition no other borrow of
7920    /// the same entry may be live.
7921    #[doc(hidden)]
7922    pub(crate) unsafe fn subscription_handle_mut(
7923        &mut self,
7924        entry_index: usize,
7925    ) -> Option<&mut session::RmwSubscriber> {
7926        let slot = self.slot_of_raw(entry_index)?;
7927        let meta = self.entries.get(slot)?.as_ref()?;
7928        if !matches!(meta.kind, EntryKind::Subscription) {
7929            return None;
7930        }
7931        let offset = meta.offset;
7932        // Issue 2060 — `&mut` to an arena subscriber's handle exists to
7933        // register a status-event callback, and those events are polled from
7934        // `has_data`: from now on the scan asks it every pass, not only after
7935        // an arrival. Marked before the registration is known to succeed; a
7936        // refused one costs one cheap probe per pass, a missed mark costs the
7937        // event.
7938        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
7939        self.entity_status_polled.set(slot);
7940        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
7941        // SAFETY: as `subscription_handle`; `&mut self` makes the borrow unique.
7942        Some(unsafe { &mut *(arena_ptr.add(offset) as *mut session::RmwSubscriber) })
7943    }
7944
7945    /// The `RmwServiceServer` of an arena-registered service, by entry index.
7946    ///
7947    /// # Safety
7948    /// See [`Executor::subscription_handle`].
7949    #[doc(hidden)]
7950    pub(crate) unsafe fn service_server_handle(
7951        &self,
7952        entry_index: usize,
7953    ) -> Option<&session::RmwServiceServer> {
7954        let meta = self.entries.get(self.slot_of_raw(entry_index)?)?.as_ref()?;
7955        if !matches!(meta.kind, EntryKind::Service) {
7956            return None;
7957        }
7958        let arena_ptr = self.arena.as_ptr() as *const u8;
7959        // SAFETY: as above; every service-server entry shape begins with its
7960        // `RmwServiceServer`.
7961        Some(unsafe { &*(arena_ptr.add(meta.offset) as *const session::RmwServiceServer) })
7962    }
7963
7964    /// The `RmwServiceClient` of an arena-registered client, by entry index.
7965    ///
7966    /// # Safety
7967    /// See [`Executor::subscription_handle`].
7968    #[doc(hidden)]
7969    pub(crate) unsafe fn service_client_handle(
7970        &self,
7971        entry_index: usize,
7972    ) -> Option<&session::RmwServiceClient> {
7973        let meta = self.entries.get(self.slot_of_raw(entry_index)?)?.as_ref()?;
7974        if !matches!(meta.kind, EntryKind::ServiceClient) {
7975            return None;
7976        }
7977        let arena_ptr = self.arena.as_ptr() as *const u8;
7978        // SAFETY: as above; both service-client entry shapes begin with their
7979        // `RmwServiceClient` — the typed one through `ServiceClientSendHeader`,
7980        // itself `#[repr(C)]` and handle-first.
7981        Some(unsafe { &*(arena_ptr.add(meta.offset) as *const session::RmwServiceClient) })
7982    }
7983
7984    /// Set the executor-level trigger condition.
7985    ///
7986    /// Controls which handles must be ready before `spin_once` dispatches
7987    /// callbacks. Defaults to [`Trigger::Any`](crate::Trigger).
7988    pub fn set_trigger(&mut self, trigger: Trigger) {
7989        self.trigger = trigger;
7990    }
7991
7992    /// Set the executor data communication semantics.
7993    ///
7994    /// Choose between `Direct` (process in place) and `LET`
7995    /// (snapshot-then-process) semantics. See [`ExecutorSemantics`].
7996    pub fn set_semantics(&mut self, semantics: ExecutorSemantics) {
7997        self.semantics = semantics;
7998    }
7999
8000    /// Set the invocation mode for a specific handle.
8001    ///
8002    /// Controls whether the callback fires on every spin
8003    /// ([`Always`](InvocationMode::Always)) or only when new data
8004    /// arrives ([`OnNewData`](InvocationMode::OnNewData), the default).
8005    pub fn set_invocation(&mut self, id: HandleId, mode: InvocationMode) {
8006        let slot = self.live_slot(id);
8007        if let Some(Some(meta)) = self.entries.get_mut(slot) {
8008            meta.invocation = mode;
8009        }
8010    }
8011
8012    // ========================================================================
8013    // Arena-based callback registration
8014    // ========================================================================
8015
8016    /// Arena bytes claimed by registered entities so far.
8017    ///
8018    /// EXACT, not a worst case: the arena is a bump allocator and every
8019    /// `arena_alloc` charges `size_of::<T>()`, so nothing is reserved per slot.
8020    /// `ARENA_SIZE` itself is derived the other way — every slot budgeted at
8021    /// the ActionClient worst case — a known over-provision, and this accessor is
8022    /// how an image can find out what it actually needs.
8023    pub fn arena_used(&self) -> usize {
8024        self.arena_used
8025    }
8026
8027    /// Total arena bytes this executor was given.
8028    ///
8029    /// The arena is a borrowed slice; where its storage lives is the caller's
8030    /// choice, not a property of this type. Three answers are real — a `.bss`
8031    /// static (the C/C++ entries, and the `alloc` constructors since the
8032    /// named-static backing), the heap (those constructors' fallback), and a stack-declared
8033    /// `rclc_executor_t`. See `super::backing` and `report_arena_headroom`.
8034    pub fn arena_capacity(&self) -> usize {
8035        self.arena.len()
8036    }
8037
8038    /// Bump-allocate space for `T` in the arena. Returns the byte offset.
8039    pub(crate) fn arena_alloc<T>(&mut self) -> Result<usize, NodeError> {
8040        // Issue 1667 — every region is grain-aligned and at least one free-list
8041        // node long, so it can be listed when it is released.
8042        let align = core::mem::align_of::<T>().max(ARENA_GRAIN);
8043        let size = Self::arena_region_len(core::mem::size_of::<T>());
8044        if let Some((offset, granted)) = self.arena_take_freed(size, align) {
8045            crate::boot_report::note_alloc(size, self.arena_used);
8046            self.note_entry_region(offset, granted);
8047            return Ok(offset);
8048        }
8049        let aligned_offset = (self.arena_used + align - 1) & !(align - 1);
8050        let new_used = aligned_offset + size;
8051        if new_used > self.arena.len() {
8052            // issue 0900 — `BufferTooSmall` is returned by a dozen other paths,
8053            // so on a target where a return code is all you get, arena
8054            // exhaustion is indistinguishable from a message that did not fit.
8055            return Err(self.arena_exhausted(
8056                core::any::type_name::<T>(),
8057                size,
8058                new_used - self.arena.len(),
8059            ));
8060        }
8061        self.arena_used = new_used;
8062        crate::boot_report::note_alloc(size, new_used);
8063        self.note_entry_region(aligned_offset, size);
8064        Ok(aligned_offset)
8065    }
8066
8067    /// Issue 1631 — remember the region an ENTRY allocation handed out, for
8068    /// `emplace_entry` to record. Only the two entry allocators call this; a
8069    /// callback capture rides inside the entry's trailing region (phase-476
8070    /// W0), so it is part of what they record.
8071    fn note_entry_region(&mut self, offset: usize, len: usize) {
8072        self.pending_region = Some(FreedRegion { offset, len });
8073    }
8074
8075    /// Issue 1667 — the length a region of `len` requested bytes occupies:
8076    /// rounded up to the grain, and never shorter than a free-list node.
8077    const fn arena_region_len(len: usize) -> usize {
8078        let len = len.next_multiple_of(ARENA_GRAIN);
8079        if len < ARENA_MIN_REGION {
8080            ARENA_MIN_REGION
8081        } else {
8082            len
8083        }
8084    }
8085
8086    /// Bytes a callback CAPTURE takes in an entry's trailing region: its length
8087    /// rounded up to the arena's `u64` grain. 0 for no capture.
8088    ///
8089    /// phase-476 W0 — a capture used to be a SEPARATE arena allocation
8090    /// (~~`stow_capture`~~ over ~~`arena_alloc_bytes`~~), which `release_entry` never
8091    /// gave back: it frees exactly the region `emplace_entry` recorded, and that
8092    /// was the entry's. Placing the capture at the END of the entry's own
8093    /// trailing region puts it inside the recorded region, so releasing the
8094    /// entry releases its capture.
8095    pub(crate) fn capture_trailing_len(capture: Option<&[u8]>) -> usize {
8096        match capture {
8097            Some(b) if !b.is_empty() => b.len().next_multiple_of(core::mem::align_of::<u64>()),
8098            _ => 0,
8099        }
8100    }
8101
8102    /// Copy a caller's callback CAPTURE to arena offset `at` and return the
8103    /// context pointer the entry should dispatch with — phase-456 W1, made a
8104    /// runtime length by W8, made part of the entry's region by phase-476 W0.
8105    ///
8106    /// `context` is one pointer. That carries a C++ `[this]` capture and not a
8107    /// `[this, state]` (two) or a `[obj, method]` (three, because a
8108    /// pointer-to-member-function is two words on the Itanium ABI) — the
8109    /// distribution phase-442 W0 measured over this tree and the porting corpus.
8110    /// So the capture lives in the arena beside the registration that uses it:
8111    /// arena bytes never move once allocated, and the returned pointer is into
8112    /// them rather than into anything of the caller's, so the C++ side keeps
8113    /// nothing.
8114    ///
8115    /// `at` must start [`capture_trailing_len`](Self::capture_trailing_len)
8116    /// bytes the caller's entry allocation reserved for it. `None` and an empty
8117    /// slice both mean "no capture", and both give the caller's own `context`
8118    /// straight back, which is every pre-W1 caller.
8119    pub(crate) fn place_capture(
8120        &mut self,
8121        at: usize,
8122        capture: Option<&[u8]>,
8123        context: *mut core::ffi::c_void,
8124    ) -> *mut core::ffi::c_void {
8125        let bytes = match capture {
8126            Some(b) if !b.is_empty() => b,
8127            _ => return context,
8128        };
8129        debug_assert!(at + bytes.len() <= self.arena.len());
8130        // SAFETY: the caller's entry allocation reserved
8131        // `capture_trailing_len(capture)` bytes at `at` for exactly this, and
8132        // `bytes` is a caller slice that cannot alias the arena (the arena is
8133        // borrowed mutably by `self` for the whole call).
8134        unsafe {
8135            let dst = (self.arena.as_mut_ptr() as *mut u8).add(at);
8136            core::ptr::copy_nonoverlapping(bytes.as_ptr(), dst, bytes.len());
8137            dst as *mut core::ffi::c_void
8138        }
8139    }
8140
8141    /// Bump-allocate space for `T` plus `trailing_bytes` extra bytes.
8142    ///
8143    /// Returns `(entry_offset, trailing_offset)`. The trailing region starts
8144    /// immediately after `T` (aligned to 8 bytes).
8145    pub(crate) fn arena_alloc_with_trailing<T>(
8146        &mut self,
8147        trailing_bytes: usize,
8148    ) -> Result<(usize, usize), NodeError> {
8149        let align = core::mem::align_of::<T>().max(ARENA_GRAIN);
8150        let entry_size = core::mem::size_of::<T>();
8151        // Issue 1496 — a released region that holds the entry AND its trailing
8152        // region is reused whole. The trailing region keeps its rule: it starts
8153        // on a `u64` boundary after the entry, so the request is sized by that.
8154        let u64_align = core::mem::align_of::<u64>();
8155        let whole = Self::arena_region_len(entry_size.next_multiple_of(u64_align) + trailing_bytes);
8156        if let Some((entry_offset, granted)) = self.arena_take_freed(whole, align) {
8157            let trailing_offset = (entry_offset + entry_size).next_multiple_of(u64_align);
8158            crate::boot_report::note_alloc(whole, self.arena_used);
8159            self.note_entry_region(entry_offset, granted);
8160            return Ok((entry_offset, trailing_offset));
8161        }
8162        let entry_offset = self.arena_used.next_multiple_of(align);
8163        // Trailing region starts on an 8-byte (u64) boundary after the entry.
8164        let trailing_offset =
8165            (entry_offset + entry_size).next_multiple_of(core::mem::align_of::<u64>());
8166        // Issue 1667 — the region ends on the grain and is at least a node.
8167        let new_used = entry_offset + whole;
8168        debug_assert!(new_used >= trailing_offset + trailing_bytes);
8169        if new_used > self.arena.len() {
8170            // This path reported NOTHING until phase-412's self-report went in,
8171            // while its sibling `arena_alloc` has named the knob since issue
8172            // 0900. Half of arena exhaustion was therefore silent -- and it is
8173            // the half carrying buffered subscriptions and action entries,
8174            // which is what an island image actually allocates.
8175            return Err(self.arena_exhausted(
8176                core::any::type_name::<T>(),
8177                new_used - entry_offset,
8178                new_used - self.arena.len(),
8179            ));
8180        }
8181        self.arena_used = new_used;
8182        crate::boot_report::note_alloc(new_used - entry_offset, new_used);
8183        self.note_entry_region(entry_offset, new_used - entry_offset);
8184        Ok((entry_offset, trailing_offset))
8185    }
8186
8187    /// The ONE exhaustion path every arena allocator goes through — issues
8188    /// 0900, 1036, 1496.
8189    ///
8190    /// It names the knob (`report_arena_exhausted`), writes the first failure
8191    /// and its shortfall to the boot record (the only channel a console-less
8192    /// board has), says whether the failure is a SHAPE problem rather than a
8193    /// size one (released regions that together hold the request, none of
8194    /// which alone does), and — where the image asked for it — halts through
8195    /// the platform's fatal hook, so the record survives instead of the board
8196    /// running on with an entity missing. Three spellings of this existed, and
8197    /// the `_with_trailing` one reported nothing until phase-412.
8198    fn arena_exhausted(&self, entity: &'static str, request: usize, shortfall: usize) -> NodeError {
8199        super::arena::report_arena_exhausted(
8200            entity,
8201            shortfall,
8202            self.arena_used,
8203            self.arena.len(),
8204            self.arena_released(),
8205            request,
8206        );
8207        crate::boot_report::note_alloc_failed(request, shortfall);
8208        super::arena::arena_exhaustion_is_fatal();
8209        NodeError::BufferTooSmall
8210    }
8211
8212    /// Issue 1667 — read the free-list node at `offset`: `(next, len)`.
8213    fn arena_hole(&self, offset: usize) -> (usize, usize) {
8214        // SAFETY: `offset` is a listed free region: in bounds, grain-aligned and
8215        // at least `ARENA_MIN_REGION` long, written by `arena_set_hole`.
8216        unsafe {
8217            let p = (self.arena.as_ptr() as *const u8).add(offset) as *const usize;
8218            (p.read_unaligned(), p.add(1).read_unaligned())
8219        }
8220    }
8221
8222    /// Issue 1667 — write the free-list node at `offset`.
8223    fn arena_set_hole(&mut self, offset: usize, next: usize, len: usize) {
8224        debug_assert!(len >= ARENA_MIN_REGION && offset + len <= self.arena.len());
8225        // SAFETY: as `arena_hole`; the region is free, so nothing else reads it.
8226        unsafe {
8227            let p = (self.arena.as_mut_ptr() as *mut u8).add(offset) as *mut usize;
8228            p.write_unaligned(next);
8229            p.add(1).write_unaligned(len);
8230        }
8231    }
8232
8233    /// Point `prev`'s node (or the head, for `ARENA_FREE_NONE`) at `next`.
8234    fn arena_link(&mut self, prev: usize, next: usize) {
8235        if prev == ARENA_FREE_NONE {
8236            self.arena_free_head = next;
8237        } else {
8238            let (_, len) = self.arena_hole(prev);
8239            self.arena_set_hole(prev, next, len);
8240        }
8241    }
8242
8243    /// Issue 1496 / 1667 — first-fit over the free list. Returns the offset and
8244    /// the length GRANTED, which is the request plus any tail too short to list
8245    /// on its own: that tail belongs to the allocation, so its release gives it
8246    /// back. A hole whose alignment slack would be too short to list is skipped
8247    /// rather than split, for the same reason — no byte is ever orphaned.
8248    fn arena_take_freed(&mut self, size: usize, align: usize) -> Option<(usize, usize)> {
8249        let mut prev = ARENA_FREE_NONE;
8250        let mut cur = self.arena_free_head;
8251        while cur != ARENA_FREE_NONE {
8252            let (next, len) = self.arena_hole(cur);
8253            let start = cur.next_multiple_of(align);
8254            let head = start - cur;
8255            let fits = start + size <= cur + len;
8256            if fits && (head == 0 || head >= ARENA_MIN_REGION) {
8257                let tail = cur + len - (start + size);
8258                let granted = if tail < ARENA_MIN_REGION {
8259                    size + tail
8260                } else {
8261                    size
8262                };
8263                // What stays listed: the head slack, the tail, both, or neither.
8264                let mut after = next;
8265                if tail >= ARENA_MIN_REGION {
8266                    let t = start + size;
8267                    self.arena_set_hole(t, after, tail);
8268                    after = t;
8269                }
8270                if head > 0 {
8271                    self.arena_set_hole(cur, after, head);
8272                } else {
8273                    self.arena_link(prev, after);
8274                }
8275                return Some((start, granted));
8276            }
8277            prev = cur;
8278            cur = next;
8279        }
8280        None
8281    }
8282
8283    /// Issue 1496 / 1667 — give a region back. It is inserted in address order
8284    /// and coalesced with both neighbours, so a loop that frees what it
8285    /// allocated returns the arena to the shape it had; a hole that then ends
8286    /// at `arena_used` is handed back to the bump pointer.
8287    pub(crate) fn arena_release(&mut self, offset: usize, len: usize) {
8288        debug_assert!(len >= ARENA_MIN_REGION && len.is_multiple_of(ARENA_GRAIN));
8289        // `pprev` -> `prev` -> [offset] -> `cur`, in address order.
8290        let mut pprev = ARENA_FREE_NONE;
8291        let mut prev = ARENA_FREE_NONE;
8292        let mut cur = self.arena_free_head;
8293        while cur != ARENA_FREE_NONE && cur < offset {
8294            pprev = prev;
8295            prev = cur;
8296            cur = self.arena_hole(cur).0;
8297        }
8298        let (mut start, mut size) = (offset, len);
8299        let mut next = cur;
8300        if next != ARENA_FREE_NONE && start + size == next {
8301            let (after, next_len) = self.arena_hole(next);
8302            size += next_len;
8303            next = after;
8304        }
8305        if prev != ARENA_FREE_NONE {
8306            let (_, prev_len) = self.arena_hole(prev);
8307            if prev + prev_len == start {
8308                start = prev;
8309                size += prev_len;
8310                // `prev` is absorbed: link from ITS predecessor.
8311                prev = pprev;
8312            }
8313        }
8314        if start + size == self.arena_used {
8315            // The top of the arena: give it back to the bump pointer.
8316            self.arena_used = start;
8317            self.arena_link(prev, next);
8318            return;
8319        }
8320        self.arena_set_hole(start, next, size);
8321        self.arena_link(prev, start);
8322    }
8323
8324    /// Bytes released back to the arena and not yet reused.
8325    /// Bytes handed back to the bump pointer are not counted: `arena_used`
8326    /// already went down by them.
8327    pub fn arena_released(&self) -> usize {
8328        let mut total = 0;
8329        let mut cur = self.arena_free_head;
8330        while cur != ARENA_FREE_NONE {
8331            let (next, len) = self.arena_hole(cur);
8332            total += len;
8333            cur = next;
8334        }
8335        total
8336    }
8337
8338    /// How many separate holes the free list holds. For tests and
8339    /// diagnostics.
8340    pub fn arena_holes(&self) -> usize {
8341        let mut count = 0;
8342        let mut cur = self.arena_free_head;
8343        while cur != ARENA_FREE_NONE {
8344            count += 1;
8345            cur = self.arena_hole(cur).0;
8346        }
8347        count
8348    }
8349
8350    /// Issue 1496 — RELEASE one callback entry: drop the entry in place (its
8351    /// RMW handles' `Drop`s destroy the backend entities, so nothing stays
8352    /// advertised), free its callback slot, and give its arena bytes back for
8353    /// reuse. `false`, touching nothing, when `index` is not a live entry of
8354    /// `kind`.
8355    ///
8356    /// Issue 1631 — the bytes released are the ones `emplace_entry` RECORDED
8357    /// from the allocator (`CallbackMeta::arena_len`), entry and trailing
8358    /// region together. 1496's form took the size from the caller, which had
8359    /// to restate the concrete entry type — impossible for a buffered
8360    /// subscription (its trailing region is sized at runtime) or a timer (its
8361    /// closure type is the registering crate's).
8362    ///
8363    /// # Safety
8364    /// No handle naming `index` may be used afterwards: the slot and its bytes
8365    /// go to the next registration.
8366    pub(crate) unsafe fn release_entry(&mut self, index: usize, kind: EntryKind) -> bool {
8367        let live = self
8368            .entries
8369            .get(index)
8370            .and_then(|e| e.as_ref())
8371            .is_some_and(|m| m.kind == kind);
8372        if !live {
8373            return false;
8374        }
8375        // Issue 1667 — the entry's own callback is running (it, or something it
8376        // called, asked for this release). Mark it and let `finish_dispatch` do
8377        // the release when the callback returns. The handle stops resolving
8378        // now, so a second request answers `false` and nothing dispatches it.
8379
8380        if let Some(tag) = self.slot_tags.get(index)
8381            && tag.flags() & super::types::SlotTag::IN_FLIGHT != 0
8382        {
8383            let was = tag.set(super::types::SlotTag::RELEASE_PENDING);
8384            return was & super::types::SlotTag::RELEASE_PENDING == 0;
8385        }
8386        // phase-397 W2 — the slot's next occupant arms (or not) on its own.
8387        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8388        {
8389            self.entity_attributed.clear(index);
8390            self.entity_recheck.clear(index);
8391            self.entity_status_polled.clear(index);
8392        }
8393        // Issue 2146 -- the slot's next occupant starts inline and unqueued.
8394        self.forget_deferred(index);
8395        let Some(meta) = self.entries[index].take() else {
8396            return false;
8397        };
8398        // SAFETY: the entry was written by its registration and not yet
8399        // dropped; `drop_fn` matches its concrete type.
8400        unsafe {
8401            let data_ptr = (self.arena.as_mut_ptr() as *mut u8).add(meta.offset);
8402            (meta.drop_fn)(data_ptr);
8403        }
8404        // The entry's binding goes; the CONTEXT's budget state stays. It is
8405        // indexed by sched context, not by entry slot, and other entries may
8406        // still be bound to it: clearing `sporadic_states[index]` here dropped
8407        // the budget of whichever context shared the released slot's number.
8408        self.sched_context_bindings[index] = super::sched_context::SchedContextId(0);
8409        // phase10-B3 -- a released trigger subscription stops starting routes.
8410        if matches!(kind, EntryKind::Subscription) {
8411            super::monitor::route_unbind(self.monitor_table, index);
8412            super::monitor::deadline_unbind(self.age_table, index);
8413        }
8414        if let Some(len) = meta.arena_len.get() {
8415            self.arena_release(meta.offset, len);
8416        }
8417        if let Some(tag) = self.slot_tags.get_mut(index) {
8418            tag.owner = 0;
8419            tag.rank = 0;
8420            tag.reset_flags();
8421        }
8422        true
8423    }
8424
8425    /// Issue 1667 — mark `slot`'s callback as running, so a release it requests
8426    /// is deferred rather than dropping the entry under it.
8427    #[inline]
8428    pub(super) fn begin_dispatch(slot_tags: &[super::types::SlotTag], slot: usize) {
8429        if let Some(tag) = slot_tags.get(slot) {
8430            tag.set(super::types::SlotTag::IN_DISPATCH);
8431        }
8432    }
8433
8434    /// Issue 1705 — `slot`'s entry is not to be touched by the spin thread
8435    /// this pass: its release is pending (it is never dispatched again), or
8436    /// (phase-509 P9b item 2) its callback is running, in another worker's
8437    /// window or below this pass on the same stack. So one callback never
8438    /// runs twice at once, and a pass never probes or sweeps an entry whose
8439    /// callback another thread is in.
8440    #[inline]
8441    pub(super) fn slot_held(slot_tags: &[super::types::SlotTag], slot: usize) -> bool {
8442        slot_tags.get(slot).is_some_and(|t| {
8443            t.flags() & (super::types::SlotTag::RELEASE_PENDING | super::types::SlotTag::IN_FLIGHT)
8444                != 0
8445        })
8446    }
8447
8448    /// phase-509 P3 (RFC-0108 D2) -- after a callback, merge what became
8449    /// ready while it ran into this pass's ready set, so the next pick is
8450    /// from the set as it is now.
8451    ///
8452    /// - An attributed slot's arrival (its bit in the ready word) joins.
8453    /// - With [`Self::set_reprobe_each_callback`], a slot that cannot be
8454    ///   attributed is probed (`has_data`) and joins when it has data.
8455    /// - A slot the pass already `settled` (queued, dispatched or held back by
8456    ///   a gate) does not join: it runs at most once per pass. An arrival for
8457    ///   one is kept for the next pass's scan.
8458    /// - A slot whose context gates its dispatch (a sporadic budget, a
8459    ///   time-triggered window) waits for the next pass, where the scan
8460    ///   applies the gate.
8461    fn merge_mid_pass(
8462        &mut self,
8463        fifo: &mut super::ready_set::RankedFifoSet<{ MAX_CALLBACK_SLOTS }>,
8464        edf: &mut super::ready_set::BucketedEdfSet<
8465            { super::sched_context::Priority::COUNT },
8466            { MAX_CALLBACK_SLOTS },
8467        >,
8468        settled: &mut super::slot_mask::SlotMask,
8469        arena_ptr: *mut u8,
8470        band_mask: super::slot_mask::SlotMask,
8471    ) {
8472        use super::slot_mask::SlotMask;
8473        let mut fresh = SlotMask::EMPTY;
8474        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8475        let attributed = self.entity_attributed;
8476        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
8477        let attributed = SlotMask::EMPTY;
8478        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8479        {
8480            // phase-509 P9b item 2 -- this band's arrivals only.
8481            let arrived = self
8482                .wake_ctx
8483                .as_ref()
8484                .map_or(SlotMask::EMPTY, |ctx| take_band_bits(&ctx.ready, band_mask))
8485                & attributed;
8486            // Kept for the next pass: its scan asks `has_data` (the bit has
8487            // left the word, and its wake already ended no park early).
8488            self.entity_recheck |= arrived & *settled;
8489            fresh |= arrived.and_not(*settled);
8490        }
8491        if self.reprobe_each_callback {
8492            let mut probes: u32 = 0;
8493            for (i, meta) in self.entries.iter().enumerate() {
8494                let bit = SlotMask::bit(i);
8495                let Some(meta) = meta else { continue };
8496                if (*settled | attributed | fresh).intersects(bit)
8497                    || !band_mask.intersects(bit)
8498                    || matches!(meta.kind, EntryKind::Timer | EntryKind::GuardCondition)
8499                    || matches!(meta.invocation, InvocationMode::Always)
8500                    || Self::slot_held(self.slot_tags, i)
8501                {
8502                    continue;
8503                }
8504                probes = probes.wrapping_add(1);
8505                // SAFETY: as the readiness scan's probe: `meta.offset` is this
8506                // live entry's arena slot, and `has_data` only reads it.
8507                if unsafe { (meta.has_data)(arena_ptr.add(meta.offset) as *const u8) } {
8508                    fresh |= bit;
8509                }
8510            }
8511            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8512            {
8513                self.readiness_probes = self.readiness_probes.wrapping_add(probes);
8514            }
8515            #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
8516            let _ = probes;
8517        }
8518        // Issue 2146 -- a deferred slot that became ready mid-pass is queued,
8519        // not joined to the pass.
8520        if self.deferred_mask.intersects(fresh) {
8521            fresh = self.defer_ready(fresh);
8522        }
8523        if fresh.is_empty() {
8524            return;
8525        }
8526        if !self.age_table.is_empty() {
8527            super::monitor::credit_arrivals(self.age_table, fresh);
8528        }
8529        for i in fresh.iter_ones() {
8530            let bit = SlotMask::bit(i);
8531            if self.entries.get(i).is_none_or(|e| e.is_none()) || Self::slot_held(self.slot_tags, i)
8532            {
8533                #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8534                {
8535                    self.entity_recheck |= bit & attributed;
8536                }
8537                continue;
8538            }
8539            let sc_idx = self.sched_context_bindings[i].0 as usize;
8540            let sc = self.sched_contexts.get(sc_idx).and_then(|s| s.as_ref());
8541            let class = sc.map_or(super::sched_context::SchedClass::Fifo, |sc| sc.class);
8542            let priority = sc.map_or(super::sched_context::Priority::Normal, |sc| sc.priority);
8543            let windowed = self.major_frame_us > 0
8544                && sc.is_some_and(|sc| sc.tt_window_duration_us.get().is_some());
8545            if matches!(class, super::sched_context::SchedClass::Sporadic) || windowed {
8546                #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8547                {
8548                    self.entity_recheck |= bit & attributed;
8549                }
8550                continue;
8551            }
8552            let is_edf = matches!(class, super::sched_context::SchedClass::Edf);
8553            let job = super::types::ActiveJob {
8554                sort_key: if is_edf {
8555                    sc.and_then(|sc| sc.deadline_us.get())
8556                        .map_or(u32::MAX, |nz| nz.get())
8557                } else {
8558                    i as u32
8559                },
8560                desc_idx: i as super::types::DescIdx,
8561            };
8562            if is_edf {
8563                let _ = edf.insert_into(priority.index(), job);
8564            } else {
8565                let rank = self.slot_tags.get(i).map_or(0, |t| t.rank);
8566                let _ = fifo.insert_at(priority.dispatch_level(rank), job);
8567            }
8568            *settled |= bit;
8569            // As the scan does: a ready attributed slot is asked again next
8570            // spin, since one dispatch may leave data behind.
8571            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8572            {
8573                self.entity_recheck |= bit & attributed;
8574            }
8575        }
8576    }
8577
8578    /// Issue 1667 — `slot`'s callback has returned. Complete a release it
8579    /// requested while running.
8580    pub(super) fn finish_dispatch(&mut self, slot: usize) {
8581        let Some(tag) = self.slot_tags.get(slot) else {
8582            return;
8583        };
8584        // phase-509 P9b item 2 -- a cancel or reset deferred behind this
8585        // callback first, while the entry is still marked running.
8586        if tag.flags()
8587            & (super::types::SlotTag::CANCEL_PENDING | super::types::SlotTag::RESET_PENDING)
8588            != 0
8589        {
8590            self.apply_deferred_timer_op(slot);
8591        }
8592        let Some(tag) = self.slot_tags.get(slot) else {
8593            return;
8594        };
8595        let was = tag.clear(super::types::SlotTag::IN_DISPATCH);
8596        if was & super::types::SlotTag::RELEASE_PENDING != 0 {
8597            self.complete_deferred_release(slot);
8598        }
8599    }
8600
8601    /// Issue 1667 / 1705 — finish a release that was deferred while a dispatch
8602    /// of the entry was in flight, if none is any more. A no-op while one still
8603    /// is: `reap_deferred_releases` retries.
8604    fn complete_deferred_release(&mut self, slot: usize) {
8605        let Some(tag) = self.slot_tags.get(slot) else {
8606            return;
8607        };
8608        let f = tag.flags();
8609        if f & super::types::SlotTag::RELEASE_PENDING == 0
8610            || f & super::types::SlotTag::IN_FLIGHT != 0
8611        {
8612            return;
8613        }
8614        if let Some(kind) = self
8615            .entries
8616            .get(slot)
8617            .and_then(|e| e.as_ref())
8618            .map(|m| m.kind)
8619        {
8620            // SAFETY: the release was requested through a generation-checked
8621            // handle, and `resolve_handle` has refused the slot since; no
8622            // dispatch holds the entry (`IN_FLIGHT` is clear).
8623            let _ = unsafe { self.release_entry(slot, kind) };
8624        }
8625    }
8626
8627    /// Issue 1705 — complete every deferred release whose last dispatch has
8628    /// finished. `finish_dispatch` completes one deferred behind a callback
8629    /// on the spin thread when it returns; this is the backstop at the top
8630    /// of every `spin_once` (it served the retired OS-priority worker pool,
8631    /// whose worker could not touch the executor, phase-509 P11).
8632    pub(crate) fn reap_deferred_releases(&mut self) {
8633        for slot in 0..self.slot_tags.len() {
8634            if self.slot_tags[slot].flags() & super::types::SlotTag::RELEASE_PENDING != 0 {
8635                self.complete_deferred_release(slot);
8636            }
8637        }
8638    }
8639
8640    /// Issue 1631 — release a SUBSCRIPTION entry, whatever registration shape
8641    /// made it (typed, raw, in-place, buffered, with-info). See
8642    /// `release_entry` (crate-private): the entry is dropped, so its
8643    /// subscriber leaves the graph; its slot and arena bytes are reused by the
8644    /// next registration. `false`, touching nothing, when `handle` is not a
8645    /// live subscription.
8646    ///
8647    /// # Safety
8648    /// No copy of `handle` may be used afterwards — the slot is handed to the
8649    /// next registration, which may be of any kind.
8650    pub(crate) unsafe fn release_subscription(&mut self, handle: HandleId) -> bool {
8651        match self.resolve_handle(handle) {
8652            Some(slot) => unsafe { self.release_entry(slot, EntryKind::Subscription) },
8653            None => false,
8654        }
8655    }
8656
8657    /// Issue 1631 — release a TIMER entry; the timer's callback (and anything
8658    /// its closure captured) is dropped and never fires again. As
8659    /// [`release_subscription`](Self::release_subscription).
8660    ///
8661    /// # Safety
8662    /// As [`release_subscription`](Self::release_subscription).
8663    pub(crate) unsafe fn release_timer(&mut self, handle: HandleId) -> bool {
8664        match self.resolve_handle(handle) {
8665            Some(slot) => unsafe { self.release_entry(slot, EntryKind::Timer) },
8666            None => false,
8667        }
8668    }
8669
8670    /// Issue 1631 — release a SERVICE SERVER entry; the server leaves the
8671    /// graph. As [`release_subscription`](Self::release_subscription).
8672    ///
8673    /// # Safety
8674    /// As [`release_subscription`](Self::release_subscription).
8675    pub(crate) unsafe fn release_service(&mut self, handle: HandleId) -> bool {
8676        match self.resolve_handle(handle) {
8677            Some(slot) => unsafe { self.release_entry(slot, EntryKind::Service) },
8678            None => false,
8679        }
8680    }
8681
8682    /// Issue 1631 — release a SERVICE CLIENT entry; the client leaves the
8683    /// graph and any reply it was waiting for is abandoned with it. As
8684    /// [`release_subscription`](Self::release_subscription).
8685    ///
8686    /// # Safety
8687    /// As [`release_subscription`](Self::release_subscription).
8688    pub(crate) unsafe fn release_service_client(&mut self, handle: HandleId) -> bool {
8689        match self.resolve_handle(handle) {
8690            Some(slot) => unsafe { self.release_entry(slot, EntryKind::ServiceClient) },
8691            None => false,
8692        }
8693    }
8694
8695    /// Issue 1667 — release a GUARD CONDITION entry: its callback is dropped and
8696    /// `spin_once` stops polling it; the slot and its arena bytes go to the next
8697    /// registration.
8698    ///
8699    /// Unlike the other release verbs this one has a contract a generation
8700    /// cannot discharge. The [`GuardCondition`] trigger handle holds a pointer
8701    /// to the flag INSIDE the entry, and it is `Clone` + `Send`, so a clone on
8702    /// another thread (an ISR, a worker) would write into whatever reuses those
8703    /// bytes. The C++ `GuardCondition` is non-copyable and the one holder of its
8704    /// trigger handle, which is why its destructor can call this.
8705    ///
8706    /// # Safety
8707    /// No [`GuardCondition`] trigger handle for this entry — the one
8708    /// registration returned, or any clone of it — may be used afterwards.
8709    pub(crate) unsafe fn release_guard_condition(&mut self, handle: HandleId) -> bool {
8710        match self.resolve_handle(handle) {
8711            Some(slot) => unsafe { self.release_entry(slot, EntryKind::GuardCondition) },
8712            None => false,
8713        }
8714    }
8715
8716    /// Find the next free entry slot index.
8717    pub(crate) fn next_entry_slot(&self) -> Result<usize, NodeError> {
8718        self.entries
8719            .iter()
8720            .position(|e| e.is_none())
8721            // Issue 0095 — the callback-entry table (`NROS_EXECUTOR_MAX_CBS`,
8722            // default 4) is full. Distinct from `BufferTooSmall` so the register
8723            // seam can tell the user to raise the knob.
8724            .ok_or(NodeError::ExecutorFull)
8725    }
8726
8727    /// Install a finished [`CallbackMeta`] into its slot.
8728    ///
8729    /// phase-8 (`docs/design/callback_tracing.rst`) — the ONE choke point
8730    /// every registration site funnels through, so the
8731    /// nros_callback_register(handle, kind, name) event is emitted once,
8732    /// here, rather than at the 25 sites that build a `CallbackMeta`. The
8733    /// design's registration half is deliberately EXHAUSTIVE across every
8734    /// `EntryKind` even though the leaf hooks are staged: a callback that was
8735    /// registered but never observed then prints as "registered, not
8736    /// instrumented" instead of being silently absent, so an incomplete hook
8737    /// set announces itself in the output rather than looking like a
8738    /// measurement.
8739    ///
8740    /// It is the assignment — not [`next_entry_slot`](Self::next_entry_slot)
8741    /// — because a slot is claimed BEFORE the fallible work (session lookup,
8742    /// arena allocation, handle creation) that can still return `Err`.
8743    /// Emitting at slot-claim time would announce callbacks that do not
8744    /// exist.
8745    pub(crate) fn emplace_entry(
8746        &mut self,
8747        slot: usize,
8748        mut meta: CallbackMeta,
8749        name: TraceName<'_>,
8750    ) {
8751        // Issue 1631 — record the region the entry's allocation handed out,
8752        // so `release_entry` gives back exactly that. Matched on the OFFSET so
8753        // a stale region (a registration that failed after allocating) is
8754        // never attributed to a different entry.
8755        meta.arena_len = match self.pending_region.take() {
8756            Some(r) if r.offset == meta.offset => super::arena::ArenaLen::new(r.len),
8757            _ => super::arena::ArenaLen::UNRECORDED,
8758        };
8759        trace_register(slot, meta.kind, name);
8760        // phase10-B3 -- a subscription on a route's trigger topic is the
8761        // route's trigger. The table is installed before any node exists.
8762        if let (EntryKind::Subscription, TraceName::Text(topic)) = (meta.kind, &name) {
8763            super::monitor::route_bind(self.monitor_table, topic, slot);
8764        }
8765        // phase-463 W7 — the slot's identity for the host profile, keyed on the
8766        // arena base the dispatch sees (stable for the executor's life).
8767        #[cfg(feature = "profile-mode")]
8768        super::profile::on_register(self.arena.as_ptr() as usize, slot, meta.kind, name);
8769        self.entries[slot] = Some(meta);
8770        // Issue 2018 -- the registering level's own context (0, the default,
8771        // when it has none); a node or group binding still overrides it.
8772        if let Some(b) = self.sched_context_bindings.get_mut(slot) {
8773            *b = super::sched_context::SchedContextId(self.worker.registering_sched);
8774        }
8775        // phase-476 W0 — a new occupant gets a new generation, so every handle
8776        // issued for the slot's previous occupant stops resolving. Owner is
8777        // cleared; a registration made for a node sets it after this
8778        // (`set_entry_owner`).
8779        if let Some(tag) = self.slot_tags.get_mut(slot) {
8780            tag.generation = tag.next_generation();
8781            tag.owner = 0;
8782            tag.rank = 0;
8783            // phase-509 P9b item 4 -- the level being set up owns it.
8784            tag.level = self.worker.registering_level;
8785            tag.reset_flags();
8786        }
8787    }
8788
8789    /// phase-397 W2 — register `slot`'s entity with THIS executor's wake
8790    /// context, through `register` (the entry handle's `register_waker`).
8791    ///
8792    /// Called by every subscription, service and client registration AFTER
8793    /// the entry is written into the arena: the handle's address is stable
8794    /// from then on, and a backend that keeps a pointer into the handle (the
8795    /// cffi route's per-entity `user_data`) must not see it move.
8796    ///
8797    /// Records whether the backend accepted it in `entity_attributed`. A
8798    /// backend that cannot attribute an arrival returns `false`, and the
8799    /// session-scoped wake keeps covering that entry. Without the async wake
8800    /// primitive, or without `rmw-cffi`, there is nothing to wake and this does
8801    /// nothing.
8802    #[allow(unused_variables, unused_mut)]
8803    pub(crate) fn arm_entity_wake(
8804        &mut self,
8805        slot: usize,
8806        register: impl FnOnce(&core::task::Waker) -> bool,
8807    ) {
8808        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8809        {
8810            if self.node_wake.is_none() || slot >= super::entity_wake::SLOTS {
8811                return;
8812            }
8813            self.wake_ctx_ptr();
8814            let Some(waker) = self
8815                .wake_ctx
8816                .as_ref()
8817                .and_then(|ctx| super::entity_wake::waker(ctx, slot))
8818            else {
8819                return;
8820            };
8821            if register(&waker) {
8822                self.entity_attributed.set(slot);
8823                // W3 — the backend replays nothing that arrived before this
8824                // call, so the first spin asks `has_data` once.
8825                self.entity_recheck.set(slot);
8826            } else {
8827                self.entity_attributed.clear(slot);
8828                self.entity_recheck.clear(slot);
8829            }
8830        }
8831    }
8832
8833    /// [`arm_entity_wake`](Self::arm_entity_wake) for the entry of type `T`
8834    /// at arena `offset`: the one place a registration site's entry is read
8835    /// back to reach its handle.
8836    ///
8837    /// # Safety
8838    ///
8839    /// A `T` was written at `offset` and is the live occupant of `slot`. It
8840    /// stays at that address until its release, which drops the handle (and
8841    /// with it the backend's registration) first.
8842    pub(crate) unsafe fn arm_entry_wake<T>(
8843        &mut self,
8844        slot: usize,
8845        offset: usize,
8846        register: impl FnOnce(&T, &core::task::Waker) -> bool,
8847    ) {
8848        let entry = self
8849            .arena
8850            .as_ptr()
8851            .cast::<u8>()
8852            .wrapping_add(offset)
8853            .cast::<T>();
8854        // SAFETY: the caller's contract — a live `T` at `offset`.
8855        self.arm_entity_wake(slot, |w| register(unsafe { &*entry }, w));
8856    }
8857
8858    /// The ready words' first 64 slots, taken: every slot below 64 an
8859    /// attributed arrival marked since the last take (a slot above stays in
8860    /// its word; [`Self::take_entity_ready_mask`] takes every slot).
8861    /// `spin_once` consumes the words (W3), so a caller that also spins sees
8862    /// only what arrived since the last spin. Tests only.
8863    #[doc(hidden)]
8864    pub fn take_entity_ready_bits(&self) -> u64 {
8865        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8866        if let Some(ctx) = self.wake_ctx.as_ref() {
8867            return ctx
8868                .ready
8869                .take_masked(super::slot_mask::SlotMask::from_word0(u64::MAX))
8870                .word(0);
8871        }
8872        0
8873    }
8874
8875    /// [`Self::take_entity_ready_bits`] over every slot.
8876    #[allow(dead_code)] // tests only
8877    pub(crate) fn take_entity_ready_mask(&self) -> super::slot_mask::SlotMask {
8878        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8879        if let Some(ctx) = self.wake_ctx.as_ref() {
8880            return ctx.ready.take();
8881        }
8882        super::slot_mask::SlotMask::EMPTY
8883    }
8884
8885    /// The slots below 64 whose backend accepted an entity waker
8886    /// ([`Self::entity_attributed_mask`] names every slot).
8887    #[doc(hidden)]
8888    pub fn entity_attributed_slots(&self) -> u64 {
8889        self.entity_attributed_mask().word(0)
8890    }
8891
8892    /// The slots whose backend accepted an entity waker.
8893    pub(crate) fn entity_attributed_mask(&self) -> super::slot_mask::SlotMask {
8894        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8895        return self.entity_attributed;
8896        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
8897        super::slot_mask::SlotMask::EMPTY
8898    }
8899
8900    /// How many `has_data` calls the readiness scan has made
8901    /// (wrapping). An attributed slot's readiness comes from its arrival bit,
8902    /// so a spin over attributed entries alone adds nothing here. Tests only;
8903    /// `0` in a build with no entity wake, where it is not counted.
8904    #[doc(hidden)]
8905    pub fn readiness_probe_count(&self) -> u32 {
8906        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
8907        return self.readiness_probes;
8908        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
8909        0
8910    }
8911
8912    /// Probe the slots whose backend cannot
8913    /// attribute an arrival (XRCE, uORB) after every callback, so one made
8914    /// ready by a callback runs in the same pass, in rank order, instead of
8915    /// at the next pass's scan. Pushed readiness joins mid-pass either way.
8916    /// The default is `REPROBE_EACH_CALLBACK_DEFAULT` (in `executor/spin.rs`); the
8917    /// host measurement that chose it is recorded beside that constant.
8918    pub fn set_reprobe_each_callback(&mut self, on: bool) {
8919        self.reprobe_each_callback = on;
8920    }
8921
8922    /// phase-476 W0 — the handle for the CURRENT occupant of `slot`. Every
8923    /// registration returns this, after `emplace_entry` has stamped the slot.
8924    pub(crate) fn handle_for(&self, slot: usize) -> HandleId {
8925        let generation = self.slot_tags.get(slot).map_or(0, |t| t.generation);
8926        HandleId::new(slot, generation)
8927    }
8928
8929    /// The slot `id` names, if and only if `id` was
8930    /// issued for the entry that occupies it NOW. A handle whose entry was
8931    /// released, or whose slot has since been taken by another registration of
8932    /// any kind, answers `None`, never the next occupant.
8933    pub fn resolve_handle(&self, id: HandleId) -> Option<usize> {
8934        let slot = id.slot();
8935        let live = self.entries.get(slot).is_some_and(|e| e.is_some())
8936            && self
8937                .slot_tags
8938                .get(slot)
8939                .is_none_or(|t| t.flags() & super::types::SlotTag::RELEASE_PENDING == 0);
8940        // Generation 0 is `HandleId::for_owned_slot`: a uniquely-owned holder
8941        // naming its own live slot. Every ISSUED handle carries >= 1.
8942        let current = id.generation() == 0
8943            || self
8944                .slot_tags
8945                .get(slot)
8946                .is_some_and(|t| t.generation == id.generation());
8947        (live && current).then_some(slot)
8948    }
8949
8950    /// Issue 1703 — the slot behind a by-index accessor's `entry_index`
8951    /// argument, which callers hand in in TWO spellings: a bare slot (nros-c's
8952    /// stored `arena_entry_index`, `node_runtime`'s resolved slot, an action's
8953    /// owned slot) or the PACKED handle an FFI issued (`HandleId::to_raw`,
8954    /// what nros-cpp's `handle_id_` and nros-c's `subscription.handle_id`
8955    /// hold since phase-476 W0). A bare slot has generation 0, so both decode
8956    /// through [`HandleId::from_raw`] and resolve here: the slot for a live
8957    /// entry, generation-checked when one was issued, `None` for a stale or
8958    /// foreign handle.
8959    ///
8960    /// The five accessors indexed `entries` with the argument as given. W0 made
8961    /// the FFI value a packed `(generation << 16) | slot`, so every packed
8962    /// caller read past the table and got `None` — `async_send_request` on a
8963    /// C++ callback client returned `INVALID_ARGUMENT` on every call, and the
8964    /// granted-QoS read-backs answered for no entity.
8965    fn slot_of_raw(&self, entry_index: usize) -> Option<usize> {
8966        self.resolve_handle(HandleId::from_raw(entry_index))
8967            .filter(|&slot| !self.running_elsewhere(slot))
8968    }
8969
8970    /// phase-476 W0 — [`resolve_handle`](Self::resolve_handle) as an index that
8971    /// is OUT OF RANGE for a stale handle, so an existing `entries.get(..)`
8972    /// chain answers `None` for it with no further change.
8973    ///
8974    /// phase-509 P9b item 2 -- also out of range while the entry's callback
8975    /// runs in another thread's window (`running_elsewhere`): the accessors
8976    /// that go through here touch the entry's arena data, which that callback
8977    /// owns until it returns. The caller sees what a stale handle gets, and
8978    /// may retry once the callback has returned.
8979    pub(crate) fn live_slot(&self, id: HandleId) -> usize {
8980        self.resolve_handle(id)
8981            .filter(|&slot| !self.running_elsewhere(slot))
8982            .unwrap_or(usize::MAX)
8983    }
8984
8985    /// phase-476 W0 — record that `node` registered the entry `id` names, so
8986    /// [`release_node`](Self::release_node) can find it. `false` when `id` is
8987    /// stale.
8988    pub(crate) fn set_entry_owner(&mut self, id: HandleId, node: crate::executor::NodeId) -> bool {
8989        let Some(slot) = self.resolve_handle(id) else {
8990            return false;
8991        };
8992        let Ok(biased) = u8::try_from(node.index() + 1) else {
8993            return false;
8994        };
8995        self.slot_tags[slot].owner = biased;
8996        true
8997    }
8998
8999    /// phase-476 W0 — release every entry `node` registered, whatever its kind.
9000    /// Returns how many were released.
9001    ///
9002    /// This is what a node's destruction calls. A C++ callback's capture is
9003    /// copied into the arena and commonly holds the node's `this`, so an entry
9004    /// that outlived its node would dispatch into freed memory.
9005    ///
9006    /// # Safety
9007    /// No handle to any of those entries may be used afterwards except through
9008    /// a lookup that checks the generation ([`resolve_handle`](Self::resolve_handle)),
9009    /// which every public lookup on this type does.
9010    pub(crate) unsafe fn release_node(&mut self, node: crate::executor::NodeId) -> usize {
9011        let Ok(biased) = u8::try_from(node.index() + 1) else {
9012            return 0;
9013        };
9014        let mut released = 0;
9015        for slot in 0..self.entries.len() {
9016            if self.slot_tags.get(slot).is_some_and(|t| t.owner == biased) {
9017                let kind = match self.entries[slot].as_ref() {
9018                    Some(m) => m.kind,
9019                    None => continue,
9020                };
9021                // SAFETY: forwarded from this function's contract.
9022                if unsafe { self.release_entry(slot, kind) } {
9023                    released += 1;
9024                }
9025            }
9026        }
9027        released
9028    }
9029
9030    /// Open a subscription: claim a slot, resolve the node's identity, create
9031    /// the backend subscriber, and answer the in-place question ONCE.
9032    ///
9033    /// **phase-456 W8 — the one prologue.** Every registration that creates its
9034    /// own subscriber goes through here, in every language. The two callers
9035    /// that do not are the two that cannot: `add_arena_subscription_callback`
9036    /// is handed a subscriber someone else built (uORB needs a
9037    /// `&'static orb_metadata`, which no `TopicInfo` can express), so there is
9038    /// no topic to resolve and no session to reach — a fourth axis under issue
9039    /// 1319's rows that W8's three-axis decomposition did not predict: WHO
9040    /// CREATED THE SUBSCRIBER. It is a real axis, it is orthogonal to the other
9041    /// three, and it has exactly one member.
9042    ///
9043    /// Everything downstream of this function differs per delivery shape: the
9044    /// arena entry's type, its `try_process`, and whether it has a receive
9045    /// region at all. That part is irreducible and stays at the call site.
9046    pub(crate) fn open_subscription(
9047        &mut self,
9048        req: &SubscriptionRequest<'_>,
9049    ) -> Result<SubscriptionOpen, NodeError> {
9050        let slot = self.next_entry_slot()?;
9051        let (node_name, ns, session_idx) = self.entity_identity(req.node_id)?;
9052        let mut topic = TopicInfo::new(req.topic_name, req.type_name, req.type_hash)
9053            .with_domain(self.domain_id)
9054            .with_namespace(&ns);
9055        if !node_name.is_empty() {
9056            topic = topic.with_node_name(&node_name);
9057        }
9058        // Phase 231 (RFC-0038) / phase-402 W2 — hand the backend a
9059        // receive-buffer size so it can size-class its receive storage
9060        // (zenoh-pico: small vs large). Only when the caller actually stated
9061        // one: `with_rx_buffer_hint(0)` would be a claim of "zero bytes", not
9062        // "no opinion".
9063        if let Some(hint) = req.backend_hint {
9064            if hint != 0 {
9065                topic = topic.with_rx_buffer_hint(hint);
9066            }
9067        }
9068        // phase-454 W10/W13 — the depth this registration asks for against the
9069        // depth this system DECLARED for the topic. Before the backend call AND
9070        // before the arena claim, so the region this registration takes and the
9071        // one the build reserved are the same number; unchanged when nothing
9072        // was declared, which is every image with no contract sidecar. See
9073        // `declared_qos::honour` for why Rust TAKES the declared depth where C
9074        // and C++ assert it at the call site.
9075        //
9076        // phase-456 W8 — this used to be `declared_qos::check` here and
9077        // `honour` in each of the twelve hand-rolled prologues this function
9078        // replaced. Collapsing them onto `check` would have silently reverted
9079        // W13 for every Rust registration: `check` validates and returns, while
9080        // `honour` REWRITES the depth the backend is then given. One consulting
9081        // site is the point of this function, and it has to be the honouring
9082        // one.
9083        let qos = crate::declared_qos::honour(topic.type_name, topic.name, req.qos)?;
9084        // phase-519 W3b (RFC-0074) — the subscription's declared arrival rate,
9085        // for a backend that paces delivery itself (XRCE asks its agent for
9086        // `rate_hz x rx_buffer_hint` bytes a second). Unchanged when nothing
9087        // was declared.
9088        let topic = crate::declared_qos::with_declared_arrival_rate(topic);
9089        let age_table = self.age_table;
9090        let (handle, deadline_row) = {
9091            let session = self
9092                .session_at_mut(session_idx)
9093                .ok_or(NodeError::BackendMismatch)?;
9094            // phase-462 W5b — a contract `deadline` the backend cannot judge
9095            // is judged by the silence rule instead, never dropped silently and
9096            // never a boot refusal (`monitor::admit_contract_deadline`).
9097            let (qos, deadline_row) = super::monitor::admit_contract_deadline(
9098                qos,
9099                nros_rmw::Session::supported_qos_policies(session),
9100                age_table,
9101                req.topic_name,
9102            );
9103            let handle = session
9104                .create_subscription(&topic, qos)
9105                .map_err(NodeError::Transport)?;
9106            (handle, deadline_row)
9107        };
9108        if let Some(row) = deadline_row {
9109            row.cell
9110                .deadline_slot
9111                .store(slot as u32 + 1, core::sync::atomic::Ordering::Relaxed);
9112            nros_log::log_info!(
9113                nros_log::get_logger("nros_node"),
9114                "qos: subscription '{}' deadline {} ms is judged by silence-runtime \
9115                 (the backend does not judge it)",
9116                req.topic_name,
9117                row.deadline_ms
9118            );
9119        }
9120        // Phase 231 Wave 0.2 (RFC-0038), phase-456 W8 — THE consulting site.
9121        // Deliberately `&&`-guarded by the delivery shape rather than by the
9122        // language: a shape that must hand the callback more than borrowed
9123        // bytes cannot use the capability however capable the backend is.
9124        let in_place = req.in_place_capable && {
9125            use nros_rmw::Subscription as _;
9126            handle.supports_process_in_place()
9127        };
9128        // phase-457 W3 — tell a metadata probe what this CALL SITE answered.
9129        //
9130        // `req.in_place_capable` and NOT `in_place`: the conjunction above
9131        // includes the backend a probe links, which is the RECORDING backend and
9132        // not the one the image ships. The sizing descriptor knows the shipped
9133        // backend from the image's `rmw` name and composes the two halves
9134        // itself; what it cannot see is this half, which is why nine of the
9135        // eleven registration entry points were previously credited with a
9136        // capability they do not have (issue 1340).
9137        //
9138        // AFTER the backend call, so a registration that failed reports
9139        // nothing — a row for a subscription that does not exist would raise the
9140        // probe's count, and an over-count of subscriptions is a real cost in
9141        // every pool that derives from it.
9142        #[cfg(feature = "registration-observer")]
9143        super::registration_observer::observe(super::registration_observer::ObservedRegistration {
9144            topic: topic.name,
9145            type_name: topic.type_name,
9146            in_place_capable: req.in_place_capable,
9147            // Issue 1648 -- the slot this registration is about to claim, read
9148            // off the request rather than inferred: `DEFAULT_RX_BUF_SIZE`
9149            // (`RX_BUF`) is the closure buffer (`unbounded`), anything else a
9150            // stated bound.
9151            claims_closure_buffer: req.slot_bytes == crate::config::DEFAULT_RX_BUF_SIZE,
9152        });
9153        Ok(SubscriptionOpen {
9154            slot,
9155            handle,
9156            qos,
9157            in_place,
9158            slot_bytes: req.slot_bytes,
9159        })
9160    }
9161
9162    /// Typed buffered subscription core (the `node_mut(id).subscription(t)
9163    /// .typed::<M>()` builder lowers here). Routes the typed subscription
9164    /// through the [`NodeId`]'s session + identity (rclcpp `add_node` pattern).
9165    ///
9166    /// Phase 403 W2 -- `rx_bytes` says how many bytes each buffer slot claims
9167    /// from the arena.
9168    ///
9169    /// phase-392 W3c -- `Some(n)` is verbatim; **`None` now means DERIVE from
9170    /// `M`**, falling back to `RX_BUF` only where no bound is reachable (an
9171    /// unbounded type, or a backend whose `MessageForRmw` carries no schema).
9172    /// It used to mean `RX_BUF` unconditionally, so a subscription that named no
9173    /// number was charged the global for every slot and a consumer who did not
9174    /// know `.rx_buffer_from_type()` existed paid it silently. The opt-out is
9175    /// now the explicit one: `.rx_buffer::<N>()` passes `Some(N)`.
9176    ///
9177    /// It is a RUNTIME `usize` and not a second const generic because on THIS
9178    /// path `RX_BUF` was never an array length -- it reaches
9179    /// `buffered_region_size`, `TripleBuffer::init` and `SpscRing::init`, all of
9180    /// which take a plain `usize`. That is the only reason W2's per-type sizing
9181    /// is expressible here at all: `Sub<{ M::BOUND }>` is
9182    /// `error: generic parameters may not be used in const operations` on stable
9183    /// (rustc 1.97.1), so the sibling `register_subscription_with_info_sized_inner`
9184    /// / `..._with_safety_sized_inner`, whose entries really do hold
9185    /// `[u8; RX_BUF]`, still need `nros::rx_buffer_for!` at the call site.
9186    pub(crate) fn register_subscription_buffered_on<M, F, const RX_BUF: usize>(
9187        &mut self,
9188        node_id: super::node_record::NodeId,
9189        topic_name: &str,
9190        qos: QoSProfile,
9191        callback: F,
9192        group: Option<&str>,
9193        rx_bytes: Option<usize>,
9194    ) -> Result<HandleId, NodeError>
9195    where
9196        M: crate::rmw_type_registry::MessageForRmw + 'static,
9197        F: FnMut(&M) + 'static,
9198    {
9199        type Entry<M, F> = SubBufferedEntry<M, F>;
9200
9201        // RFC-0088 / phase-421 W1 — the message's declared format must be the
9202        // one the linked backend speaks. Universal: the const lives on
9203        // `RosMessage`, which `MessageForRmw` requires under every backend.
9204        crate::format_check::assert_message_format::<M>();
9205        // Phase 212.K.7.6.b — see `create_publisher_on`.
9206        crate::rmw_type_registry::register_type::<M>()?;
9207
9208        // W3b.5 — contracted-endpoint age hook (None = free).
9209        let age_mon = self.age_lookup::<M>(topic_name);
9210
9211        // Phase 403 W2 -- one number for the whole allocation. The region size,
9212        // the strategy's slot size and the pointer arithmetic must agree, so
9213        // they read the same local rather than each spelling `RX_BUF`.
9214        //
9215        // phase-392 W3c -- and `None` no longer means `RX_BUF`, it means DERIVE.
9216        // This is the one choke point every default registration funnels
9217        // through, so putting the derivation here is what makes it the default
9218        // at all four of them (`create_subscription`, `create_subscription_in_group`,
9219        // the builder's `build()`, and the `/clock` time source) instead of at
9220        // whichever one a wave happened to touch. An explicit `Some(n)` -- what
9221        // `.rx_buffer::<N>()` and `.rx_buffer_from_type()` pass -- is still
9222        // verbatim, so the opt-out and the opt-in both bypass this line.
9223        let slot_bytes = crate::rmw_type_registry::subscription_slot_bytes::<M>(rx_bytes, RX_BUF);
9224
9225        let open = self.open_subscription(&SubscriptionRequest {
9226            node_id: Some(node_id),
9227            topic_name,
9228            type_name: <M as RosMessage>::TYPE_NAME,
9229            type_hash: <M as RosMessage>::TYPE_HASH,
9230            qos,
9231            // Phase 392 W3a — the TYPE's bound, not `RX_BUF`. The arena slot
9232            // size says nothing about the message: a 64-byte type and a 4 KiB
9233            // type both hinted the same number, so the class was chosen from a
9234            // value unrelated to what arrives. Falls back to `RX_BUF` for an
9235            // unbounded type, where no bound exists to state (phase 380).
9236            backend_hint: Some(crate::rmw_type_registry::subscription_rx_hint::<M>(RX_BUF)),
9237            slot_bytes,
9238            // A typed Rust callback takes `&M` and nothing else, so borrowed
9239            // bytes are enough: deserialize straight from the backend's slot.
9240            in_place_capable: true,
9241        })?;
9242        let SubscriptionOpen {
9243            slot,
9244            handle,
9245            qos,
9246            in_place,
9247            slot_bytes,
9248        } = open;
9249
9250        // Phase 231 Wave 0.2 (RFC-0038) — in-place dispatch when the backend
9251        // advertises it: deserialize straight from the borrowed receive slot,
9252        // no arena buffer (copy #1 removed). Else the buffered path below.
9253        if in_place {
9254            let entry_offset = self.arena_alloc::<SubInplaceEntry<M, F>>()?;
9255            unsafe {
9256                let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9257                let entry_ptr = arena_ptr.add(entry_offset) as *mut SubInplaceEntry<M, F>;
9258                core::ptr::write(
9259                    entry_ptr,
9260                    SubInplaceEntry {
9261                        handle,
9262                        callback,
9263                        age_mon,
9264                        _phantom: PhantomData,
9265                    },
9266                );
9267            }
9268            let meta = CallbackMeta {
9269                offset: entry_offset,
9270                kind: EntryKind::Subscription,
9271                arena_len: super::arena::ArenaLen::UNRECORDED,
9272                try_process: sub_inplace_try_process::<M, F>,
9273                has_data: sub_inplace_has_data::<M, F>,
9274                pre_sample: no_pre_sample,
9275                invocation: InvocationMode::OnNewData,
9276                drop_fn: drop_entry::<SubInplaceEntry<M, F>>,
9277            };
9278            self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9279            // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9280            // SAFETY: a `SubInplaceEntry<M, F>` was written at `entry_offset` just above.
9281            unsafe {
9282                self.arm_entry_wake::<SubInplaceEntry<M, F>>(slot, entry_offset, |e, w| {
9283                    nros_rmw::Subscription::register_waker(&e.handle, w)
9284                })
9285            };
9286            self.apply_node_default_sched(slot, Some(node_id), group);
9287            return Ok(self.handle_for(slot));
9288        }
9289
9290        let (_slot_count, trailing_bytes) = buffered_region_size(qos.depth, slot_bytes);
9291
9292        let (entry_offset, trailing_offset) =
9293            self.arena_alloc_with_trailing::<Entry<M, F>>(trailing_bytes)?;
9294
9295        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
9296
9297        let buffer = if qos.depth <= 1 {
9298            BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, slot_bytes) })
9299        } else {
9300            BufferStrategy::Ring(unsafe { SpscRing::init(buf_ptr, slot_bytes, qos.depth as usize) })
9301        };
9302
9303        unsafe {
9304            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9305            let entry_ptr = arena_ptr.add(entry_offset) as *mut Entry<M, F>;
9306            core::ptr::write(
9307                entry_ptr,
9308                Entry {
9309                    handle,
9310                    buffer,
9311                    callback,
9312                    age_mon,
9313                    _phantom: PhantomData,
9314                },
9315            );
9316        }
9317
9318        let meta = CallbackMeta {
9319            offset: entry_offset,
9320            kind: EntryKind::Subscription,
9321            arena_len: super::arena::ArenaLen::UNRECORDED,
9322            try_process: sub_buffered_try_process::<M, F>,
9323            has_data: sub_buffered_has_data::<M, F>,
9324            pre_sample: no_pre_sample,
9325            invocation: InvocationMode::OnNewData,
9326            drop_fn: drop_entry::<Entry<M, F>>,
9327        };
9328        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9329        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9330        // SAFETY: a `Entry<M, F>` was written at `entry_offset` just above.
9331        unsafe {
9332            self.arm_entry_wake::<Entry<M, F>>(slot, entry_offset, |e, w| {
9333                nros_rmw::Subscription::register_waker(&e.handle, w)
9334            })
9335        };
9336        // Phase 104.C.4 — apply Node's default SchedContext.
9337        self.apply_node_default_sched(slot, Some(node_id), group);
9338        Ok(self.handle_for(slot))
9339    }
9340
9341    /// Generic (type-erased) buffered subscription core (the
9342    /// `node_mut(id).subscription(t).generic(ty, hash)` builder lowers here).
9343    /// Routes the subscriber creation through the [`NodeId`]'s
9344    /// session + identity (rclcpp `add_node` pattern).
9345    ///
9346    /// Use this in bridge code where two Nodes bind to different RMW
9347    /// backends:
9348    ///
9349    /// ```ignore
9350    /// let node_in = exec.node_builder("ingress").rmw("zenoh").build()?;
9351    /// let pub_out = exec.with_node(node_out, |n| {
9352    ///     n.create_publisher_raw("/fwd", TYPE, HASH)
9353    /// })??;
9354    /// exec.register_subscription_buffered_raw_on::<_, 1024>(
9355    ///     node_in, "/src", TYPE, HASH, qos(), None,
9356    ///     move |bytes: &[u8]| { let _ = pub_out.publish_serialized(bytes); },
9357    /// )?;
9358    /// ```
9359    #[allow(clippy::too_many_arguments)]
9360    pub(crate) fn register_subscription_buffered_raw_on<F, const RX_BUF: usize>(
9361        &mut self,
9362        node_id: super::node_record::NodeId,
9363        topic_name: &str,
9364        type_name: &str,
9365        type_hash: &str,
9366        qos: QoSProfile,
9367        backend_hint: Option<usize>,
9368        callback: F,
9369    ) -> Result<HandleId, NodeError>
9370    where
9371        F: FnMut(&[u8]) + 'static,
9372    {
9373        // Issue #52 — fold the node's baked overrides for this topic before the
9374        // backend-compat check runs inside `create_subscription`.
9375        //
9376        // **This is the one registration that does it**, which phase-456 W8
9377        // noticed while collapsing the twelve prologues into one and did NOT
9378        // change: the other eleven reach `create_subscription` with the QoS
9379        // their caller passed. Whether that is a defect or a deliberate limit
9380        // of the generic bridge path is a question with a measurable answer and
9381        // no answer here, so the asymmetry stays where it was, stated.
9382        let qos = self.fold_node_qos_overrides(node_id, topic_name, qos)?;
9383
9384        let SubscriptionOpen {
9385            slot,
9386            handle,
9387            qos,
9388            in_place,
9389            slot_bytes,
9390        } = self.open_subscription(&SubscriptionRequest {
9391            node_id: Some(node_id),
9392            topic_name,
9393            type_name,
9394            type_hash,
9395            qos,
9396            // Issue 2208 -- the caller's statement of the type's bound. A
9397            // type-erased caller that knows the type (the declarative
9398            // runtime, from its entity metadata) states it; one that does not
9399            // passes `None`, "stated nothing".
9400            backend_hint,
9401            slot_bytes: RX_BUF,
9402            // Issue 1340 — `FnMut(&[u8])` IS a borrowed-bytes callback, which is
9403            // exactly what `process_raw_in_place` hands over, so this shape takes
9404            // the in-place row the way the C raw path does.
9405            //
9406            // This used to be `false` because the buffered entry is shared with
9407            // `Self::add_arena_subscription_callback` and "an in-place twin would
9408            // have to serve both". It does not: that caller supplies its own
9409            // subscriber and never reaches `open_subscription`, so no in-place
9410            // report can arrive there. The branch below is local to this entry
9411            // point, and the shared buffered emplace is untouched.
9412            //
9413            // phase-457 W5 (issue 1522) — spelled as the SHAPE rather than as a
9414            // literal, because the declarative registrar lowers here and the
9415            // metadata probe must state the same bool without registering. One
9416            // definition (`DeclaredSubscriptionShape::in_place_capable`), two
9417            // readers, so the row the build prices and the claim made here
9418            // moved together when it flipped.
9419            in_place_capable: super::declared_shape::DeclaredSubscriptionShape::BufferedRaw
9420                .in_place_capable(),
9421        })?;
9422
9423        if in_place {
9424            // No receive region: the backend's slot is the buffer for the
9425            // duration of the callback. This is the whole of issue 1340's saving
9426            // on the generic path — `buffered_region_size(depth, RX_BUF)` is
9427            // never reserved.
9428            type Entry<F> = super::arena::SubInplaceRawEntry<F>;
9429            let entry_offset = self.arena_alloc::<Entry<F>>()?;
9430            unsafe {
9431                let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9432                let entry_ptr = arena_ptr.add(entry_offset) as *mut Entry<F>;
9433                core::ptr::write(entry_ptr, Entry { handle, callback });
9434            }
9435            let meta = CallbackMeta {
9436                offset: entry_offset,
9437                kind: EntryKind::Subscription,
9438                arena_len: super::arena::ArenaLen::UNRECORDED,
9439                try_process: super::arena::sub_inplace_raw_try_process::<F>,
9440                has_data: super::arena::sub_inplace_raw_has_data::<F>,
9441                pre_sample: no_pre_sample,
9442                invocation: InvocationMode::OnNewData,
9443                drop_fn: drop_entry::<Entry<F>>,
9444            };
9445            // Same trace name as the buffered arm, so a trace reads the same
9446            // whichever dispatch the backend chose.
9447            self.emplace_entry(slot, meta, TraceName::Slot("sub", slot));
9448            // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9449            // SAFETY: a `Entry<F>` was written at `entry_offset` just above.
9450            unsafe {
9451                self.arm_entry_wake::<Entry<F>>(slot, entry_offset, |e, w| {
9452                    nros_rmw::Subscription::register_waker(&e.handle, w)
9453                })
9454            };
9455        } else {
9456            self.emplace_raw_buffered_subscription(slot, handle, qos, slot_bytes, callback)?;
9457        }
9458        // Phase 104.C.4 — apply Node's default SchedContext.
9459        self.apply_node_default_sched(slot, Some(node_id), None);
9460        Ok(self.handle_for(slot))
9461    }
9462
9463    /// Register a borrowed (zero-copy) buffered subscription (Phase 229.6,
9464    /// issue 0007 / RFC-0033 `borrowed` mode).
9465    ///
9466    /// `B` is the code-generated borrowed-message marker (e.g. `ImageViewable`)
9467    /// implementing [`ViewableMessage`](nros_core::ViewableMessage); the
9468    /// callback receives `&B::View<'a>` — a lifetime-carrying message whose
9469    /// unbounded sequence/string fields borrow directly from the receive buffer
9470    /// (no `heapless::Vec` copy). The view is valid only for the callback's
9471    /// duration.
9472    ///
9473    /// **Triple-buffer only.** A borrowed view must reference exactly one
9474    /// well-defined buffer slot for the callback's duration; an SPSC ring
9475    /// (`qos.depth > 1`) keeps several samples in flight with no single such
9476    /// slot. `qos.depth > 1` is therefore rejected with
9477    /// [`TransportError::Unsupported`].
9478    pub(crate) fn register_subscription_buffered_borrowed_on<B, F, const RX_BUF: usize>(
9479        &mut self,
9480        node_id: super::node_record::NodeId,
9481        topic_name: &str,
9482        qos: QoSProfile,
9483        callback: F,
9484    ) -> Result<HandleId, NodeError>
9485    where
9486        B: nros_core::ViewableMessage + 'static,
9487        F: for<'a> FnMut(&B::View<'a>) + 'static,
9488    {
9489        type Entry<B, F> = SubBufferedViewEntry<B, F>;
9490
9491        // Borrowed views require a single well-defined slot (triple buffer).
9492        if qos.depth > 1 {
9493            return Err(NodeError::Transport(TransportError::Unsupported));
9494        }
9495
9496        let SubscriptionOpen { slot, handle, .. } =
9497            self.open_subscription(&SubscriptionRequest {
9498                node_id: Some(node_id),
9499                topic_name,
9500                type_name: <B as ViewableMessage>::TYPE_NAME,
9501                type_hash: <B as ViewableMessage>::TYPE_HASH,
9502                qos,
9503                backend_hint: None,
9504                slot_bytes: RX_BUF,
9505                // The view borrows the arena's own triple-buffer slot for the
9506                // callback's duration and `ViewableMessage::deserialize_view` is
9507                // what produces it, so there is no `FnMut(&[u8])` here to hand a
9508                // backend slot to. Making this shape in-place is a real option and
9509                // a separate change: it would move the borrow from the arena to the
9510                // backend's ring, which is a lifetime argument this item did not
9511                // make.
9512                in_place_capable: false,
9513            })?;
9514
9515        let (_slot_count, trailing_bytes) = buffered_region_size(qos.depth, RX_BUF);
9516        let (entry_offset, trailing_offset) =
9517            self.arena_alloc_with_trailing::<Entry<B, F>>(trailing_bytes)?;
9518        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
9519
9520        // depth <= 1 guaranteed above → always triple buffer.
9521        let buffer = BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, RX_BUF) });
9522
9523        unsafe {
9524            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9525            let entry_ptr = arena_ptr.add(entry_offset) as *mut Entry<B, F>;
9526            core::ptr::write(
9527                entry_ptr,
9528                Entry {
9529                    handle,
9530                    buffer,
9531                    callback,
9532                    _phantom: PhantomData,
9533                },
9534            );
9535        }
9536
9537        let meta = CallbackMeta {
9538            offset: entry_offset,
9539            kind: EntryKind::Subscription,
9540            arena_len: super::arena::ArenaLen::UNRECORDED,
9541            try_process: sub_buffered_view_try_process::<B, F>,
9542            has_data: sub_buffered_view_has_data::<B, F>,
9543            pre_sample: no_pre_sample,
9544            invocation: InvocationMode::OnNewData,
9545            drop_fn: drop_entry::<Entry<B, F>>,
9546        };
9547        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9548        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9549        // SAFETY: a `Entry<B, F>` was written at `entry_offset` just above.
9550        unsafe {
9551            self.arm_entry_wake::<Entry<B, F>>(slot, entry_offset, |e, w| {
9552                nros_rmw::Subscription::register_waker(&e.handle, w)
9553            })
9554        };
9555        self.apply_node_default_sched(slot, Some(node_id), None);
9556        Ok(self.handle_for(slot))
9557    }
9558
9559    /// Fold node `node_id`'s baked QoS overrides for subscription `topic` into
9560    /// `qos`: the step the declared subscription paths take before opening
9561    /// (issue #52). Shared so the metadata-carrying declared path (issue
9562    /// 2349) keeps a component's overrides exactly as the plain one does.
9563    pub(crate) fn fold_node_qos_overrides(
9564        &self,
9565        node_id: super::node_record::NodeId,
9566        topic: &str,
9567        qos: QoSProfile,
9568    ) -> Result<QoSProfile, NodeError> {
9569        let overrides = self
9570            .nodes
9571            .get(node_id.index())
9572            .ok_or(NodeError::InvalidSchedContextBinding)?
9573            .qos_overrides;
9574        Ok(super::node_record::apply_qos_override_codes(
9575            qos,
9576            topic,
9577            nros_rmw::QoSOverrideRole::Subscription,
9578            overrides,
9579        ))
9580    }
9581
9582    /// Register a raw (type-erased) buffered subscription whose callback
9583    /// also receives a [`RawMessageInfo`](nros_core::RawMessageInfo)
9584    /// carrying the sample's wire **attachment**.
9585    ///
9586    /// Backs the `node.subscription(t).generic(..).message_info().build(cb)`
9587    /// builder — the cross-RMW bridge reads the bridge_origin tag from
9588    /// `info.attachment()` for echo suppression. One sample per
9589    /// `spin_once`; the attachment is staged in a flat per-entry buffer
9590    /// (cap `RAW_INFO_ATT_CAP`).
9591    pub fn register_subscription_buffered_raw_info_on<F, const RX_BUF: usize>(
9592        &mut self,
9593        node_id: super::node_record::NodeId,
9594        topic_name: &str,
9595        type_name: &str,
9596        type_hash: &str,
9597        qos: QoSProfile,
9598        callback: F,
9599    ) -> Result<HandleId, NodeError>
9600    where
9601        F: FnMut(&[u8], &nros_core::RawMessageInfo) + 'static,
9602    {
9603        type Entry<F> = SubBufferedRawInfoEntry<F>;
9604
9605        let SubscriptionOpen {
9606            slot,
9607            handle,
9608            slot_bytes,
9609            ..
9610        } = self.open_subscription(&SubscriptionRequest {
9611            node_id: Some(node_id),
9612            topic_name,
9613            type_name,
9614            type_hash,
9615            qos,
9616            backend_hint: None,
9617            slot_bytes: RX_BUF,
9618            // The callback also receives the sample's wire ATTACHMENT, which
9619            // `process_raw_in_place` does not carry: it hands over borrowed
9620            // payload bytes and nothing else. Not a limitation of the backend.
9621            in_place_capable: false,
9622        })?;
9623
9624        // Issue 1860 -- in the trailing region, as the C twin. A raw subscription
9625        // has no type to derive from, so the size is still `RX_BUF`.
9626        let (offset, trailing) = self.arena_alloc_with_trailing::<Entry<F>>(slot_bytes)?;
9627        unsafe {
9628            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9629            let buffer = super::arena::TrailingBuf::init(arena_ptr.add(trailing), slot_bytes);
9630            let entry_ptr = arena_ptr.add(offset) as *mut Entry<F>;
9631            core::ptr::write(
9632                entry_ptr,
9633                Entry {
9634                    handle,
9635                    buffer,
9636                    att: [0u8; super::arena::RAW_INFO_ATT_CAP],
9637                    callback,
9638                },
9639            );
9640        }
9641
9642        let meta = CallbackMeta {
9643            offset,
9644            kind: EntryKind::Subscription,
9645            arena_len: super::arena::ArenaLen::UNRECORDED,
9646            try_process: sub_buffered_raw_info_try_process::<F>,
9647            has_data: sub_buffered_raw_info_has_data::<F>,
9648            pre_sample: no_pre_sample,
9649            invocation: InvocationMode::OnNewData,
9650            drop_fn: drop_entry::<Entry<F>>,
9651        };
9652        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9653        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9654        // SAFETY: a `Entry<F>` was written at `offset` just above.
9655        unsafe {
9656            self.arm_entry_wake::<Entry<F>>(slot, offset, |e, w| {
9657                nros_rmw::Subscription::register_waker(&e.handle, w)
9658            })
9659        };
9660        self.apply_node_default_sched(slot, Some(node_id), None);
9661        Ok(self.handle_for(slot))
9662    }
9663
9664    /// Register a generic (type-erased) raw subscription
9665    /// that surfaces E2E [`IntegrityStatus`](nros_rmw::IntegrityStatus) (CRC +
9666    /// sequence gap/dup) alongside the raw CDR bytes
9667    /// (`FnMut(&[u8], &IntegrityStatus)`). The type-erased analog of
9668    /// `register_subscription_with_safety_sized_inner`: the validator lives in
9669    /// the `RmwSubscriber` (`take_validated`), so the subscriber is created
9670    /// plainly and no `register_type::<M>()` is needed (the declarative `Node`
9671    /// path is generic). Used by the declarative runtime's `.safety()` opt-in.
9672    #[cfg(feature = "safety-e2e")]
9673    #[allow(clippy::too_many_arguments)]
9674    pub fn register_subscription_buffered_raw_safety_on<F, const RX_BUF: usize>(
9675        &mut self,
9676        node_id: super::node_record::NodeId,
9677        topic_name: &str,
9678        type_name: &str,
9679        type_hash: &str,
9680        qos: QoSProfile,
9681        backend_hint: Option<usize>,
9682        callback: F,
9683    ) -> Result<HandleId, NodeError>
9684    where
9685        F: FnMut(&[u8], &nros_rmw::IntegrityStatus) + 'static,
9686    {
9687        use super::arena::{
9688            SubBufferedRawSafetyEntry, sub_buffered_raw_safety_has_data,
9689            sub_buffered_raw_safety_try_process,
9690        };
9691        type Entry<F> = SubBufferedRawSafetyEntry<F>;
9692
9693        let SubscriptionOpen {
9694            slot,
9695            handle,
9696            slot_bytes,
9697            ..
9698        } = self.open_subscription(&SubscriptionRequest {
9699            node_id: Some(node_id),
9700            topic_name,
9701            type_name,
9702            type_hash,
9703            qos,
9704            backend_hint, // Issue 2208 -- as the basic raw path.
9705            slot_bytes: RX_BUF,
9706            // The sample is taken through `take_validated`, which computes the
9707            // integrity status as it copies. `process_raw_in_place` has no
9708            // validating form, so this shape cannot use it.
9709            //
9710            // phase-457 W5 (issue 1522) — as the SHAPE, for the reason its
9711            // sibling in `register_subscription_buffered_raw_on` gives.
9712            in_place_capable: super::declared_shape::DeclaredSubscriptionShape::BufferedRawSafety
9713                .in_place_capable(),
9714        })?;
9715
9716        // Issue 1860 -- in the trailing region; untyped, so still `RX_BUF` bytes.
9717        let (offset, trailing) = self.arena_alloc_with_trailing::<Entry<F>>(slot_bytes)?;
9718        unsafe {
9719            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9720            let buffer = super::arena::TrailingBuf::init(arena_ptr.add(trailing), slot_bytes);
9721            let entry_ptr = arena_ptr.add(offset) as *mut Entry<F>;
9722            core::ptr::write(
9723                entry_ptr,
9724                Entry {
9725                    handle,
9726                    buffer,
9727                    callback,
9728                },
9729            );
9730        }
9731
9732        let meta = CallbackMeta {
9733            offset,
9734            kind: EntryKind::Subscription,
9735            arena_len: super::arena::ArenaLen::UNRECORDED,
9736            try_process: sub_buffered_raw_safety_try_process::<F>,
9737            has_data: sub_buffered_raw_safety_has_data::<F>,
9738            pre_sample: no_pre_sample,
9739            invocation: InvocationMode::OnNewData,
9740            drop_fn: drop_entry::<Entry<F>>,
9741        };
9742        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9743        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9744        // SAFETY: a `Entry<F>` was written at `offset` just above.
9745        unsafe {
9746            self.arm_entry_wake::<Entry<F>>(slot, offset, |e, w| {
9747                nros_rmw::Subscription::register_waker(&e.handle, w)
9748            })
9749        };
9750        self.apply_node_default_sched(slot, Some(node_id), None);
9751        Ok(self.handle_for(slot))
9752    }
9753
9754    /// Register a raw byte-shaped callback against a pre-built
9755    /// `RmwSubscriber` handle.
9756    ///
9757    /// Backend-agnostic primitive — the caller is responsible for
9758    /// obtaining the handle by whatever route the active backend
9759    /// supports:
9760    ///
9761    /// - **Generic ROS-typed flow**: call `Session::create_subscription`
9762    ///   on `self.session_mut()` with a [`TopicInfo`]. The
9763    ///   `node_mut(id).subscription(t).generic(ty, hash)` builder is the
9764    ///   convenience wrapper for this path.
9765    /// - **Backend-specific flow** (e.g. uORB needs `&'static orb_metadata`):
9766    ///   reach into the concrete session via [`Self::session_mut`] and
9767    ///   call its backend-specific create method, then hand the handle
9768    ///   here. `nros-px4::uorb::create_subscription_with_callback` is
9769    ///   the example.
9770    ///
9771    /// The arena-store + vtable wiring is identical to
9772    /// `register_subscription_buffered_raw_on`; the only thing that varies is
9773    /// where the handle came from. Callback fires on every message
9774    /// delivery during [`spin_once`](Self::spin_once); bytes are
9775    /// passed as `&[u8]`.
9776    pub fn add_arena_subscription_callback<F, const RX_BUF: usize>(
9777        &mut self,
9778        handle: session::RmwSubscriber,
9779        qos: QoSProfile,
9780        callback: F,
9781    ) -> Result<HandleId, NodeError>
9782    where
9783        F: FnMut(&[u8]) + 'static,
9784    {
9785        let slot = self.next_entry_slot()?;
9786        self.emplace_raw_buffered_subscription(slot, handle, qos, RX_BUF, callback)?;
9787        Ok(self.handle_for(slot))
9788    }
9789
9790    /// Write a raw buffered subscription entry into an already-claimed slot —
9791    /// phase-456 W8.
9792    ///
9793    /// The shared tail of [`Self::add_arena_subscription_callback`] and
9794    /// `register_subscription_buffered_raw_on`, which differ only in where the
9795    /// subscriber came from: one is handed a live `RmwSubscriber`, the other
9796    /// resolves a topic through [`Self::open_subscription`] and gets one back.
9797    /// Both then build exactly this entry, and they used to build it twice —
9798    /// the bridge path by CALLING the other, which meant it claimed a slot,
9799    /// resolved a topic, and then let the callee claim a second slot it did not
9800    /// need.
9801    fn emplace_raw_buffered_subscription<F>(
9802        &mut self,
9803        slot: usize,
9804        handle: session::RmwSubscriber,
9805        qos: QoSProfile,
9806        slot_bytes: usize,
9807        callback: F,
9808    ) -> Result<(), NodeError>
9809    where
9810        F: FnMut(&[u8]) + 'static,
9811    {
9812        type Entry<F> = SubBufferedRawEntry<F>;
9813
9814        let (_slot_count, trailing_bytes) = buffered_region_size(qos.depth, slot_bytes);
9815
9816        let (entry_offset, trailing_offset) =
9817            self.arena_alloc_with_trailing::<Entry<F>>(trailing_bytes)?;
9818
9819        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
9820
9821        let buffer = if qos.depth <= 1 {
9822            BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, slot_bytes) })
9823        } else {
9824            BufferStrategy::Ring(unsafe { SpscRing::init(buf_ptr, slot_bytes, qos.depth as usize) })
9825        };
9826
9827        unsafe {
9828            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9829            let entry_ptr = arena_ptr.add(entry_offset) as *mut Entry<F>;
9830            core::ptr::write(
9831                entry_ptr,
9832                Entry {
9833                    handle,
9834                    buffer,
9835                    callback,
9836                },
9837            );
9838        }
9839
9840        let meta = CallbackMeta {
9841            offset: entry_offset,
9842            kind: EntryKind::Subscription,
9843            arena_len: super::arena::ArenaLen::UNRECORDED,
9844            try_process: sub_buffered_raw_try_process::<F>,
9845            has_data: sub_buffered_raw_has_data::<F>,
9846            pre_sample: no_pre_sample,
9847            invocation: InvocationMode::OnNewData,
9848            drop_fn: drop_entry::<Entry<F>>,
9849        };
9850        self.emplace_entry(slot, meta, TraceName::Slot("sub", slot));
9851        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9852        // SAFETY: a `Entry<F>` was written at `entry_offset` just above.
9853        unsafe {
9854            self.arm_entry_wake::<Entry<F>>(slot, entry_offset, |e, w| {
9855                nros_rmw::Subscription::register_waker(&e.handle, w)
9856            })
9857        };
9858        Ok(())
9859    }
9860
9861    pub(crate) fn register_subscription_with_info_sized_inner<M, F, const RX_BUF: usize>(
9862        &mut self,
9863        node_id: Option<super::node_record::NodeId>,
9864        topic_name: &str,
9865        qos: QoSProfile,
9866        callback: F,
9867        // Issue 1860 -- `Some(n)` is a size the caller NAMED (`.rx_buffer::<N>()`),
9868        // used verbatim; `None` derives it from `M` exactly as the buffered path
9869        // does, falling back to `RX_BUF` only where `M` states no bound.
9870        rx_bytes: Option<usize>,
9871    ) -> Result<HandleId, NodeError>
9872    where
9873        M: crate::rmw_type_registry::MessageForRmw + 'static,
9874        F: FnMut(&M, Option<&nros_core::MessageInfo>) + 'static,
9875    {
9876        type Entry<M, F> = SubInfoEntry<M, F>;
9877
9878        // Phase 212.K.7.6.b — see `create_publisher_on`.
9879        crate::rmw_type_registry::register_type::<M>()?;
9880
9881        let SubscriptionOpen {
9882            slot,
9883            handle,
9884            slot_bytes,
9885            ..
9886        } = self.open_subscription(&SubscriptionRequest {
9887            node_id,
9888            topic_name,
9889            type_name: <M as RosMessage>::TYPE_NAME,
9890            type_hash: <M as RosMessage>::TYPE_HASH,
9891            qos,
9892            backend_hint: None,
9893            slot_bytes: crate::rmw_type_registry::subscription_slot_bytes::<M>(rx_bytes, RX_BUF),
9894            // The entry's `pre_sample` hook stages a `MessageInfo` beside the
9895            // payload before the callback runs; an in-place drain has no
9896            // pre-sample step to hang it on.
9897            in_place_capable: false,
9898        })?;
9899
9900        let (offset, trailing) = self.arena_alloc_with_trailing::<Entry<M, F>>(slot_bytes)?;
9901
9902        unsafe {
9903            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9904            let buffer = super::arena::TrailingBuf::init(arena_ptr.add(trailing), slot_bytes);
9905            let entry_ptr = arena_ptr.add(offset) as *mut Entry<M, F>;
9906            core::ptr::write(
9907                entry_ptr,
9908                Entry {
9909                    handle,
9910                    buffer,
9911                    sampled_len: 0,
9912                    callback,
9913                    _phantom: PhantomData,
9914                },
9915            );
9916        }
9917
9918        let meta = CallbackMeta {
9919            offset,
9920            kind: EntryKind::Subscription,
9921            arena_len: super::arena::ArenaLen::UNRECORDED,
9922            try_process: sub_info_try_process::<M, F>,
9923            has_data: sub_info_has_data::<M, F>,
9924            pre_sample: sub_info_pre_sample::<M, F>,
9925            invocation: InvocationMode::OnNewData,
9926            drop_fn: drop_entry::<Entry<M, F>>,
9927        };
9928        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
9929        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
9930        // SAFETY: a `Entry<M, F>` was written at `offset` just above.
9931        unsafe {
9932            self.arm_entry_wake::<Entry<M, F>>(slot, offset, |e, w| {
9933                nros_rmw::Subscription::register_waker(&e.handle, w)
9934            })
9935        };
9936        self.apply_node_default_sched(slot, node_id, None);
9937        Ok(self.handle_for(slot))
9938    }
9939
9940    #[cfg(feature = "safety-e2e")]
9941    pub(crate) fn register_subscription_with_safety_sized_inner<M, F, const RX_BUF: usize>(
9942        &mut self,
9943        node_id: Option<super::node_record::NodeId>,
9944        topic_name: &str,
9945        qos: QoSProfile,
9946        callback: F,
9947        // Issue 1860 -- as `register_subscription_with_info_sized_inner`.
9948        rx_bytes: Option<usize>,
9949    ) -> Result<HandleId, NodeError>
9950    where
9951        M: crate::rmw_type_registry::MessageForRmw + 'static,
9952        F: FnMut(&M, &nros_rmw::IntegrityStatus) + 'static,
9953    {
9954        type Entry<M, F> = SubSafetyEntry<M, F>;
9955
9956        // Phase 212.K.7.6.b — see `create_publisher_on`.
9957        crate::rmw_type_registry::register_type::<M>()?;
9958
9959        let SubscriptionOpen {
9960            slot,
9961            handle,
9962            slot_bytes,
9963            ..
9964        } = self.open_subscription(&SubscriptionRequest {
9965            node_id,
9966            topic_name,
9967            type_name: <M as RosMessage>::TYPE_NAME,
9968            type_hash: <M as RosMessage>::TYPE_HASH,
9969            qos,
9970            backend_hint: None,
9971            slot_bytes: crate::rmw_type_registry::subscription_slot_bytes::<M>(rx_bytes, RX_BUF),
9972            // Same as the raw safety sibling: the status comes out of
9973            // `take_validated`, which is a copying take.
9974            in_place_capable: false,
9975        })?;
9976
9977        let (offset, trailing) = self.arena_alloc_with_trailing::<Entry<M, F>>(slot_bytes)?;
9978
9979        unsafe {
9980            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
9981            let buffer = super::arena::TrailingBuf::init(arena_ptr.add(trailing), slot_bytes);
9982            let entry_ptr = arena_ptr.add(offset) as *mut Entry<M, F>;
9983            core::ptr::write(
9984                entry_ptr,
9985                Entry {
9986                    handle,
9987                    buffer,
9988                    sampled_len: 0,
9989                    callback,
9990                    _phantom: PhantomData,
9991                },
9992            );
9993        }
9994
9995        let meta = CallbackMeta {
9996            offset,
9997            kind: EntryKind::Subscription,
9998            arena_len: super::arena::ArenaLen::UNRECORDED,
9999            try_process: sub_safety_try_process::<M, F>,
10000            has_data: sub_safety_has_data::<M, F>,
10001            pre_sample: sub_safety_pre_sample::<M, F>,
10002            invocation: InvocationMode::OnNewData,
10003            drop_fn: drop_entry::<Entry<M, F>>,
10004        };
10005        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
10006        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
10007        // SAFETY: a `Entry<M, F>` was written at `offset` just above.
10008        unsafe {
10009            self.arm_entry_wake::<Entry<M, F>>(slot, offset, |e, w| {
10010                nros_rmw::Subscription::register_waker(&e.handle, w)
10011            })
10012        };
10013        self.apply_node_default_sched(slot, node_id, None);
10014        Ok(self.handle_for(slot))
10015    }
10016
10017    /// Register a service callback with the default buffer size.
10018    ///
10019    /// The callback is stored in the arena and invoked during [`spin_once()`](Self::spin_once).
10020    pub fn register_service<Svc, F>(
10021        &mut self,
10022        service_name: &str,
10023        callback: F,
10024    ) -> Result<HandleId, NodeError>
10025    where
10026        Svc: RosService + 'static,
10027        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10028        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10029        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
10030    {
10031        self.register_service_sized::<Svc, F, { crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(service_name, callback)
10032    }
10033
10034    /// Register a service callback with custom request/reply buffer sizes.
10035    pub fn register_service_sized<Svc, F, const REQ_BUF: usize, const REPLY_BUF: usize>(
10036        &mut self,
10037        service_name: &str,
10038        callback: F,
10039    ) -> Result<HandleId, NodeError>
10040    where
10041        Svc: RosService + 'static,
10042        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10043        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10044        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
10045    {
10046        type Entry<Svc, F, const RQ: usize, const RP: usize> = SrvEntry<Svc, F, RQ, RP>;
10047
10048        // Phase 212.K.7.7.b — register both halves of the service round-trip
10049        // under cyclonedds. No-op for other RMWs. Mirrors the K.7.6.b hook
10050        // on `Node::create_service_sized`.
10051        crate::rmw_type_registry::register_type::<Svc::Request>()?;
10052        crate::rmw_type_registry::register_type::<Svc::Reply>()?;
10053
10054        let slot = self.next_entry_slot()?;
10055        // RFC-0128 D8 -- an executor-level service belongs to the primary
10056        // node, on that node's session, never to the executor's label.
10057        let (node_name, ns, session_idx) = self.entity_identity(None)?;
10058        let mut info = ServiceInfo::new(service_name, Svc::SERVICE_NAME, Svc::SERVICE_HASH)
10059            .with_domain(self.domain_id)
10060            .with_namespace(&ns);
10061        if !node_name.is_empty() {
10062            info = info.with_node_name(&node_name);
10063        }
10064        let handle = self
10065            .session_at_mut(session_idx)
10066            .ok_or(NodeError::BackendMismatch)?
10067            .create_service(&info, QoSProfile::services_default())
10068            .map_err(NodeError::Transport)?;
10069
10070        let offset = self.arena_alloc::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>()?;
10071
10072        // SAFETY: same guarantees as register_subscription_sized.
10073        unsafe {
10074            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10075            let entry_ptr = arena_ptr.add(offset) as *mut Entry<Svc, F, REQ_BUF, REPLY_BUF>;
10076            core::ptr::write(
10077                entry_ptr,
10078                Entry {
10079                    handle,
10080                    req_buffer: [0u8; REQ_BUF],
10081                    reply_buffer: [0u8; REPLY_BUF],
10082                    callback,
10083                    _phantom: PhantomData,
10084                },
10085            );
10086        }
10087
10088        let meta = CallbackMeta {
10089            offset,
10090            kind: EntryKind::Service,
10091            arena_len: super::arena::ArenaLen::UNRECORDED,
10092            try_process: srv_try_process::<Svc, F, REQ_BUF, REPLY_BUF>,
10093            has_data: srv_has_data::<Svc, F, REQ_BUF, REPLY_BUF>,
10094            pre_sample: no_pre_sample,
10095            invocation: InvocationMode::OnNewData,
10096            drop_fn: drop_entry::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>,
10097        };
10098        self.emplace_entry(slot, meta, TraceName::Text(service_name));
10099        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
10100        // SAFETY: a `Entry<Svc, F, REQ_BUF, REPLY_BUF>` was written at `offset` just above.
10101        unsafe {
10102            self.arm_entry_wake::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>(slot, offset, |e, w| {
10103                nros_rmw::ServiceTrait::register_waker(&e.handle, w)
10104            })
10105        };
10106        Ok(self.handle_for(slot))
10107    }
10108
10109    /// Node-aware variant of
10110    /// [`register_service_sized`](Self::register_service_sized).
10111    pub fn register_service_sized_on<Svc, F, const REQ_BUF: usize, const REPLY_BUF: usize>(
10112        &mut self,
10113        node_id: super::node_record::NodeId,
10114        service_name: &str,
10115        qos: QoSProfile,
10116        callback: F,
10117    ) -> Result<HandleId, NodeError>
10118    where
10119        Svc: RosService + 'static,
10120        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10121        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10122        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
10123    {
10124        self.register_service_sized_on_inner::<Svc, F, REQ_BUF, REPLY_BUF>(
10125            node_id,
10126            service_name,
10127            qos,
10128            callback,
10129            srv_try_process::<Svc, F, REQ_BUF, REPLY_BUF>,
10130        )
10131    }
10132
10133    /// [`register_service_sized_on`](Self::register_service_sized_on)
10134    /// for a callback that also receives the request's
10135    /// [`ServiceInfo`](nros_core::ServiceInfo) — rclrs's `(request, ServiceInfo)`
10136    /// service callback. A field the backend cannot report arrives as `None`.
10137    pub fn register_service_with_info_sized_on<
10138        Svc,
10139        F,
10140        const REQ_BUF: usize,
10141        const REPLY_BUF: usize,
10142    >(
10143        &mut self,
10144        node_id: super::node_record::NodeId,
10145        service_name: &str,
10146        qos: QoSProfile,
10147        callback: F,
10148    ) -> Result<HandleId, NodeError>
10149    where
10150        Svc: RosService + 'static,
10151        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10152        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10153        F: FnMut(&Svc::Request, &nros_core::ServiceInfo) -> Svc::Reply + 'static,
10154    {
10155        self.register_service_sized_on_inner::<Svc, F, REQ_BUF, REPLY_BUF>(
10156            node_id,
10157            service_name,
10158            qos,
10159            callback,
10160            srv_try_process_with_info::<Svc, F, REQ_BUF, REPLY_BUF>,
10161        )
10162    }
10163
10164    /// The one body behind both callback shapes: they share [`SrvEntry`] and
10165    /// differ only in the dispatch function.
10166    fn register_service_sized_on_inner<Svc, F, const REQ_BUF: usize, const REPLY_BUF: usize>(
10167        &mut self,
10168        node_id: super::node_record::NodeId,
10169        service_name: &str,
10170        qos: QoSProfile,
10171        callback: F,
10172        try_process: unsafe fn(*mut u8, u64, u8) -> Result<bool, TransportError>,
10173    ) -> Result<HandleId, NodeError>
10174    where
10175        Svc: RosService + 'static,
10176        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10177        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10178        F: 'static,
10179    {
10180        type Entry<Svc, F, const RQ: usize, const RP: usize> = SrvEntry<Svc, F, RQ, RP>;
10181
10182        // Phase 212.K.7.7.b — see `register_service_sized`.
10183        crate::rmw_type_registry::register_type::<Svc::Request>()?;
10184        crate::rmw_type_registry::register_type::<Svc::Reply>()?;
10185
10186        let slot = self.next_entry_slot()?;
10187        let (node_name, ns, session_idx) = {
10188            let r = self
10189                .nodes
10190                .get(node_id.index())
10191                .ok_or(NodeError::InvalidSchedContextBinding)?;
10192            (r.name.clone(), r.namespace.clone(), r.session_idx)
10193        };
10194        let mut info = ServiceInfo::new(service_name, Svc::SERVICE_NAME, Svc::SERVICE_HASH)
10195            .with_domain(self.domain_id)
10196            .with_namespace(&ns);
10197        if !node_name.is_empty() {
10198            info = info.with_node_name(&node_name);
10199        }
10200        let handle = {
10201            let session = self
10202                .session_at_mut(session_idx)
10203                .ok_or(NodeError::BackendMismatch)?;
10204            // Phase 193.5 — validate against the backend's supported policies
10205            // (no silent downgrade); request/reply effectively requires RELIABLE.
10206            super::node::validate_qos_or_report(
10207                &qos,
10208                session.supported_qos_policies(),
10209                "service",
10210                service_name,
10211            )?;
10212            session
10213                .create_service(&info, qos)
10214                .map_err(NodeError::Transport)?
10215        };
10216
10217        let offset = self.arena_alloc::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>()?;
10218        unsafe {
10219            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10220            let entry_ptr = arena_ptr.add(offset) as *mut Entry<Svc, F, REQ_BUF, REPLY_BUF>;
10221            core::ptr::write(
10222                entry_ptr,
10223                Entry {
10224                    handle,
10225                    req_buffer: [0u8; REQ_BUF],
10226                    reply_buffer: [0u8; REPLY_BUF],
10227                    callback,
10228                    _phantom: PhantomData,
10229                },
10230            );
10231        }
10232
10233        let meta = CallbackMeta {
10234            offset,
10235            kind: EntryKind::Service,
10236            arena_len: super::arena::ArenaLen::UNRECORDED,
10237            try_process,
10238            has_data: srv_has_data::<Svc, F, REQ_BUF, REPLY_BUF>,
10239            pre_sample: no_pre_sample,
10240            invocation: InvocationMode::OnNewData,
10241            drop_fn: drop_entry::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>,
10242        };
10243        self.emplace_entry(slot, meta, TraceName::Text(service_name));
10244        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
10245        // SAFETY: a `Entry<Svc, F, REQ_BUF, REPLY_BUF>` was written at `offset` just above.
10246        unsafe {
10247            self.arm_entry_wake::<Entry<Svc, F, REQ_BUF, REPLY_BUF>>(slot, offset, |e, w| {
10248                nros_rmw::ServiceTrait::register_waker(&e.handle, w)
10249            })
10250        };
10251        self.apply_node_default_sched(slot, Some(node_id), None);
10252        Ok(self.handle_for(slot))
10253    }
10254
10255    /// Node-aware variant of
10256    /// [`register_service`](Self::register_service).
10257    pub fn register_service_on<Svc, F>(
10258        &mut self,
10259        node_id: super::node_record::NodeId,
10260        service_name: &str,
10261        callback: F,
10262    ) -> Result<HandleId, NodeError>
10263    where
10264        Svc: RosService + 'static,
10265        Svc::Request: crate::rmw_type_registry::MessageForRmw,
10266        Svc::Reply: crate::rmw_type_registry::MessageForRmw,
10267        F: FnMut(&Svc::Request) -> Svc::Reply + 'static,
10268    {
10269        self.register_service_sized_on::<
10270            Svc,
10271            F,
10272            { crate::config::DEFAULT_RX_BUF_SIZE },
10273            { crate::config::DEFAULT_RX_BUF_SIZE },
10274        >(node_id, service_name, QoSProfile::services_default(), callback)
10275    }
10276
10277    // ========================================================================
10278    // Timer registration
10279    // ========================================================================
10280
10281    /// The ONE timer registration in the tree (phase-430 W4).
10282    ///
10283    /// Every timer verb — the four `Executor::register_timer*` entry points
10284    /// below, `Node::create_timer_in_group` / `create_timer_on_clock*`, the
10285    /// declarative `nros::Node` timer, and the C/C++ FFI that lower to them —
10286    /// constructs its arena entry HERE. Until W4 there were four copies of this
10287    /// body differing only in `oneshot`, `clock_source` and whether the sched
10288    /// binding was applied, and phase-425's clock axis reached exactly one of
10289    /// them; that is how a `nros::main!` component could declare a timer but
10290    /// not a ROS-time one.
10291    ///
10292    /// `node_id` / `group` feed `apply_node_default_sched` (phase 273: group
10293    /// table > node default > SC 0). `node_id == None` is the legacy unscoped
10294    /// path and makes that call a no-op.
10295    pub(crate) fn register_timer_entry<F>(
10296        &mut self,
10297        node_id: Option<super::node_record::NodeId>,
10298        period: TimerDuration,
10299        source: TimerClockSource,
10300        oneshot: bool,
10301        group: Option<&str>,
10302        callback: F,
10303    ) -> Result<HandleId, NodeError>
10304    where
10305        F: FnMut() + 'static,
10306    {
10307        let mut callback = callback;
10308        self.register_timer_entry_with(
10309            node_id,
10310            period,
10311            source,
10312            oneshot,
10313            true,
10314            group,
10315            None,
10316            core::ptr::null_mut(),
10317            move |_| move |_: &TimerCallInfo| callback(),
10318        )
10319    }
10320
10321    /// [`register_timer_entry`](Self::register_timer_entry), with a CAPTURE
10322    /// the arena holds — phase-476 W2.
10323    ///
10324    /// The callback is BUILT after the allocation, by `make`, from the context
10325    /// pointer the entry should dispatch with: `place_capture`'s copy of
10326    /// `capture` when there is one, otherwise `context` unchanged. That is what
10327    /// lets the capture ride in the timer entry's own trailing region (so a
10328    /// release frees it) while the closure that reads it is still a plain
10329    /// `TimerEntry<F>`.
10330    ///
10331    /// Issue 1974 — the stored callback takes the dispatcher's
10332    /// [`TimerCallInfo`]; a plain `FnMut()` is adapted by ignoring it, so there
10333    /// is one entry type and one dispatch whichever flavour the caller wrote.
10334    /// `autostart == false` builds the entry CANCELLED (rcl's
10335    /// `rcl_timer_init2(..., autostart = false)`): it never fires until
10336    /// [`reset_timer`](Self::reset_timer) starts it.
10337    #[allow(clippy::too_many_arguments)]
10338    pub(crate) fn register_timer_entry_with<F, M>(
10339        &mut self,
10340        node_id: Option<super::node_record::NodeId>,
10341        period: TimerDuration,
10342        source: TimerClockSource,
10343        oneshot: bool,
10344        autostart: bool,
10345        group: Option<&str>,
10346        capture: Option<&[u8]>,
10347        context: *mut core::ffi::c_void,
10348        make: M,
10349    ) -> Result<HandleId, NodeError>
10350    where
10351        F: FnMut(&TimerCallInfo) + 'static,
10352        M: FnOnce(*mut core::ffi::c_void) -> F,
10353    {
10354        let slot = self.next_entry_slot()?;
10355        let capture_len = Self::capture_trailing_len(capture);
10356        // No capture keeps the exact pre-W2 allocation, so a timer that captures
10357        // nothing costs what it always did.
10358        let (offset, context) = if capture_len == 0 {
10359            (self.arena_alloc::<TimerEntry<F>>()?, context)
10360        } else {
10361            let (offset, at) = self.arena_alloc_with_trailing::<TimerEntry<F>>(capture_len)?;
10362            (offset, self.place_capture(at, capture, context))
10363        };
10364        let callback = make(context);
10365
10366        unsafe {
10367            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10368            let entry_ptr = arena_ptr.add(offset) as *mut TimerEntry<F>;
10369            core::ptr::write(
10370                entry_ptr,
10371                TimerEntry {
10372                    period_us: period.as_micros(),
10373                    elapsed_us: 0,
10374                    overruns: 0,
10375                    overruns_reported: 0,
10376                    oneshot,
10377                    fired: false,
10378                    cancelled: !autostart,
10379                    overrun_policy: TimerOverrunPolicy::default(),
10380                    clock_source: source,
10381                    // Seeded HERE rather than on the first poll: a zero would
10382                    // make the first delta the whole epoch, which `Skip` would
10383                    // then coalesce into one immediate activation and `CatchUp`
10384                    // into a replay burst of ~10^9 periods. `Steady` reads no
10385                    // clock at all, so its seed is 0 and is never read.
10386                    last_clock_ns: source.now_ns(),
10387                    callback,
10388                },
10389            );
10390        }
10391
10392        let meta = CallbackMeta {
10393            offset,
10394            kind: EntryKind::Timer,
10395            arena_len: super::arena::ArenaLen::UNRECORDED,
10396            try_process: timer_try_process::<F>,
10397            has_data: always_ready,
10398            pre_sample: no_pre_sample,
10399            invocation: InvocationMode::Always,
10400            drop_fn: drop_entry::<TimerEntry<F>>,
10401        };
10402        self.emplace_entry(slot, meta, TraceName::TimerPeriod(period.as_micros()));
10403        // Phase 273 — apply group sched binding (group > node default > SC 0).
10404        self.apply_node_default_sched(slot, node_id, group);
10405        Ok(self.handle_for(slot))
10406    }
10407
10408    /// Register a repeating timer callback.
10409    ///
10410    /// The callback fires every `period` milliseconds during [`spin_once()`](Self::spin_once).
10411    /// The timer delta is approximated by the `timeout_ms` argument to `spin_once`.
10412    pub fn register_timer<F>(
10413        &mut self,
10414        period: TimerDuration,
10415        callback: F,
10416    ) -> Result<HandleId, NodeError>
10417    where
10418        F: FnMut() + 'static,
10419    {
10420        self.register_timer_entry(
10421            None,
10422            period,
10423            TimerClockSource::Steady,
10424            false,
10425            None,
10426            callback,
10427        )
10428    }
10429
10430    /// Register a repeating timer driven by a CLOCK rather than by the spin
10431    /// delta — the shape rclcpp spells
10432    /// `create_timer(node, clock, period, cb)`.
10433    ///
10434    /// [`register_timer`](Self::register_timer) is the wall timer: it consumes
10435    /// the executor's monotonic spin delta and no simulator can slow it down.
10436    /// This one reads `source` on every poll and advances by the difference, so
10437    /// a [`TimerClockSource::Ros`] timer follows `/clock` — it stops while the
10438    /// simulator is paused, halves with a bag replayed at 0.5x, and restarts
10439    /// its period on a backwards jump instead of stalling for the length of it.
10440    ///
10441    /// With no `/clock` source installed, a `Ros` timer reads system time and
10442    /// behaves like a wall timer with NTP steps, which is the same fallback
10443    /// `rclcpp::Clock` has: a node written for simulation still runs standalone.
10444    ///
10445    /// The node-level spellings of this are `Node::create_timer_on_clock`
10446    /// and the declarative `DeclaredNode::create_timer_on_clock`;
10447    /// all of them reach `register_timer_entry`, which is the only place a
10448    /// timer entry is built.
10449    pub fn register_timer_on_clock<F>(
10450        &mut self,
10451        period: TimerDuration,
10452        source: TimerClockSource,
10453        callback: F,
10454    ) -> Result<HandleId, NodeError>
10455    where
10456        F: FnMut() + 'static,
10457    {
10458        self.register_timer_entry(None, period, source, false, None, callback)
10459    }
10460
10461    /// Register a one-shot timer callback.
10462    ///
10463    /// The callback fires once after `delay` milliseconds, then becomes inert.
10464    pub fn register_timer_oneshot<F>(
10465        &mut self,
10466        delay: TimerDuration,
10467        callback: F,
10468    ) -> Result<HandleId, NodeError>
10469    where
10470        F: FnMut() + 'static,
10471    {
10472        self.register_timer_entry(None, delay, TimerClockSource::Steady, true, None, callback)
10473    }
10474
10475    /// phase-476 W2 — register a timer whose callback is a C function pointer
10476    /// and whose CAPTURE the arena holds: the `nros-cpp` road for a C++
10477    /// lambda, the timer twin of
10478    /// [`add_arena_subscription_c_callback_with_capture`](Self::add_arena_subscription_c_callback_with_capture).
10479    ///
10480    /// `capture`'s bytes are copied into the timer entry's trailing region and
10481    /// `callback` is called with a pointer to that copy, so the caller keeps
10482    /// nothing — which is what lets the C++ side hand back a two-word handle
10483    /// instead of a heap cell the node had to keep alive. Releasing the timer
10484    /// releases the capture with it.
10485    ///
10486    /// `source` picks the clock: [`TimerClockSource::Steady`] is the wall timer
10487    /// that advances with the spin delta.
10488    ///
10489    /// `capture_drop`, when given, is called with the same pointer when the
10490    /// entry is dropped (released, or the executor torn down), BEFORE its bytes
10491    /// go back to the arena. A C++ capture is a callable that may own something
10492    /// (a `std::shared_ptr`, a `std::string`), and its bytes were MOVED here by
10493    /// copy, so this is the only place its destructor can run.
10494    pub(crate) fn register_timer_c_capturing(
10495        &mut self,
10496        node_id: Option<super::node_record::NodeId>,
10497        period: TimerDuration,
10498        source: TimerClockSource,
10499        callback: unsafe extern "C" fn(*mut core::ffi::c_void),
10500        capture: Option<&[u8]>,
10501        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
10502    ) -> Result<HandleId, NodeError> {
10503        self.register_timer_entry_with(
10504            node_id,
10505            period,
10506            source,
10507            false,
10508            true,
10509            None,
10510            capture,
10511            core::ptr::null_mut(),
10512            move |ctx| {
10513                let held = super::arena::CapturedCallback {
10514                    callback,
10515                    guard: super::arena::CaptureGuard {
10516                        ctx,
10517                        drop: capture_drop,
10518                    },
10519                };
10520                move |_: &TimerCallInfo| held.call()
10521            },
10522        )
10523    }
10524
10525    /// [`register_timer_c_capturing`](Self::register_timer_c_capturing) with
10526    /// the dispatcher's [`TimerCallInfo`] handed to the C callback, a callback
10527    /// group, and rcl's `autostart` — issue 1974, the road a C++
10528    /// `TimerInfoCallbackType` lambda and `create_wall_timer(..., autostart)`
10529    /// take.
10530    ///
10531    /// `I` is the FFI's own `#[repr(C)]` mirror of the info struct (the C++
10532    /// header is generated without includes, so it cannot name this crate's
10533    /// type); it is built from the executor's `TimerCallInfo` by `From` on each
10534    /// activation — a copy of two words, never a second computation.
10535    ///
10536    /// `autostart == false` registers the timer cancelled; `reset_timer`
10537    /// starts it. `group` binds it as `register_timer_on` does.
10538    #[allow(clippy::too_many_arguments)]
10539    pub(crate) fn register_timer_c_capturing_with_info<I>(
10540        &mut self,
10541        node_id: Option<super::node_record::NodeId>,
10542        period: TimerDuration,
10543        source: TimerClockSource,
10544        autostart: bool,
10545        group: Option<&str>,
10546        callback: unsafe extern "C" fn(*const I, *mut core::ffi::c_void),
10547        capture: Option<&[u8]>,
10548        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
10549    ) -> Result<HandleId, NodeError>
10550    where
10551        I: From<TimerCallInfo> + 'static,
10552    {
10553        self.register_timer_entry_with(
10554            node_id,
10555            period,
10556            source,
10557            false,
10558            autostart,
10559            group,
10560            capture,
10561            core::ptr::null_mut(),
10562            move |ctx| {
10563                let guard = super::arena::CaptureGuard {
10564                    ctx,
10565                    drop: capture_drop,
10566                };
10567                move |info: &TimerCallInfo| {
10568                    // Borrow the WHOLE guard: a closure naming only `guard.ctx`
10569                    // would capture that `Copy` field alone and let the guard
10570                    // (whose `Drop` runs the capture's destructor) die here.
10571                    let guard = &guard;
10572                    let ffi_info = I::from(*info);
10573                    // SAFETY: the registrant's contract — `callback` reads its
10574                    // capture through the pointer it is given, and the info
10575                    // pointer is valid for the duration of the call.
10576                    unsafe { callback(&ffi_info, guard.ctx) }
10577                }
10578            },
10579        )
10580    }
10581
10582    /// Register a repeating timer whose callback receives the dispatcher's
10583    /// [`TimerCallInfo`] — the Rust counterpart of Jazzy's
10584    /// `rclcpp::TimerInfoCallbackType` / `rcl_timer_call_info_t`.
10585    ///
10586    /// `source` picks the clock both the period and the two call times are
10587    /// measured on. `autostart == false` creates the timer CANCELLED (rcl's
10588    /// `rcl_timer_init2(..., autostart)`): it does not fire until
10589    /// [`reset_timer`](Self::reset_timer) starts it, and its first period
10590    /// counts from that reset.
10591    ///
10592    /// ```ignore
10593    /// executor.register_timer_with_info(
10594    ///     TimerDuration::from_millis(10),
10595    ///     TimerClockSource::Steady,
10596    ///     true,
10597    ///     |info| jitter.record(info.lateness_ns()),
10598    /// )?;
10599    /// ```
10600    pub fn register_timer_with_info<F>(
10601        &mut self,
10602        period: TimerDuration,
10603        source: TimerClockSource,
10604        autostart: bool,
10605        callback: F,
10606    ) -> Result<HandleId, NodeError>
10607    where
10608        F: FnMut(&TimerCallInfo) + 'static,
10609    {
10610        self.register_timer_with_info_on(None, period, source, autostart, None, callback)
10611    }
10612
10613    /// [`register_timer_with_info`](Self::register_timer_with_info) bound to a
10614    /// node and an optional callback group — the executor primitive behind
10615    /// `Node::create_timer_with_info` and the C `rcl_timer_init2` / `rclc_timer_init_default2` /
10616    /// `rclc_timer_init_with_info` timers. `node_id`/`group` feed
10617    /// the sched binding exactly as [`register_timer_on`](Self::register_timer_on).
10618    pub fn register_timer_with_info_on<F>(
10619        &mut self,
10620        node_id: Option<super::node_record::NodeId>,
10621        period: TimerDuration,
10622        source: TimerClockSource,
10623        autostart: bool,
10624        group: Option<&str>,
10625        callback: F,
10626    ) -> Result<HandleId, NodeError>
10627    where
10628        F: FnMut(&TimerCallInfo) + 'static,
10629    {
10630        self.register_timer_entry_with(
10631            node_id,
10632            period,
10633            source,
10634            false,
10635            autostart,
10636            group,
10637            None,
10638            core::ptr::null_mut(),
10639            move |_| callback,
10640        )
10641    }
10642
10643    /// Register a repeating timer callback bound to a
10644    /// specific node and optional callback group. The group name is threaded to
10645    /// `apply_node_default_sched` so the seeded `group_sched_table` assigns
10646    /// the timer's callback to the group's `SchedContext`. When `group` is
10647    /// `None` the node's `default_sched` applies.
10648    ///
10649    /// This is the executor-level primitive called by the Rust `_in_group` API
10650    /// (`Node::create_timer_in_group`) and the C/C++ group-aware timer FFI.
10651    pub fn register_timer_on<F>(
10652        &mut self,
10653        node_id: Option<super::node_record::NodeId>,
10654        period: TimerDuration,
10655        callback: F,
10656        group: Option<&str>,
10657    ) -> Result<HandleId, NodeError>
10658    where
10659        F: FnMut() + 'static,
10660    {
10661        self.register_timer_entry(
10662            node_id,
10663            period,
10664            TimerClockSource::Steady,
10665            false,
10666            group,
10667            callback,
10668        )
10669    }
10670
10671    // ========================================================================
10672    // Raw callback registration (for C API)
10673    // ========================================================================
10674
10675    /// The kept C-FFI subscription core (Phase 189.M2.b): registers a
10676    /// raw `RawSubscriptionCallback` fn-ptr + `context` against an
10677    /// optional node's session. The Rust ergonomic surface is the
10678    /// `node.subscription(t)` builder (closures); this is the single
10679    /// primitive the `nros-c` thin wrapper lowers to. `node_id == None`
10680    /// is the legacy single-node path.
10681    #[allow(clippy::too_many_arguments)]
10682    pub(crate) fn add_arena_subscription_c_callback<const RX_BUF: usize>(
10683        &mut self,
10684        node_id: Option<super::node_record::NodeId>,
10685        topic_name: &str,
10686        type_name: &str,
10687        type_hash: &str,
10688        qos: QoSProfile,
10689        callback: RawSubscriptionCallback,
10690        context: *mut core::ffi::c_void,
10691        group: Option<&str>,
10692        rx_buffer_hint: usize,
10693    ) -> Result<HandleId, NodeError> {
10694        self.add_arena_subscription_c_callback_with_capture::<RX_BUF>(
10695            node_id,
10696            topic_name,
10697            type_name,
10698            type_hash,
10699            qos,
10700            callback,
10701            context,
10702            group,
10703            rx_buffer_hint,
10704            None,
10705            None,
10706        )
10707    }
10708
10709    /// The same registration, with the caller's CAPTURE held by the arena —
10710    /// phase-456 W1.
10711    ///
10712    /// `context` is one pointer, which carries a C++ `[this]` capture and not a
10713    /// `[this, state]` or a `[obj, method]`. When `capture` is `Some`, its
10714    /// bytes are copied into the arena and `context` is repointed at that copy,
10715    /// so the caller keeps nothing and nothing the caller owns is referenced
10716    /// after this returns. When it is `None` the behaviour is exactly the
10717    /// pre-existing one, which is why the plain entry point above is a wrapper
10718    /// rather than a second implementation.
10719    ///
10720    /// **phase-456 W8 changed two things here.** The capture is a RUNTIME
10721    /// length — see `Self::place_capture` — so there is no constant the C++
10722    /// side has to match and no `BufferTooSmall` reachable only by drifting
10723    /// from it. And this path now reaches the in-place dispatch that the Rust
10724    /// typed path has had since phase-231: `RawSubscriptionCallback` is
10725    /// `(const uint8_t*, size_t, void*)`, so the backend's borrowed receive
10726    /// slot IS the argument, and a C or C++ subscription on zenoh or XRCE
10727    /// claims no receive region at all.
10728    #[allow(clippy::too_many_arguments)]
10729    pub(crate) fn add_arena_subscription_c_callback_with_capture<const RX_BUF: usize>(
10730        &mut self,
10731        node_id: Option<super::node_record::NodeId>,
10732        topic_name: &str,
10733        type_name: &str,
10734        type_hash: &str,
10735        qos: QoSProfile,
10736        callback: RawSubscriptionCallback,
10737        context: *mut core::ffi::c_void,
10738        group: Option<&str>,
10739        // phase-402 W2 / issue 0896 — bytes the caller expects to receive; 0 =
10740        // no opinion. A size-classing backend (zenoh-pico) routes on this, and
10741        // a subscription that states nothing takes the SMALL class whatever its
10742        // message type. The C path had no way to say it until the options
10743        // struct existed.
10744        rx_buffer_hint: usize,
10745        capture: Option<&[u8]>,
10746        // phase-476 W2 — called on the arena's copy of `capture` when the entry
10747        // is dropped; see `CaptureGuard`. `None` when the capture owns nothing.
10748        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
10749    ) -> Result<HandleId, NodeError> {
10750        // phase-403 W3/W5 -- size the arena slot from the TYPE, not from the
10751        // image-wide default. `rx_buffer_hint` already arrives here (phase-402
10752        // routed it to the backend's payload class and stopped); spending it on
10753        // the allocation as well is what makes the buffer per-type.
10754        //
10755        // This is the whole saving on the raw path. `RX_BUF` is
10756        // DEFAULT_RX_BUF_SIZE, so every slot -- publishers and timers included --
10757        // was charged the largest subscription's buffer. Measured on
10758        // mr-canhubk344: 36 handles at the correct 2052-byte bound wanted a
10759        // 242096-byte arena of a 77968-byte region; only 13 of those handles
10760        // receive anything.
10761        //
10762        // 0 keeps the old behaviour, and it means "this CALLER stated nothing"
10763        // rather than "this type is unbounded" -- an unbounded type is a build
10764        // error now, so a zero here is a caller that did not ask, never a type
10765        // that could not answer.
10766        let slot_bytes = if rx_buffer_hint != 0 {
10767            rx_buffer_hint
10768        } else {
10769            RX_BUF
10770        };
10771
10772        let SubscriptionOpen {
10773            slot,
10774            handle,
10775            qos,
10776            in_place,
10777            slot_bytes,
10778        } = self.open_subscription(&SubscriptionRequest {
10779            node_id,
10780            topic_name,
10781            type_name,
10782            type_hash,
10783            qos,
10784            backend_hint: Some(rx_buffer_hint),
10785            slot_bytes,
10786            // phase-456 W8 — `RawSubscriptionCallback` takes borrowed bytes and
10787            // a context, which is exactly what `process_raw_in_place` hands it.
10788            in_place_capable: true,
10789        })?;
10790
10791        // The capture is placed AFTER the backend call and BEFORE either entry
10792        // is written, so both dispatch shapes get the same context and a failed
10793        // `create_subscription` costs no arena bytes. phase-476 W0 — it rides
10794        // at the end of the entry's own trailing region, so releasing the entry
10795        // gives it back.
10796        let capture_len = Self::capture_trailing_len(capture);
10797
10798        if in_place {
10799            let (entry_offset, capture_at) =
10800                self.arena_alloc_with_trailing::<super::arena::SubInplaceRawCEntry>(capture_len)?;
10801            let context = self.place_capture(capture_at, capture, context);
10802            unsafe {
10803                let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10804                let entry_ptr =
10805                    arena_ptr.add(entry_offset) as *mut super::arena::SubInplaceRawCEntry;
10806                core::ptr::write(
10807                    entry_ptr,
10808                    super::arena::SubInplaceRawCEntry {
10809                        handle,
10810                        callback,
10811                        context,
10812                        capture: super::arena::CaptureGuard {
10813                            ctx: context,
10814                            drop: capture_drop,
10815                        },
10816                        age_mon: None,
10817                    },
10818                );
10819            }
10820            let meta = CallbackMeta {
10821                offset: entry_offset,
10822                kind: EntryKind::Subscription,
10823                arena_len: super::arena::ArenaLen::UNRECORDED,
10824                try_process: super::arena::sub_inplace_raw_c_try_process,
10825                has_data: super::arena::sub_inplace_raw_c_has_data,
10826                pre_sample: no_pre_sample,
10827                invocation: InvocationMode::OnNewData,
10828                drop_fn: drop_entry::<super::arena::SubInplaceRawCEntry>,
10829            };
10830            self.emplace_entry(slot, meta, TraceName::Text(topic_name));
10831            // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
10832            // SAFETY: a `super::arena::SubInplaceRawCEntry` was written at `entry_offset` just above.
10833            unsafe {
10834                self.arm_entry_wake::<super::arena::SubInplaceRawCEntry>(
10835                    slot,
10836                    entry_offset,
10837                    |e, w| nros_rmw::Subscription::register_waker(&e.handle, w),
10838                )
10839            };
10840            self.apply_node_default_sched(slot, node_id, group);
10841            return Ok(self.handle_for(slot));
10842        }
10843
10844        let (_slot_count, trailing_bytes) = buffered_region_size(qos.depth, slot_bytes);
10845
10846        // The ring first, then the capture on the next `u64` boundary after it.
10847        let ring_len = trailing_bytes.next_multiple_of(core::mem::align_of::<u64>());
10848        let (entry_offset, trailing_offset) =
10849            self.arena_alloc_with_trailing::<SubBufferedRawCEntry>(ring_len + capture_len)?;
10850        let context = self.place_capture(trailing_offset + ring_len, capture, context);
10851
10852        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
10853
10854        let buffer = if qos.depth <= 1 {
10855            BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, slot_bytes) })
10856        } else {
10857            BufferStrategy::Ring(unsafe { SpscRing::init(buf_ptr, slot_bytes, qos.depth as usize) })
10858        };
10859
10860        unsafe {
10861            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10862            let entry_ptr = arena_ptr.add(entry_offset) as *mut SubBufferedRawCEntry;
10863            core::ptr::write(
10864                entry_ptr,
10865                SubBufferedRawCEntry {
10866                    handle,
10867                    buffer,
10868                    callback,
10869                    context,
10870                    capture: super::arena::CaptureGuard {
10871                        ctx: context,
10872                        drop: capture_drop,
10873                    },
10874                    age_mon: None,
10875                },
10876            );
10877        }
10878
10879        let meta = CallbackMeta {
10880            offset: entry_offset,
10881            kind: EntryKind::Subscription,
10882            arena_len: super::arena::ArenaLen::UNRECORDED,
10883            try_process: sub_buffered_raw_c_try_process,
10884            has_data: sub_buffered_raw_c_has_data,
10885            pre_sample: no_pre_sample,
10886            invocation: InvocationMode::OnNewData,
10887            drop_fn: drop_entry::<SubBufferedRawCEntry>,
10888        };
10889        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
10890        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
10891        // SAFETY: a `SubBufferedRawCEntry` was written at `entry_offset` just above.
10892        unsafe {
10893            self.arm_entry_wake::<SubBufferedRawCEntry>(slot, entry_offset, |e, w| {
10894                nros_rmw::Subscription::register_waker(&e.handle, w)
10895            })
10896        };
10897        self.apply_node_default_sched(slot, node_id, group);
10898        Ok(self.handle_for(slot))
10899    }
10900
10901    /// phase-417 W5.a (RFC-0089 stage 5) — the TYPED C-FFI subscription core:
10902    /// the same registration as [`Self::add_arena_subscription_c_callback`],
10903    /// plus caller-owned message storage and the erased deserialiser for its
10904    /// type, so the callback receives a DESERIALISED message instead of CDR
10905    /// bytes.
10906    ///
10907    /// This is the Rust half of rclc's
10908    /// `rclc_executor_add_subscription(executor, subscription, msg, callback,
10909    /// invocation)`. rclc has no allocator on that path either — it makes the
10910    /// CALLER own the storage, which is exactly what `msg` is here. The C
10911    /// ledger recorded our byte-oriented delivery as forced by "no allocator";
10912    /// the compared surface operates under the same constraint, so the reason
10913    /// was false and the divergence was avoidable (issue 1022 / W-C3).
10914    ///
10915    /// The raw path is untouched and stays: a byte-oriented subscriber is a
10916    /// legitimate thing to want, and this is additive.
10917    ///
10918    /// # Contract on failure
10919    /// If `deserialize` returns non-zero the callback is **not** invoked, the
10920    /// sample is dropped, `try_process` reports
10921    /// `TransportError::DeserializationError` (so it lands in
10922    /// `SpinOnceResult::subscription_errors`), and a rate-limited `nros_log`
10923    /// error names the length and the return code. A message that does not fit
10924    /// the caller's storage arrives here as exactly that failure: both the
10925    /// bounded-string and bounded-sequence decoders refuse rather than
10926    /// truncate, so there is no silent short read.
10927    ///
10928    /// # Safety
10929    /// `msg` must point to storage of the type `deserialize` writes, valid for
10930    /// as long as the subscription is registered. Nothing here drops it.
10931    #[allow(clippy::too_many_arguments)]
10932    pub(crate) unsafe fn add_arena_subscription_c_typed_callback<const RX_BUF: usize>(
10933        &mut self,
10934        node_id: Option<super::node_record::NodeId>,
10935        topic_name: &str,
10936        type_name: &str,
10937        type_hash: &str,
10938        qos: QoSProfile,
10939        msg: core::ptr::NonNull<core::ffi::c_void>,
10940        deserialize: RawMessageDeserializeFn,
10941        callback: TypedSubscriptionCallback,
10942        context: *mut core::ffi::c_void,
10943        group: Option<&str>,
10944        // Same meaning as on the raw path: bytes the caller expects to receive,
10945        // 0 = no opinion. A typed caller normally HAS an answer — the generated
10946        // `<Msg>_RX_MAX_SERIALIZED_SIZE` — which is why the C entry point takes
10947        // it rather than defaulting.
10948        rx_buffer_hint: usize,
10949    ) -> Result<HandleId, NodeError> {
10950        let SubscriptionOpen {
10951            slot,
10952            handle,
10953            qos,
10954            slot_bytes: rx_bytes,
10955            ..
10956        } = self.open_subscription(&SubscriptionRequest {
10957            node_id,
10958            topic_name,
10959            type_name,
10960            type_hash,
10961            qos,
10962            backend_hint: Some(rx_buffer_hint),
10963            // phase-403 W3/W5, unchanged: the hint sizes the arena slot, and 0
10964            // means "this caller stated nothing", never "this type is zero
10965            // bytes".
10966            slot_bytes: if rx_buffer_hint != 0 {
10967                rx_buffer_hint
10968            } else {
10969                RX_BUF
10970            },
10971            // The callback receives the caller's DESERIALISED storage, written
10972            // by `deserialize` from the sample's bytes, so borrowed bytes would
10973            // be enough and this shape could take the in-place row. It does not
10974            // yet: `SubBufferedTypedCEntry` also owns the `msg` pointer and the
10975            // deserialiser, so an in-place twin is a second entry type rather
10976            // than a flag, and phase-456 W8's acceptance is the RAW C path.
10977            // Stated here rather than left blank because a `false` nobody wrote
10978            // down is what this whole item is about.
10979            in_place_capable: false,
10980        })?;
10981
10982        let (_slot_count, trailing_bytes) = buffered_region_size(qos.depth, rx_bytes);
10983
10984        let (entry_offset, trailing_offset) =
10985            self.arena_alloc_with_trailing::<SubBufferedTypedCEntry>(trailing_bytes)?;
10986
10987        let buf_ptr = unsafe { (self.arena.as_mut_ptr() as *mut u8).add(trailing_offset) };
10988
10989        let buffer = if qos.depth <= 1 {
10990            BufferStrategy::Triple(unsafe { TripleBuffer::init(buf_ptr, rx_bytes) })
10991        } else {
10992            BufferStrategy::Ring(unsafe { SpscRing::init(buf_ptr, rx_bytes, qos.depth as usize) })
10993        };
10994
10995        unsafe {
10996            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
10997            let entry_ptr = arena_ptr.add(entry_offset) as *mut SubBufferedTypedCEntry;
10998            core::ptr::write(
10999                entry_ptr,
11000                SubBufferedTypedCEntry {
11001                    handle,
11002                    buffer,
11003                    msg: msg.as_ptr(),
11004                    deserialize,
11005                    callback,
11006                    context,
11007                },
11008            );
11009        }
11010
11011        let meta = CallbackMeta {
11012            offset: entry_offset,
11013            kind: EntryKind::Subscription,
11014            arena_len: super::arena::ArenaLen::UNRECORDED,
11015            try_process: sub_buffered_typed_c_try_process,
11016            has_data: sub_buffered_typed_c_has_data,
11017            pre_sample: no_pre_sample,
11018            invocation: InvocationMode::OnNewData,
11019            drop_fn: drop_entry::<SubBufferedTypedCEntry>,
11020        };
11021        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
11022        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11023        // SAFETY: a `SubBufferedTypedCEntry` was written at `entry_offset` just above.
11024        unsafe {
11025            self.arm_entry_wake::<SubBufferedTypedCEntry>(slot, entry_offset, |e, w| {
11026                nros_rmw::Subscription::register_waker(&e.handle, w)
11027            })
11028        };
11029        self.apply_node_default_sched(slot, node_id, group);
11030        Ok(self.handle_for(slot))
11031    }
11032
11033    /// Register a raw subscription whose closure receives each
11034    /// sample's [`MessageInfo`](nros_core::MessageInfo) (`None` from a backend
11035    /// that reports none): the raw twin of the typed `with_info` path, for a
11036    /// caller that deserializes itself. Backs the C++
11037    /// `(const M&, const rclcpp::MessageInfo&)` subscription callback
11038    /// (`nros_cpp_subscription_register_message_info`).
11039    ///
11040    /// `rx_buffer_hint` sizes both the backend's payload class and the arena
11041    /// slot, as on [`add_arena_subscription_c_info_callback`](crate::executor::ffi::ExecutorFfi::add_arena_subscription_c_info_callback);
11042    /// 0 falls back to `DEFAULT_RX_BUF_SIZE`.
11043    #[allow(clippy::too_many_arguments)]
11044    pub fn add_arena_subscription_msg_info_closure<F>(
11045        &mut self,
11046        node_id: Option<super::node_record::NodeId>,
11047        topic_name: &str,
11048        type_name: &str,
11049        type_hash: &str,
11050        qos: QoSProfile,
11051        rx_buffer_hint: usize,
11052        callback: F,
11053    ) -> Result<HandleId, NodeError>
11054    where
11055        F: FnMut(&[u8], Option<&nros_core::MessageInfo>) + 'static,
11056    {
11057        self.register_subscription_buffered_raw_msg_info_on(
11058            node_id,
11059            topic_name,
11060            type_name,
11061            type_hash,
11062            qos,
11063            rx_buffer_hint,
11064            core::ptr::null_mut(),
11065            None,
11066            move |_| callback,
11067        )
11068    }
11069
11070    // Issue 2717.
11071    /// The same registration with the caller's CAPTURE held by the arena:
11072    /// the metadata twin of
11073    /// `add_arena_subscription_c_callback_with_capture` (the plain C path).
11074    /// `capture`'s bytes are copied into the entry's region; `make` builds the
11075    /// callback from the context pointer it is to dispatch with (the arena
11076    /// copy, or `context` when there is none) and owns whatever releases the
11077    /// capture, so dropping the entry runs it once. Backs C++'s freestanding
11078    /// `(const M&, const rclcpp::MessageInfo&)` callback, which has no heap to
11079    /// own its callable.
11080    #[allow(clippy::too_many_arguments)]
11081    pub fn add_arena_subscription_msg_info_closure_with_capture<F>(
11082        &mut self,
11083        node_id: Option<super::node_record::NodeId>,
11084        topic_name: &str,
11085        type_name: &str,
11086        type_hash: &str,
11087        qos: QoSProfile,
11088        rx_buffer_hint: usize,
11089        context: *mut core::ffi::c_void,
11090        capture: Option<&[u8]>,
11091        make: impl FnOnce(*mut core::ffi::c_void) -> F,
11092    ) -> Result<HandleId, NodeError>
11093    where
11094        F: FnMut(&[u8], Option<&nros_core::MessageInfo>) + 'static,
11095    {
11096        self.register_subscription_buffered_raw_msg_info_on(
11097            node_id,
11098            topic_name,
11099            type_name,
11100            type_hash,
11101            qos,
11102            rx_buffer_hint,
11103            context,
11104            capture,
11105            make,
11106        )
11107    }
11108
11109    /// The one body behind
11110    /// [`add_arena_subscription_msg_info_closure`](Self::add_arena_subscription_msg_info_closure)
11111    /// (C++'s `(const M&, const rclcpp::MessageInfo&)` callback) and the
11112    /// declarative runtime's lowering for a component subscription that asked
11113    /// for `CallbackCtx::message_info` (issue 2349,
11114    /// `DeclaredSubscriptionShape::BufferedRawInfo`). One path, so the
11115    /// metadata a component reads is the metadata a C++ callback reads.
11116    ///
11117    /// `capture` (issue 2717) is the caller's callback CAPTURE, held by the
11118    /// arena as the plain C path holds it
11119    /// ([`add_arena_subscription_c_callback_with_capture`](Self::add_arena_subscription_c_callback_with_capture)):
11120    /// its bytes are copied to the entry's trailing region after the receive
11121    /// buffer, so releasing the entry gives them back and the caller keeps
11122    /// nothing. `make` builds the callback from the context pointer it is to
11123    /// dispatch with: the arena copy, or `context` when there is no capture.
11124    /// This is what lets a freestanding C++ build, with no allocator, register
11125    /// a metadata callback.
11126    #[allow(clippy::too_many_arguments)]
11127    pub(crate) fn register_subscription_buffered_raw_msg_info_on<F>(
11128        &mut self,
11129        node_id: Option<super::node_record::NodeId>,
11130        topic_name: &str,
11131        type_name: &str,
11132        type_hash: &str,
11133        qos: QoSProfile,
11134        rx_buffer_hint: usize,
11135        context: *mut core::ffi::c_void,
11136        capture: Option<&[u8]>,
11137        make: impl FnOnce(*mut core::ffi::c_void) -> F,
11138    ) -> Result<HandleId, NodeError>
11139    where
11140        F: FnMut(&[u8], Option<&nros_core::MessageInfo>) + 'static,
11141    {
11142        type Entry<F> = SubBufferedRawMsgInfoEntry<F>;
11143
11144        let SubscriptionOpen {
11145            slot,
11146            handle,
11147            slot_bytes: rx_bytes,
11148            ..
11149        } = self.open_subscription(&SubscriptionRequest {
11150            node_id,
11151            topic_name,
11152            type_name,
11153            type_hash,
11154            qos,
11155            backend_hint: Some(rx_buffer_hint),
11156            slot_bytes: if rx_buffer_hint != 0 {
11157                rx_buffer_hint
11158            } else {
11159                crate::config::DEFAULT_RX_BUF_SIZE
11160            },
11161            // The metadata comes with a COPYING take (`take_serialized_with_info`),
11162            // so this shape cannot dispatch in place. Spelled as the SHAPE, which
11163            // the metadata probe states without registering (issue 2349).
11164            in_place_capable: super::declared_shape::DeclaredSubscriptionShape::BufferedRawInfo
11165                .in_place_capable(),
11166        })?;
11167
11168        // The receive buffer first, then the capture on the next `u64`
11169        // boundary after it, as the plain C path lays out its ring.
11170        let capture_len = Self::capture_trailing_len(capture);
11171        let buf_len = rx_bytes.next_multiple_of(core::mem::align_of::<u64>());
11172        let (offset, trailing_offset) =
11173            self.arena_alloc_with_trailing::<Entry<F>>(buf_len + capture_len)?;
11174        let context = self.place_capture(trailing_offset + buf_len, capture, context);
11175        let callback = make(context);
11176        unsafe {
11177            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11178            let buffer = super::arena::TrailingBuf::init(arena_ptr.add(trailing_offset), rx_bytes);
11179            let entry_ptr = arena_ptr.add(offset) as *mut Entry<F>;
11180            core::ptr::write(
11181                entry_ptr,
11182                Entry {
11183                    handle,
11184                    buffer,
11185                    callback,
11186                },
11187            );
11188        }
11189
11190        let meta = CallbackMeta {
11191            offset,
11192            kind: EntryKind::Subscription,
11193            arena_len: super::arena::ArenaLen::UNRECORDED,
11194            try_process: sub_buffered_raw_msg_info_try_process::<F>,
11195            has_data: sub_buffered_raw_msg_info_has_data::<F>,
11196            pre_sample: no_pre_sample,
11197            invocation: InvocationMode::OnNewData,
11198            drop_fn: drop_entry::<Entry<F>>,
11199        };
11200        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
11201        // SAFETY: an `Entry<F>` was written at `offset` just above.
11202        unsafe {
11203            self.arm_entry_wake::<Entry<F>>(slot, offset, |e, w| {
11204                nros_rmw::Subscription::register_waker(&e.handle, w)
11205            })
11206        };
11207        self.apply_node_default_sched(slot, node_id, None);
11208        Ok(self.handle_for(slot))
11209    }
11210
11211    /// Phase 189.M3.4 — register a raw C-fn-ptr subscription whose callback
11212    /// also receives the sample's wire **attachment**
11213    /// ([`RawSubscriptionInfoCallback`]: `(data, len, attachment, att_len,
11214    /// context)`) — the C analog of the Rust
11215    /// `node.subscription(t).generic(..).message_info()` builder. Backs the C
11216    /// FFI `rclc_executor_add_subscription_raw_with_info`. Flat per-entry
11217    /// payload + attachment buffers (cap `RAW_INFO_ATT_CAP`);
11218    /// one sample per `spin_once`.
11219    #[allow(clippy::too_many_arguments)]
11220    pub(crate) fn add_arena_subscription_c_info_callback<const RX_BUF: usize>(
11221        &mut self,
11222        node_id: Option<super::node_record::NodeId>,
11223        topic_name: &str,
11224        type_name: &str,
11225        type_hash: &str,
11226        qos: QoSProfile,
11227        callback: RawSubscriptionInfoCallback,
11228        context: *mut core::ffi::c_void,
11229        // phase-408 W5a/W5b — bytes the caller expects to receive; 0 = no
11230        // opinion. It now buys BOTH halves: the BACKEND's payload size-class
11231        // routing (W5a, below) and the ARENA slot (W5b, further down). `RX_BUF`
11232        // survives only as the fallback for a caller that states nothing, which
11233        // is exactly its role on the plain C path.
11234        rx_buffer_hint: usize,
11235    ) -> Result<HandleId, NodeError> {
11236        type Entry = SubBufferedRawInfoCEntry;
11237
11238        let SubscriptionOpen {
11239            slot,
11240            handle,
11241            slot_bytes: rx_bytes,
11242            ..
11243        } = self.open_subscription(&SubscriptionRequest {
11244            node_id,
11245            topic_name,
11246            type_name,
11247            type_hash,
11248            qos,
11249            backend_hint: Some(rx_buffer_hint),
11250            // phase-408 W5b — the hint sizes the ARENA too, not just the
11251            // backend's size class. 0 still means "this caller stated nothing",
11252            // so `RX_BUF` -- `DEFAULT_RX_BUF_SIZE` at every call site -- is what
11253            // it falls back to, and an unhinted registration claims the same
11254            // bytes it always did.
11255            slot_bytes: if rx_buffer_hint != 0 {
11256                rx_buffer_hint
11257            } else {
11258                RX_BUF
11259            },
11260            // Carries the wire attachment — see the Rust `_raw_info_on` twin.
11261            in_place_capable: false,
11262        })?;
11263
11264        let (offset, trailing_offset) = self.arena_alloc_with_trailing::<Entry>(rx_bytes)?;
11265        unsafe {
11266            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11267            let buf = super::arena::TrailingBuf::init(arena_ptr.add(trailing_offset), rx_bytes);
11268            let entry_ptr = arena_ptr.add(offset) as *mut Entry;
11269            core::ptr::write(
11270                entry_ptr,
11271                Entry {
11272                    handle,
11273                    buffer: buf,
11274                    att: [0u8; super::arena::RAW_INFO_ATT_CAP],
11275                    callback,
11276                    context,
11277                },
11278            );
11279        }
11280
11281        let meta = CallbackMeta {
11282            offset,
11283            kind: EntryKind::Subscription,
11284            arena_len: super::arena::ArenaLen::UNRECORDED,
11285            try_process: sub_buffered_raw_info_c_try_process,
11286            has_data: sub_buffered_raw_info_c_has_data,
11287            pre_sample: no_pre_sample,
11288            invocation: InvocationMode::OnNewData,
11289            drop_fn: drop_entry::<Entry>,
11290        };
11291        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
11292        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11293        // SAFETY: a `Entry` was written at `offset` just above.
11294        unsafe {
11295            self.arm_entry_wake::<Entry>(slot, offset, |e, w| {
11296                nros_rmw::Subscription::register_waker(&e.handle, w)
11297            })
11298        };
11299        self.apply_node_default_sched(slot, node_id, None);
11300        Ok(self.handle_for(slot))
11301    }
11302
11303    /// Phase 269 W3 — register a raw C-fn-ptr subscription whose callback
11304    /// ALSO surfaces the sample's E2E integrity status (CRC + sequence gap/dup)
11305    /// alongside the CDR bytes — the C/C++ component-callback analog of Rust's
11306    /// `register_subscription_buffered_raw_safety_on` (`FnMut(&[u8], &IntegrityStatus)`).
11307    ///
11308    /// The executor validates the sample via `take_validated` and unpacks the
11309    /// [`nros_rmw::IntegrityStatus`] into three plain scalars (gap, duplicate,
11310    /// crc_valid) before calling `callback`. This avoids introducing a
11311    /// cbindgen-visible struct at the executor layer; the C/C++ headers pack them
11312    /// back into their local integrity-status typedef.
11313    ///
11314    /// Requires the `safety-e2e` feature. Backed by `SubBufferedRawSafetyCEntry`.
11315    #[cfg(feature = "safety-e2e")]
11316    #[allow(clippy::too_many_arguments)]
11317    pub(crate) fn add_arena_subscription_c_validated_callback<const RX_BUF: usize>(
11318        &mut self,
11319        node_id: Option<super::node_record::NodeId>,
11320        topic_name: &str,
11321        type_name: &str,
11322        type_hash: &str,
11323        qos: QoSProfile,
11324        callback: super::types::RawSubscriptionSafetyCallback,
11325        context: *mut core::ffi::c_void,
11326        // phase-408 W5a/W5b — bytes the caller expects to receive; 0 = no
11327        // opinion. It now buys BOTH halves: the BACKEND's payload size-class
11328        // routing (W5a, below) and the ARENA slot (W5b, further down). `RX_BUF`
11329        // survives only as the fallback for a caller that states nothing, which
11330        // is exactly its role on the plain C path.
11331        rx_buffer_hint: usize,
11332    ) -> Result<HandleId, NodeError> {
11333        use super::arena::{
11334            SubBufferedRawSafetyCEntry, TrailingBuf, sub_buffered_raw_safety_c_has_data,
11335            sub_buffered_raw_safety_c_try_process,
11336        };
11337        type Entry = SubBufferedRawSafetyCEntry;
11338
11339        let SubscriptionOpen {
11340            slot,
11341            handle,
11342            slot_bytes: rx_bytes,
11343            ..
11344        } = self.open_subscription(&SubscriptionRequest {
11345            node_id,
11346            topic_name,
11347            type_name,
11348            type_hash,
11349            qos,
11350            backend_hint: Some(rx_buffer_hint),
11351            // phase-408 W5b — same as the info sibling: one flat slot in the
11352            // trailing region, sized from the hint, `RX_BUF` only as the
11353            // stated-nothing fallback.
11354            slot_bytes: if rx_buffer_hint != 0 {
11355                rx_buffer_hint
11356            } else {
11357                RX_BUF
11358            },
11359            // Carries the integrity status, which comes from `take_validated`.
11360            in_place_capable: false,
11361        })?;
11362
11363        let (offset, trailing_offset) = self.arena_alloc_with_trailing::<Entry>(rx_bytes)?;
11364        unsafe {
11365            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11366            let buf = TrailingBuf::init(arena_ptr.add(trailing_offset), rx_bytes);
11367            let entry_ptr = arena_ptr.add(offset) as *mut Entry;
11368            core::ptr::write(
11369                entry_ptr,
11370                Entry {
11371                    handle,
11372                    buffer: buf,
11373                    callback,
11374                    context,
11375                },
11376            );
11377        }
11378
11379        let meta = CallbackMeta {
11380            offset,
11381            kind: EntryKind::Subscription,
11382            arena_len: super::arena::ArenaLen::UNRECORDED,
11383            try_process: sub_buffered_raw_safety_c_try_process,
11384            has_data: sub_buffered_raw_safety_c_has_data,
11385            pre_sample: no_pre_sample,
11386            invocation: InvocationMode::OnNewData,
11387            drop_fn: drop_entry::<Entry>,
11388        };
11389        self.emplace_entry(slot, meta, TraceName::Text(topic_name));
11390        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11391        // SAFETY: a `Entry` was written at `offset` just above.
11392        unsafe {
11393            self.arm_entry_wake::<Entry>(slot, offset, |e, w| {
11394                nros_rmw::Subscription::register_waker(&e.handle, w)
11395            })
11396        };
11397        self.apply_node_default_sched(slot, node_id, None);
11398        Ok(self.handle_for(slot))
11399    }
11400
11401    /// Register a raw (untyped) service callback.
11402    ///
11403    /// Register a raw (untyped) service callback with the default buffer size.
11404    ///
11405    /// The callback receives and produces CDR bytes without typed
11406    /// deserialization/serialization. Used by the C API wrapper.
11407    pub(crate) fn register_service_raw(
11408        &mut self,
11409        service_name: &str,
11410        service_type: &str,
11411        service_hash: &str,
11412        callback: RawServiceCallback,
11413        context: *mut core::ffi::c_void,
11414    ) -> Result<HandleId, NodeError> {
11415        self.register_service_raw_sized::<{ crate::config::DEFAULT_RX_BUF_SIZE }, { crate::config::DEFAULT_RX_BUF_SIZE }>(
11416            service_name,
11417            service_type,
11418            service_hash,
11419            QoSProfile::services_default(),
11420            callback,
11421            context,
11422        )
11423    }
11424
11425    /// Register a raw (untyped) service callback with custom buffer sizes + QoS.
11426    ///
11427    /// `REQ_BUF` and `REPLY_BUF` set the stack-allocated CDR buffers
11428    /// for the request and reply respectively. Increase for services
11429    /// with large payloads (e.g., parameter services). `qos` applies to both
11430    /// the request + reply endpoints (Phase 193.2c).
11431    #[allow(clippy::too_many_arguments)]
11432    pub(crate) fn register_service_raw_sized<const REQ_BUF: usize, const REPLY_BUF: usize>(
11433        &mut self,
11434        service_name: &str,
11435        service_type: &str,
11436        service_hash: &str,
11437        qos: QoSProfile,
11438        callback: RawServiceCallback,
11439        context: *mut core::ffi::c_void,
11440    ) -> Result<HandleId, NodeError> {
11441        self.register_service_raw_sized_inner::<REQ_BUF, REPLY_BUF, RawServiceCallback>(
11442            None,
11443            service_name,
11444            service_type,
11445            service_hash,
11446            qos,
11447            callback,
11448            context,
11449            None,
11450            None,
11451        )
11452    }
11453
11454    /// Phase 104.C.3.3.a — Node-aware variant of
11455    /// [`Self::register_service_raw_sized`]. C-FFI path.
11456    #[allow(clippy::too_many_arguments)]
11457    pub(crate) fn register_service_raw_sized_on<const REQ_BUF: usize, const REPLY_BUF: usize>(
11458        &mut self,
11459        node_id: super::node_record::NodeId,
11460        service_name: &str,
11461        service_type: &str,
11462        service_hash: &str,
11463        qos: QoSProfile,
11464        callback: RawServiceCallback,
11465        context: *mut core::ffi::c_void,
11466    ) -> Result<HandleId, NodeError> {
11467        self.register_service_raw_sized_inner::<REQ_BUF, REPLY_BUF, RawServiceCallback>(
11468            Some(node_id),
11469            service_name,
11470            service_type,
11471            service_hash,
11472            qos,
11473            callback,
11474            context,
11475            None,
11476            None,
11477        )
11478    }
11479
11480    /// phase-488 — [`Self::register_service_raw_sized`] / `_on` with the
11481    /// handler's CAPTURE copied into the entry's own region, as
11482    /// [`Self::add_arena_subscription_c_callback_with_capture`] does for a
11483    /// subscription. The dispatch context becomes the arena's copy, and
11484    /// `capture_drop` (when given) destroys it with the entry. This is what lets a
11485    /// C++ service handler carry state (`std::bind(&Node::on_x, this, _1, _2)`,
11486    /// a capturing lambda): a context word holds a `[this]` and not a
11487    /// pointer-to-member plus its object.
11488    #[allow(clippy::too_many_arguments)]
11489    pub(crate) fn register_service_raw_capturing<const REQ_BUF: usize, const REPLY_BUF: usize>(
11490        &mut self,
11491        node_id: Option<super::node_record::NodeId>,
11492        service_name: &str,
11493        service_type: &str,
11494        service_hash: &str,
11495        qos: QoSProfile,
11496        callback: RawServiceCallback,
11497        capture: Option<&[u8]>,
11498        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
11499    ) -> Result<HandleId, NodeError> {
11500        self.register_service_raw_sized_inner::<REQ_BUF, REPLY_BUF, RawServiceCallback>(
11501            node_id,
11502            service_name,
11503            service_type,
11504            service_hash,
11505            qos,
11506            callback,
11507            core::ptr::null_mut(),
11508            capture,
11509            capture_drop,
11510        )
11511    }
11512
11513    /// A raw service whose callback also receives the request's
11514    /// id (client writer GUID + client sequence number), rclc's
11515    /// `rclc_service_callback_with_request_id_t` shape in CDR bytes. The id is
11516    /// the one the backend reported for the request being dispatched
11517    /// ([`ServiceTrait::request_info`](nros_rmw::ServiceTrait::request_info)),
11518    /// all zeros when it reported none.
11519    ///
11520    /// One entry point for every registration shape: `node_id` as
11521    /// `register_service_raw_sized_on` (or `None`), and `capture` as
11522    /// `register_service_raw_capturing` (or `None`, with `context`
11523    /// passed through instead).
11524    #[allow(clippy::too_many_arguments)]
11525    pub fn register_service_raw_with_request_id_sized<
11526        const REQ_BUF: usize,
11527        const REPLY_BUF: usize,
11528    >(
11529        &mut self,
11530        node_id: Option<super::node_record::NodeId>,
11531        service_name: &str,
11532        service_type: &str,
11533        service_hash: &str,
11534        qos: QoSProfile,
11535        callback: RawServiceRequestIdCallback,
11536        context: *mut core::ffi::c_void,
11537        capture: Option<&[u8]>,
11538        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
11539    ) -> Result<HandleId, NodeError> {
11540        self.register_service_raw_sized_inner::<REQ_BUF, REPLY_BUF, RawServiceRequestIdCallback>(
11541            node_id,
11542            service_name,
11543            service_type,
11544            service_hash,
11545            qos,
11546            callback,
11547            context,
11548            capture,
11549            capture_drop,
11550        )
11551    }
11552
11553    #[allow(clippy::too_many_arguments)]
11554    fn register_service_raw_sized_inner<
11555        const REQ_BUF: usize,
11556        const REPLY_BUF: usize,
11557        C: super::arena::RawServiceDispatch,
11558    >(
11559        &mut self,
11560        node_id: Option<super::node_record::NodeId>,
11561        service_name: &str,
11562        service_type: &str,
11563        service_hash: &str,
11564        qos: QoSProfile,
11565        callback: C,
11566        context: *mut core::ffi::c_void,
11567        capture: Option<&[u8]>,
11568        capture_drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
11569    ) -> Result<HandleId, NodeError> {
11570        let slot = self.next_entry_slot()?;
11571        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
11572        let mut info = ServiceInfo::new(service_name, service_type, service_hash)
11573            .with_domain(self.domain_id)
11574            .with_namespace(&ns);
11575        if !node_name.is_empty() {
11576            info = info.with_node_name(&node_name);
11577        }
11578        let handle = {
11579            let session = self
11580                .session_at_mut(session_idx)
11581                .ok_or(NodeError::BackendMismatch)?;
11582            // Phase 193.5 — validate against the backend's supported policies
11583            // (no silent downgrade); request/reply effectively requires RELIABLE.
11584            super::node::validate_qos_or_report(
11585                &qos,
11586                session.supported_qos_policies(),
11587                "service",
11588                service_name,
11589            )?;
11590            session
11591                .create_service(&info, qos)
11592                .map_err(NodeError::Transport)?
11593        };
11594
11595        // phase-488 — a capture rides at the end of the entry's own region, as
11596        // a subscription's does, so releasing the entry gives it back. No
11597        // capture keeps `arena_alloc`, so a C caller's arena use does not move.
11598        let capture_len = Self::capture_trailing_len(capture);
11599        let (offset, context) = if capture_len == 0 {
11600            (
11601                self.arena_alloc::<SrvRawEntry<REQ_BUF, REPLY_BUF, C>>()?,
11602                context,
11603            )
11604        } else {
11605            let (offset, capture_at) =
11606                self.arena_alloc_with_trailing::<SrvRawEntry<REQ_BUF, REPLY_BUF, C>>(capture_len)?;
11607            (offset, self.place_capture(capture_at, capture, context))
11608        };
11609
11610        unsafe {
11611            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11612            let entry_ptr = arena_ptr.add(offset) as *mut SrvRawEntry<REQ_BUF, REPLY_BUF, C>;
11613            core::ptr::write(
11614                entry_ptr,
11615                SrvRawEntry {
11616                    handle,
11617                    req_buffer: [0u8; REQ_BUF],
11618                    reply_buffer: [0u8; REPLY_BUF],
11619                    callback,
11620                    context,
11621                    capture: super::arena::CaptureGuard {
11622                        ctx: context,
11623                        drop: capture_drop,
11624                    },
11625                },
11626            );
11627        }
11628
11629        let meta = CallbackMeta {
11630            offset,
11631            kind: EntryKind::Service,
11632            arena_len: super::arena::ArenaLen::UNRECORDED,
11633            try_process: srv_raw_try_process::<REQ_BUF, REPLY_BUF, C>,
11634            has_data: srv_raw_has_data::<REQ_BUF, REPLY_BUF, C>,
11635            pre_sample: no_pre_sample,
11636            invocation: InvocationMode::OnNewData,
11637            drop_fn: drop_entry::<SrvRawEntry<REQ_BUF, REPLY_BUF, C>>,
11638        };
11639        self.emplace_entry(slot, meta, TraceName::Text(service_name));
11640        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11641        // SAFETY: a `SrvRawEntry<REQ_BUF, REPLY_BUF, C>` was written at `offset` just above.
11642        unsafe {
11643            self.arm_entry_wake::<SrvRawEntry<REQ_BUF, REPLY_BUF, C>>(slot, offset, |e, w| {
11644                nros_rmw::ServiceTrait::register_waker(&e.handle, w)
11645            })
11646        };
11647        self.apply_node_default_sched(slot, node_id, None);
11648        Ok(self.handle_for(slot))
11649    }
11650
11651    // ========================================================================
11652    // Raw service client registration (Phase 82)
11653    // ========================================================================
11654
11655    /// Register a raw (untyped) service client with the default reply
11656    /// buffer size.
11657    ///
11658    /// The client is owned by the executor's arena. Each `spin_once`
11659    /// dispatch polls the in-flight reply slot via `take_response_raw`
11660    /// and fires the registered callback when the response arrives.
11661    /// Used by the C API thin wrapper — see Phase 82.
11662    pub(crate) fn register_service_client_raw(
11663        &mut self,
11664        service_name: &str,
11665        service_type: &str,
11666        service_hash: &str,
11667        callback: Option<RawResponseCallback>,
11668        context: *mut core::ffi::c_void,
11669    ) -> Result<HandleId, NodeError> {
11670        self.register_service_client_raw_sized::<{ crate::config::DEFAULT_RX_BUF_SIZE }>(
11671            service_name,
11672            service_type,
11673            service_hash,
11674            QoSProfile::services_default(),
11675            callback,
11676            context,
11677        )
11678    }
11679
11680    /// Register a raw service client with a custom reply buffer size + QoS.
11681    ///
11682    /// `qos` applies to the client's request + reply endpoints (Phase 193.3b);
11683    /// defaults to [`QoSProfile::services_default`] via the convenience
11684    /// wrapper.
11685    #[allow(clippy::too_many_arguments)]
11686    pub(crate) fn register_service_client_raw_sized<const REPLY_BUF: usize>(
11687        &mut self,
11688        service_name: &str,
11689        service_type: &str,
11690        service_hash: &str,
11691        qos: QoSProfile,
11692        callback: Option<RawResponseCallback>,
11693        context: *mut core::ffi::c_void,
11694    ) -> Result<HandleId, NodeError> {
11695        self.register_service_client_raw_sized_inner::<REPLY_BUF>(
11696            None,
11697            service_name,
11698            service_type,
11699            service_hash,
11700            qos,
11701            callback,
11702            context,
11703            None,
11704        )
11705    }
11706
11707    /// Phase 104.C.3.3.a — Node-aware variant of
11708    /// [`Self::register_service_client_raw_sized`]. Routes the client
11709    /// creation through the named Node's session.
11710    #[allow(clippy::too_many_arguments)]
11711    pub(crate) fn register_service_client_raw_sized_on<const REPLY_BUF: usize>(
11712        &mut self,
11713        node_id: super::node_record::NodeId,
11714        service_name: &str,
11715        service_type: &str,
11716        service_hash: &str,
11717        qos: QoSProfile,
11718        callback: Option<RawResponseCallback>,
11719        context: *mut core::ffi::c_void,
11720    ) -> Result<HandleId, NodeError> {
11721        self.register_service_client_raw_sized_inner::<REPLY_BUF>(
11722            Some(node_id),
11723            service_name,
11724            service_type,
11725            service_hash,
11726            qos,
11727            callback,
11728            context,
11729            None,
11730        )
11731    }
11732
11733    /// phase-515 C3 — a raw service client whose response callback reads a
11734    /// CAPTURE the arena holds, the client twin of
11735    /// [`register_service_raw_capturing`](Self::register_service_raw_capturing).
11736    ///
11737    /// rclc's typed `rclc_executor_add_client(executor, client, response_msg,
11738    /// callback)` needs three words at dispatch — the caller's response
11739    /// storage, the type's deserialiser and the callback — and the raw entry
11740    /// has one context word. The capture is copied to the end of the entry's
11741    /// own region and `callback` is handed a pointer to that copy, so the C
11742    /// side keeps nothing and releasing the client releases the capture.
11743    /// `rclc_client_call` swaps its own one-shot pair in and out of the entry
11744    /// and restores this one, so a typed client can still be called
11745    /// synchronously.
11746    #[allow(clippy::too_many_arguments)]
11747    pub(crate) fn register_service_client_raw_capturing<const REPLY_BUF: usize>(
11748        &mut self,
11749        node_id: Option<super::node_record::NodeId>,
11750        service_name: &str,
11751        service_type: &str,
11752        service_hash: &str,
11753        qos: QoSProfile,
11754        callback: Option<RawResponseCallback>,
11755        capture: Option<&[u8]>,
11756    ) -> Result<HandleId, NodeError> {
11757        self.register_service_client_raw_sized_inner::<REPLY_BUF>(
11758            node_id,
11759            service_name,
11760            service_type,
11761            service_hash,
11762            qos,
11763            callback,
11764            core::ptr::null_mut(),
11765            capture,
11766        )
11767    }
11768
11769    #[allow(clippy::too_many_arguments)]
11770    fn register_service_client_raw_sized_inner<const REPLY_BUF: usize>(
11771        &mut self,
11772        node_id: Option<super::node_record::NodeId>,
11773        service_name: &str,
11774        service_type: &str,
11775        service_hash: &str,
11776        qos: QoSProfile,
11777        callback: Option<RawResponseCallback>,
11778        context: *mut core::ffi::c_void,
11779        capture: Option<&[u8]>,
11780    ) -> Result<HandleId, NodeError> {
11781        let slot = self.next_entry_slot()?;
11782        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
11783        let mut info = ServiceInfo::new(service_name, service_type, service_hash)
11784            .with_domain(self.domain_id)
11785            .with_namespace(&ns);
11786        if !node_name.is_empty() {
11787            info = info.with_node_name(&node_name);
11788        }
11789        let handle = {
11790            let session = self
11791                .session_at_mut(session_idx)
11792                .ok_or(NodeError::BackendMismatch)?;
11793            // Phase 193.5 — validate against the backend's supported policies
11794            // (no silent downgrade); request/reply effectively requires RELIABLE.
11795            super::node::validate_qos_or_report(
11796                &qos,
11797                session.supported_qos_policies(),
11798                "client",
11799                service_name,
11800            )?;
11801            session
11802                .create_client(&info, qos)
11803                .map_err(|_| NodeError::Transport(TransportError::ServiceClientCreationFailed))?
11804        };
11805
11806        // phase-515 C3 — a capture rides at the end of the entry's own region,
11807        // as a service's does (phase-488). No capture keeps `arena_alloc`, so a
11808        // client registered without one uses exactly the arena it always did.
11809        let capture_len = Self::capture_trailing_len(capture);
11810        let (offset, context) = if capture_len == 0 {
11811            (
11812                self.arena_alloc::<ServiceClientRawArenaEntry<REPLY_BUF>>()?,
11813                context,
11814            )
11815        } else {
11816            let (offset, capture_at) = self
11817                .arena_alloc_with_trailing::<ServiceClientRawArenaEntry<REPLY_BUF>>(capture_len)?;
11818            (offset, self.place_capture(capture_at, capture, context))
11819        };
11820        unsafe {
11821            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11822            let entry_ptr = arena_ptr.add(offset) as *mut ServiceClientRawArenaEntry<REPLY_BUF>;
11823            core::ptr::write(
11824                entry_ptr,
11825                ServiceClientRawArenaEntry {
11826                    handle,
11827                    reply_buffer: [0u8; REPLY_BUF],
11828                    pending: false,
11829                    reply_ready: core::sync::atomic::AtomicBool::new(false),
11830                    callback,
11831                    request_id_callback: None,
11832                    context,
11833                    sequences: super::arena::ClientSequences::new(),
11834                },
11835            );
11836        }
11837
11838        let meta = CallbackMeta {
11839            offset,
11840            kind: EntryKind::ServiceClient,
11841            arena_len: super::arena::ArenaLen::UNRECORDED,
11842            try_process: service_client_raw_try_process::<REPLY_BUF>,
11843            has_data: always_ready,
11844            pre_sample: no_pre_sample,
11845            invocation: InvocationMode::Always,
11846            drop_fn: drop_entry::<ServiceClientRawArenaEntry<REPLY_BUF>>,
11847        };
11848        self.emplace_entry(slot, meta, TraceName::Text(service_name));
11849        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11850        // SAFETY: a `ServiceClientRawArenaEntry<REPLY_BUF>` was written at `offset` just above.
11851        unsafe {
11852            self.arm_entry_wake::<ServiceClientRawArenaEntry<REPLY_BUF>>(slot, offset, |e, w| {
11853                nros_rmw::ClientTrait::register_waker(&e.handle, w)
11854            })
11855        };
11856        self.apply_node_default_sched(slot, node_id, None);
11857        Ok(self.handle_for(slot))
11858    }
11859
11860    /// RFC-0041 / Phase 239.1 — register a **typed callback** service client.
11861    /// The reply is eager-drained at `spin_once` and dispatched to `callback` as
11862    /// a deserialized `Svc::Reply`. Returns the scheduling [`HandleId`] and a
11863    /// `*mut` to the arena entry's send header (used to build the typed
11864    /// [`ServiceClientCallback`](super::handles::ServiceClientCallback)).
11865    #[allow(clippy::too_many_arguments)]
11866    pub(crate) fn register_service_client_callback<Svc, F, const REPLY_BUF: usize>(
11867        &mut self,
11868        node_id: Option<super::node_record::NodeId>,
11869        service_name: &str,
11870        service_type: &str,
11871        service_hash: &str,
11872        qos: QoSProfile,
11873        callback: F,
11874    ) -> Result<(HandleId, *mut ServiceClientSendHeader<REPLY_BUF>), NodeError>
11875    where
11876        Svc: nros_core::RosService + 'static,
11877        // Issue 2148 — `ReplyOnly(closure)` or `ReplyWithInfo(closure)`.
11878        F: super::arena::ClientReplyCallback<Svc::Reply> + 'static,
11879    {
11880        let slot = self.next_entry_slot()?;
11881        let (node_name, ns, session_idx) = self.entity_identity(node_id)?;
11882        let mut info = ServiceInfo::new(service_name, service_type, service_hash)
11883            .with_domain(self.domain_id)
11884            .with_namespace(&ns);
11885        if !node_name.is_empty() {
11886            info = info.with_node_name(&node_name);
11887        }
11888        let handle = {
11889            let session = self
11890                .session_at_mut(session_idx)
11891                .ok_or(NodeError::BackendMismatch)?;
11892            super::node::validate_qos_or_report(
11893                &qos,
11894                session.supported_qos_policies(),
11895                "client",
11896                service_name,
11897            )?;
11898            session
11899                .create_client(&info, qos)
11900                .map_err(|_| NodeError::Transport(TransportError::ServiceClientCreationFailed))?
11901        };
11902
11903        let offset = self.arena_alloc::<ServiceClientCallbackEntry<Svc, F, REPLY_BUF>>()?;
11904        let hdr_ptr = unsafe {
11905            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
11906            let entry_ptr =
11907                arena_ptr.add(offset) as *mut ServiceClientCallbackEntry<Svc, F, REPLY_BUF>;
11908            core::ptr::write(
11909                entry_ptr,
11910                ServiceClientCallbackEntry {
11911                    hdr: ServiceClientSendHeader {
11912                        handle,
11913                        reply_buffer: [0u8; REPLY_BUF],
11914                        pending: false,
11915                        reply_ready: core::sync::atomic::AtomicBool::new(false),
11916                        sequences: super::arena::ClientSequences::new(),
11917                    },
11918                    callback,
11919                    _phantom: core::marker::PhantomData,
11920                },
11921            );
11922            // Phase-573 W2b — a raw place, not `&mut .. as *mut`: a pointer
11923            // made from a temporary reference is a child of it, and the
11924            // dispatcher's own write to the entry disables it, so the next
11925            // `call` through the handle would be UB.
11926            core::ptr::addr_of_mut!((*entry_ptr).hdr)
11927        };
11928
11929        let meta = CallbackMeta {
11930            offset,
11931            kind: EntryKind::ServiceClient,
11932            arena_len: super::arena::ArenaLen::UNRECORDED,
11933            try_process: service_client_callback_try_process::<Svc, F, REPLY_BUF>,
11934            has_data: always_ready,
11935            pre_sample: no_pre_sample,
11936            invocation: InvocationMode::Always,
11937            drop_fn: drop_entry::<ServiceClientCallbackEntry<Svc, F, REPLY_BUF>>,
11938        };
11939        self.emplace_entry(slot, meta, TraceName::Text(service_name));
11940        // phase-397 W2 — this entry's arrivals mark its slot and wake this executor.
11941        // SAFETY: a `ServiceClientCallbackEntry<Svc, F, REPLY_BUF>` was written at `offset` just above.
11942        unsafe {
11943            self.arm_entry_wake::<ServiceClientCallbackEntry<Svc, F, REPLY_BUF>>(
11944                slot,
11945                offset,
11946                |e, w| nros_rmw::ClientTrait::register_waker(&e.hdr.handle, w),
11947            )
11948        };
11949        self.apply_node_default_sched(slot, node_id, None);
11950        Ok((self.handle_for(slot), hdr_ptr))
11951    }
11952
11953    // ========================================================================
11954    // Guard condition registration
11955    // ========================================================================
11956
11957    /// Register a guard condition with a callback, on no particular node.
11958    ///
11959    /// Returns both the [`HandleId`] for trigger configuration and a
11960    /// [`GuardCondition`] for triggering from other threads.
11961    ///
11962    /// **This is the ours-only PRIMITIVE, not the verb a user reaches for.**
11963    /// It was settled that the NODE owns a guard condition in all three
11964    /// languages, so the spelling an application writes is
11965    /// [`Node::create_guard_condition`](crate::executor::Node::create_guard_condition)
11966    /// — which is this function with a node bound, so the guard inherits that
11967    /// node's `SchedContext` like every other entity the node creates. This one
11968    /// stays because the executor is what owns the arena the flag lives in, and
11969    /// because an image with no node at all (a bare `Executor::open` plus a
11970    /// wake source) still has to be able to make one.
11971    pub fn register_guard_condition<F>(
11972        &mut self,
11973        callback: F,
11974    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
11975    where
11976        F: FnMut() + 'static,
11977    {
11978        self.register_guard_condition_on(None, callback)
11979    }
11980
11981    /// The node-bound form of [`register_guard_condition`](Self::register_guard_condition).
11982    ///
11983    /// `node_id == None` is the legacy nodeless path and behaves exactly as
11984    /// `register_guard_condition` always did. With a node, the registered slot
11985    /// takes that node's default `SchedContext`, which is what "the node owns
11986    /// it" has to mean for a callback that shares one executor with every other
11987    /// sched task in the image.
11988    pub fn register_guard_condition_on<F>(
11989        &mut self,
11990        node_id: Option<super::node_record::NodeId>,
11991        callback: F,
11992    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
11993    where
11994        F: FnMut() + 'static,
11995    {
11996        let slot = self.next_entry_slot()?;
11997        let offset = self.arena_alloc::<GuardConditionEntry<F>>()?;
11998
11999        unsafe {
12000            let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12001            let entry_ptr = arena_ptr.add(offset) as *mut GuardConditionEntry<F>;
12002            core::ptr::write(
12003                entry_ptr,
12004                GuardConditionEntry {
12005                    flag: portable_atomic::AtomicBool::new(false),
12006                    callback,
12007                },
12008            );
12009
12010            // Create a handle pointing to the flag in the arena
12011            // Phase-573 W2b — a raw place, like the client handles' pointers.
12012            // (A shared reference to an atomic would tolerate the entry's
12013            // writes; the one spelling keeps the class uniform.)
12014            let flag_ptr = core::ptr::addr_of!((*entry_ptr).flag);
12015            #[allow(unused_mut)]
12016            let mut guard_handle = GuardCondition::new(flag_ptr);
12017            // Phase 124.B.5 — wire the wake callback so trigger()
12018            // also signals the executor's wake_cv.
12019            #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
12020            {
12021                // Issue 2727 -- the handle holds its own `Arc`, so a trigger
12022                // after the executor is dropped reaches live memory.
12023                let _ = self.wake_ctx_ptr();
12024                let ctx = self.wake_ctx.clone().expect("wake_ctx_ptr just set it");
12025                guard_handle.set_wake_cb(
12026                    nros_rmw_runtime_wake_cb,
12027                    nros_rmw_runtime_wake_cb_from_isr,
12028                    ctx,
12029                );
12030            }
12031
12032            let meta = CallbackMeta {
12033                offset,
12034                kind: EntryKind::GuardCondition,
12035                arena_len: super::arena::ArenaLen::UNRECORDED,
12036                try_process: guard_try_process::<F>,
12037                has_data: guard_has_data::<F>,
12038                pre_sample: no_pre_sample,
12039                invocation: InvocationMode::OnNewData,
12040                drop_fn: drop_entry::<GuardConditionEntry<F>>,
12041            };
12042            self.emplace_entry(slot, meta, TraceName::Slot("guard", slot));
12043            self.apply_node_default_sched(slot, node_id, None);
12044
12045            Ok((self.handle_for(slot), guard_handle))
12046        }
12047    }
12048
12049    /// A guard condition the BACKEND triggers when the ROS
12050    /// graph changes. Upstream's `rcl_node_get_graph_guard_condition`, under
12051    /// this project's guard-condition shape.
12052    ///
12053    /// **The verb is upstream's, the shape is ours, and the difference is
12054    /// stated rather than silent.** `rcl_node_get_graph_guard_condition`
12055    /// RETURNS a borrowed handle to a guard the node owns, which the caller
12056    /// then adds to a wait set. The C API's thin-wrapper discipline forbids returning an owned
12057    /// handle across the C seam, we decline wait sets (one executor
12058    /// per RTOS task), and a guard condition here is created into CALLER
12059    /// storage with its callback bound at creation. So this CREATES one —
12060    /// exactly as [`register_guard_condition_on`] does — and differs from it
12061    /// only in who pulls the trigger.
12062    ///
12063    /// Order matters and is the reason this is one verb rather than two. The
12064    /// backend is asked whether it HAS a graph before a handle slot is
12065    /// consumed, so a caller on XRCE or uORB gets `Unsupported` and an
12066    /// unchanged executor, never a guard condition nothing will ever fire.
12067    ///
12068    /// [`register_guard_condition_on`]: Self::register_guard_condition_on
12069    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
12070    pub fn register_graph_change_guard_on<F>(
12071        &mut self,
12072        node_id: Option<super::node_record::NodeId>,
12073        callback: F,
12074    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
12075    where
12076        F: FnMut() + 'static,
12077    {
12078        // The probe FIRST — see the doc comment. `supports_*` asks by
12079        // clearing, which is idempotent and costs nothing.
12080        if !self.supports_graph_change_callback() {
12081            return Err(NodeError::Transport(TransportError::Unsupported));
12082        }
12083        let (handle_id, guard) = self.register_guard_condition_on(node_id, callback)?;
12084        self.install_graph_change_guard(&guard)?;
12085        Ok((handle_id, guard))
12086    }
12087
12088    /// The nodeless form of
12089    /// [`register_graph_change_guard_on`](Self::register_graph_change_guard_on),
12090    /// for an image with a session and no node — the same pairing
12091    /// [`register_guard_condition`](Self::register_guard_condition) has.
12092    #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
12093    pub fn register_graph_change_guard<F>(
12094        &mut self,
12095        callback: F,
12096    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
12097    where
12098        F: FnMut() + 'static,
12099    {
12100        self.register_graph_change_guard_on(None, callback)
12101    }
12102
12103    /// The same two verbs on a build with no `rmw-cffi` backend seam, or no
12104    /// allocator — they REFUSE rather than disappear.
12105    ///
12106    /// The cfg'd-out spelling was the first shape and it was wrong in a way
12107    /// `just check fast` cannot see: `rclc_node_get_graph_guard_condition` is
12108    /// a C ABI symbol and calls this unconditionally, so a feature
12109    /// combination without the seam stopped `nros-c` from COMPILING
12110    /// (`check-build`'s `workspace-features`, which is the lane that unifies
12111    /// nothing and therefore sees each combination as a user would).
12112    ///
12113    /// Refusing is also the honest answer rather than a compile fix. The
12114    /// graph-change edge is installed on a SESSION through the backend seam;
12115    /// without that seam there is no backend to install it on, and the
12116    /// executor-owned target needs an allocator for the box the backend holds
12117    /// a pointer to. `Unsupported` is what a caller gets from a backend with
12118    /// no graph too, so the C entry point answers `RCL_RET_UNSUPPORTED` in
12119    /// both cases and a ported program sees one behaviour, not two.
12120    #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
12121    pub fn register_graph_change_guard_on<F>(
12122        &mut self,
12123        node_id: Option<super::node_record::NodeId>,
12124        callback: F,
12125    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
12126    where
12127        F: FnMut() + 'static,
12128    {
12129        let _ = (node_id, callback);
12130        Err(NodeError::Transport(TransportError::Unsupported))
12131    }
12132
12133    /// The nodeless form on a build with no backend seam — see
12134    /// [`register_graph_change_guard_on`](Self::register_graph_change_guard_on).
12135    #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
12136    pub fn register_graph_change_guard<F>(
12137        &mut self,
12138        callback: F,
12139    ) -> Result<(HandleId, GuardCondition<'s>), NodeError>
12140    where
12141        F: FnMut() + 'static,
12142    {
12143        self.register_graph_change_guard_on(None, callback)
12144    }
12145
12146    // ========================================================================
12147    // Timer control methods
12148    // ========================================================================
12149
12150    /// Cancel a timer. A cancelled timer will not fire but still accumulates
12151    /// elapsed time. The timer can be restarted with [`reset_timer()`](Self::reset_timer).
12152    ///
12153    /// While the timer's callback runs in another
12154    /// thread's window, the cancel is recorded and applied when it returns.
12155    pub fn cancel_timer(&mut self, id: HandleId) -> Result<(), NodeError> {
12156        if self.defer_timer_op(id, super::types::SlotTag::CANCEL_PENDING)? {
12157            return Ok(());
12158        }
12159        let meta = self
12160            .entries
12161            .get(self.live_slot(id))
12162            .and_then(|e| e.as_ref())
12163            .ok_or(NodeError::BufferTooSmall)?;
12164        if !matches!(meta.kind, EntryKind::Timer) {
12165            return Err(NodeError::BufferTooSmall);
12166        }
12167        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12168        // SAFETY: meta.offset points to a valid TimerEntry<F> which shares
12169        // layout with TimerHeader for its initial fields (both #[repr(C)]).
12170        let header = unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
12171        header.cancelled = true;
12172        Ok(())
12173    }
12174
12175    /// Reset a timer. Clears the cancelled state and resets the elapsed time
12176    /// to zero, so the timer starts a fresh period.
12177    ///
12178    /// Deferred like [`Self::cancel_timer`].
12179    pub fn reset_timer(&mut self, id: HandleId) -> Result<(), NodeError> {
12180        if self.defer_timer_op(id, super::types::SlotTag::RESET_PENDING)? {
12181            return Ok(());
12182        }
12183        let meta = self
12184            .entries
12185            .get(self.live_slot(id))
12186            .and_then(|e| e.as_ref())
12187            .ok_or(NodeError::BufferTooSmall)?;
12188        if !matches!(meta.kind, EntryKind::Timer) {
12189            return Err(NodeError::BufferTooSmall);
12190        }
12191        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12192        let header = unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
12193        header.cancelled = false;
12194        header.elapsed_us = 0;
12195        // Issue 1974 — a CLOCK timer advances by `now - last_clock_ns`, and a
12196        // cancelled timer is not polled, so its last reading is from when it
12197        // was cancelled (or, for `autostart = false`, registered). Without a
12198        // re-seed the first poll after this reset would credit the whole
12199        // cancelled interval as one step and fire at once — "a fresh period"
12200        // would hold for wall timers only. `Steady` reads no clock; its seed
12201        // stays 0 and is never read.
12202        header.last_clock_ns = header.clock_source.now_ns();
12203        Ok(())
12204    }
12205
12206    /// Start this executor's timing NOW, as if it had just been opened.
12207    ///
12208    /// The first `spin_once` normally credits every timer with the time since
12209    /// the executor opened (the spin baseline is read at open), and a clock
12210    /// timer with the time since it registered. That is right while setup and
12211    /// the first spin are back to back. A boot that waits between them (the
12212    /// wall-clock resolution, which can take a few seconds with an SNTP source
12213    /// and no server) would otherwise reach its first spin owing every timer
12214    /// that wait: a `CatchUp` timer would replay it, a `Skip` timer would count
12215    /// it as overruns. Called once, before the first spin, it re-seeds the spin
12216    /// baseline and every timer's last clock reading; no timer has advanced
12217    /// yet, so nothing else needs resetting.
12218    pub fn restart_timing(&mut self) {
12219        if let Some(clock) = self.clock_us_fn {
12220            self.last_spin_end_us = Some(clock());
12221        }
12222        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12223        for meta in self.entries.iter().flatten() {
12224            if matches!(meta.kind, EntryKind::Timer) {
12225                // SAFETY: a live Timer entry's offset names its TimerHeader in
12226                // the arena, exactly as `reset_timer` reads it above.
12227                let header = unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
12228                header.last_clock_ns = header.clock_source.now_ns();
12229            }
12230        }
12231    }
12232
12233    /// phase-509 P9b item 2 -- record a cancel (`op` = `CANCEL_PENDING`) or a
12234    /// reset (`RESET_PENDING`) of the timer `id` when its callback runs in
12235    /// another thread's window, and answer `true`; `false` when it is not,
12236    /// and the caller applies the operation now. The later of the two wins.
12237    fn defer_timer_op(&mut self, id: HandleId, op: u8) -> Result<bool, NodeError> {
12238        let Some(slot) = self.resolve_handle(id) else {
12239            return Ok(false);
12240        };
12241        if !self.running_elsewhere(slot) {
12242            return Ok(false);
12243        }
12244        if !self.entries[slot]
12245            .as_ref()
12246            .is_some_and(|m| matches!(m.kind, EntryKind::Timer))
12247        {
12248            return Err(NodeError::BufferTooSmall);
12249        }
12250        let tag = &self.slot_tags[slot];
12251        tag.clear(super::types::SlotTag::CANCEL_PENDING | super::types::SlotTag::RESET_PENDING);
12252        tag.set(op);
12253        Ok(true)
12254    }
12255
12256    /// phase-509 P9b item 2 -- apply the cancel or reset deferred while the
12257    /// timer in `slot` ran (`defer_timer_op`). Under the lock, its callback
12258    /// returned.
12259    fn apply_deferred_timer_op(&mut self, slot: usize) {
12260        let Some(tag) = self.slot_tags.get(slot) else {
12261            return;
12262        };
12263        let was =
12264            tag.clear(super::types::SlotTag::CANCEL_PENDING | super::types::SlotTag::RESET_PENDING);
12265        if was & (super::types::SlotTag::CANCEL_PENDING | super::types::SlotTag::RESET_PENDING) == 0
12266        {
12267            return;
12268        }
12269        let id = self.handle_for(slot);
12270        if was & super::types::SlotTag::CANCEL_PENDING != 0 {
12271            let _ = self.cancel_timer(id);
12272        } else {
12273            let _ = self.reset_timer(id);
12274        }
12275    }
12276
12277    /// Check if a timer is cancelled.
12278    ///
12279    /// A cancel or reset still pending behind the
12280    /// timer's running callback is the answer, as if it had applied.
12281    pub fn timer_is_canceled(&self, id: HandleId) -> bool {
12282        if let Some(slot) = self.resolve_handle(id)
12283            && self.running_elsewhere(slot)
12284        {
12285            let f = self.slot_tags[slot].flags();
12286            if f & super::types::SlotTag::CANCEL_PENDING != 0 {
12287                return true;
12288            }
12289            if f & super::types::SlotTag::RESET_PENDING != 0 {
12290                return false;
12291            }
12292        }
12293        // `resolve_handle`, not `live_slot`: a running callback's dispatch
12294        // never writes `cancelled` (only `cancel_timer` / `reset_timer` do,
12295        // and they are deferred while it runs elsewhere), so the flag is read
12296        // as a plain field, through a raw pointer, with no reference to the
12297        // entry the callback holds.
12298        let meta = match self
12299            .entries
12300            .get(self.resolve_handle(id).unwrap_or(usize::MAX))
12301            .and_then(|e| e.as_ref())
12302        {
12303            Some(m) if matches!(m.kind, EntryKind::Timer) => m,
12304            _ => return false,
12305        };
12306        let arena_ptr = self.arena.as_ptr() as *const u8;
12307        // SAFETY: `meta.offset` is this live entry's slot inside the arena.
12308        let header = unsafe { arena_ptr.add(meta.offset) as *const TimerHeader };
12309        // SAFETY: a Timer entry's arena slot starts with its `TimerHeader`;
12310        // see above for why the read races no write.
12311        unsafe { core::ptr::addr_of!((*header).cancelled).read() }
12312    }
12313
12314    /// Get the period of a timer in milliseconds (truncated — see
12315    /// [`Self::timer_period_us`]), or `None` if the handle is not a
12316    /// valid timer.
12317    pub fn timer_period_ms(&self, id: HandleId) -> Option<u64> {
12318        let meta = self
12319            .entries
12320            .get(self.live_slot(id))
12321            .and_then(|e| e.as_ref())
12322            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12323        let arena_ptr = self.arena.as_ptr() as *const u8;
12324        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12325        Some(header.period_us / 1000)
12326    }
12327
12328    /// Get the period of a timer in microseconds, or `None` if the
12329    /// handle is not a valid timer.
12330    pub fn timer_period_us(&self, id: HandleId) -> Option<u64> {
12331        let meta = self
12332            .entries
12333            .get(self.live_slot(id))
12334            .and_then(|e| e.as_ref())
12335            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12336        let arena_ptr = self.arena.as_ptr() as *const u8;
12337        // SAFETY: same layout invariant as `timer_period_ms`.
12338        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12339        Some(header.period_us)
12340    }
12341
12342    /// Which clock advances this timer, or `None` if the handle is not a valid
12343    /// timer.
12344    ///
12345    /// The state `rclcpp::TimerBase::get_clock()` reports. The
12346    /// header field is the one `arena::timer_try_process` reads, so the answer
12347    /// is the dispatcher's own rather than a copy a wrapper kept beside it: a
12348    /// wall timer answers [`TimerClockSource::Steady`], a clock timer the
12349    /// source it was registered with.
12350    pub fn timer_clock_source(&self, id: HandleId) -> Option<TimerClockSource> {
12351        let meta = self
12352            .entries
12353            .get(self.live_slot(id))
12354            .and_then(|e| e.as_ref())
12355            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12356        let arena_ptr = self.arena.as_ptr() as *const u8;
12357        // SAFETY: same layout invariant as `timer_period_us`.
12358        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12359        Some(header.clock_source)
12360    }
12361
12362    /// Swap a registered timer's period, in microseconds, returning the one
12363    /// it had — or `None` if the handle is not a valid timer.
12364    ///
12365    /// `TimerHeader::period_us` is the number `arena::timer_try_process`
12366    /// compares `elapsed_us` against, so this writes the period the
12367    /// DISPATCHER honours rather than a second copy of it (RFC-0019). The C
12368    /// entry point `rcl_timer_exchange_period` also keeps
12369    /// `rcl_timer_t::period_ns` in step, because that field is the
12370    /// registration input a later `rclc_executor_add_timer` would re-read.
12371    ///
12372    /// `elapsed_us` is deliberately NOT rewound, which is rcl's own behaviour:
12373    /// `rcl_timer_exchange_period` swaps the period and touches nothing else,
12374    /// so a timer shortened below its accumulated elapsed time becomes ready
12375    /// at once and one lengthened past it simply waits longer. A caller that
12376    /// wants the new period to start fresh calls
12377    /// [`reset_timer`](Self::reset_timer) after it.
12378    ///
12379    /// phase-417 W5.c — the Rust half of `c:timer_exchange_period`, the last
12380    /// timer row the C ledger filed as `gap`. The answer lives here and only
12381    /// the spelling lives in the wrapper, the same split
12382    /// [`timer_elapsed_us`](Self::timer_elapsed_us) made.
12383    pub(crate) fn exchange_timer_period_us(
12384        &mut self,
12385        id: HandleId,
12386        new_period_us: u64,
12387    ) -> Option<u64> {
12388        let offset = self
12389            .entries
12390            .get(self.live_slot(id))
12391            .and_then(|e| e.as_ref())
12392            .filter(|m| matches!(m.kind, EntryKind::Timer))?
12393            .offset;
12394        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12395        // SAFETY: same layout invariant as `timer_period_us`.
12396        let header = unsafe { &mut *(arena_ptr.add(offset) as *mut TimerHeader) };
12397        let old_period_us = header.period_us;
12398        header.period_us = new_period_us;
12399        Some(old_period_us)
12400    }
12401
12402    /// Set a timer's overrun policy. Timers default to
12403    /// [`TimerOverrunPolicy::Skip`]; switch to
12404    /// [`TimerOverrunPolicy::CatchUp`] for timers whose every activation
12405    /// is a unit of work that must not be lost.
12406    pub fn set_timer_overrun_policy(
12407        &mut self,
12408        id: HandleId,
12409        policy: TimerOverrunPolicy,
12410    ) -> Result<(), NodeError> {
12411        let meta = self
12412            .entries
12413            .get(self.live_slot(id))
12414            .and_then(|e| e.as_ref())
12415            .ok_or(NodeError::BufferTooSmall)?;
12416        if !matches!(meta.kind, EntryKind::Timer) {
12417            return Err(NodeError::BufferTooSmall);
12418        }
12419        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
12420        // SAFETY: same layout invariant as `cancel_timer`.
12421        let header = unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
12422        header.overrun_policy = policy;
12423        Ok(())
12424    }
12425
12426    /// Periods this timer missed and dropped under
12427    /// [`TimerOverrunPolicy::Skip`], or `None` if the handle
12428    /// is not a valid timer.
12429    ///
12430    /// Monotonic and saturating. A growing count is the on-target signal
12431    /// that a tier is not keeping up with its declared cadence — the
12432    /// symptom an external observer would otherwise have to infer by
12433    /// differencing timestamps.
12434    pub fn timer_overruns(&self, id: HandleId) -> Option<u32> {
12435        let meta = self
12436            .entries
12437            .get(self.live_slot(id))
12438            .and_then(|e| e.as_ref())
12439            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12440        let arena_ptr = self.arena.as_ptr() as *const u8;
12441        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12442        Some(header.overruns)
12443    }
12444
12445    /// Microseconds accumulated since this timer last fired, or `None` if the
12446    /// handle is not a valid timer.
12447    ///
12448    /// This is `TimerHeader::elapsed_us` — the SAME counter
12449    /// `arena::timer_try_process` compares against the period and rewinds on
12450    /// every activation, so it is the executor's own answer rather than a
12451    /// second one derived from a clock. `None` is not "zero elapsed": a caller
12452    /// that cannot tell them apart reports a timer that has just fired and a
12453    /// handle that is not a timer identically.
12454    ///
12455    /// phase-417 W5.c — added because the state was already here and nothing
12456    /// exposed it, which is why `c:timer_get_time_since_last_call` and
12457    /// `c:timer_is_ready` were both filed as gaps. The C forwarders
12458    /// (`rcl_timer_get_time_since_last_call`, `rcl_timer_is_ready`) read
12459    /// this; RFC-0019 puts the answer in Rust and only the spelling in the
12460    /// wrapper.
12461    pub(crate) fn timer_elapsed_us(&self, id: HandleId) -> Option<u64> {
12462        let meta = self
12463            .entries
12464            .get(self.live_slot(id))
12465            .and_then(|e| e.as_ref())
12466            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12467        let arena_ptr = self.arena.as_ptr() as *const u8;
12468        // SAFETY: same layout invariant as `timer_period_us`.
12469        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12470        Some(header.elapsed_us)
12471    }
12472
12473    /// Would this timer fire on the next dispatch pass? `None` if the handle
12474    /// is not a valid timer.
12475    ///
12476    /// The predicate is `arena::timer_try_process`'s own guard, in the same
12477    /// order: a cancelled timer is never ready, a one-shot that already fired
12478    /// is never ready again, and otherwise readiness is `elapsed >= period`.
12479    /// Keeping the two in one shape is the point — a readiness answer that
12480    /// disagrees with the dispatcher is worse than no answer at all.
12481    pub(crate) fn timer_is_ready(&self, id: HandleId) -> Option<bool> {
12482        let meta = self
12483            .entries
12484            .get(self.live_slot(id))
12485            .and_then(|e| e.as_ref())
12486            .filter(|m| matches!(m.kind, EntryKind::Timer))?;
12487        let arena_ptr = self.arena.as_ptr() as *const u8;
12488        // SAFETY: same layout invariant as `timer_period_us`.
12489        let header = unsafe { &*(arena_ptr.add(meta.offset) as *const TimerHeader) };
12490        if header.cancelled || (header.oneshot && header.fired) {
12491            return Some(false);
12492        }
12493        Some(header.elapsed_us >= header.period_us)
12494    }
12495
12496    /// Nanoseconds until this timer next fires — NEGATIVE when it is overdue.
12497    /// `None` if the handle is not a valid timer.
12498    ///
12499    /// THE computation, and it has to be: rcl's own pair are
12500    /// `next_call_time` and `next_call_time - now`, so upstream cannot have
12501    /// them disagree either. Before this it lived in `nros-c`
12502    /// (~~`remaining_period_ns`~~ + `time_until_next_call_ns_of`), and the C++
12503    /// half of `cpp:Timer::time_until_trigger` would have been a second
12504    /// derivation of the same subtraction in a second crate — the shape
12505    /// CLAUDE.md's "fix the CLASS, add ONE shared helper rather than a second
12506    /// spelling" rule names. `nros-c` forwards here now; so does `nros-cpp`.
12507    ///
12508    /// **The unit is nanoseconds and the RESOLUTION is microseconds.** The
12509    /// arena's timer accounting is microsecond-based, so this is a
12510    /// microsecond quantity scaled by 1000. The unit is rcl's; the resolution
12511    /// is ours.
12512    ///
12513    /// Saturating rather than wrapping: `period_us` and `elapsed_us` are both
12514    /// `u64`, so their difference in nanoseconds can leave `i64` in either
12515    /// direction, and a wrap would turn "overdue by a lot" into "due in a
12516    /// long time" — the sign is the whole answer here.
12517    pub fn timer_time_until_next_call_ns(&self, id: HandleId) -> Option<i64> {
12518        let period_us = self.timer_period_us(id)?;
12519        let elapsed_us = self.timer_elapsed_us(id)?;
12520        let delta_ns = (period_us as i128 - elapsed_us as i128).saturating_mul(1_000);
12521        Some(if delta_ns > i64::MAX as i128 {
12522            i64::MAX
12523        } else if delta_ns < i64::MIN as i128 {
12524            i64::MIN
12525        } else {
12526            delta_ns as i64
12527        })
12528    }
12529
12530    // ========================================================================
12531    // spin_once (three-phase: readiness -> trigger -> dispatch)
12532    // ========================================================================
12533
12534    /// Drive I/O and dispatch registered callbacks once.
12535    ///
12536    /// Three-phase execution:
12537    /// 1. **Readiness scan** — query each handle's `has_data()`.
12538    /// 2. **Trigger evaluation** — check if the executor-level trigger passes.
12539    /// 3. **Dispatch** — invoke callbacks according to their `InvocationMode`.
12540    ///
12541    /// Returns a [`SpinOnceResult`] with counts of processed items and errors.
12542    ///
12543    /// # Arguments
12544    /// * `timeout` — upper bound on the I/O wait. Saturated at
12545    ///   `i32::MAX` ms (~24 days) for the underlying transport call.
12546    ///
12547    /// Phase 84.D7: unified on `core::time::Duration`. The previous
12548    /// `timeout_ms: i32` signature had a latent footgun where
12549    /// `spin_once(-1)` silently froze timers while still polling I/O;
12550    /// `Duration` has no negative sentinel.
12551    /// Consecutive `drive_io` failures on the primary session (issue 0324).
12552    ///
12553    /// `0` means the last drive succeeded. A value that keeps climbing across
12554    /// spins is a session that is no longer doing I/O — router gone, lease
12555    /// expired, socket closed — which otherwise presents as a node that spins
12556    /// `Ok(())` forever while publishing nowhere and firing no callbacks.
12557    ///
12558    /// Transient failures happen, so a single non-zero reading is not a fault;
12559    /// a threshold (say, "more than a few consecutive spins") is the useful
12560    /// signal. Extra (bridge / multi-domain) sessions are best-effort and are
12561    /// deliberately NOT counted here.
12562    pub(crate) fn session_io_failures(&self) -> u32 {
12563        self.consecutive_io_failures
12564    }
12565
12566    /// Whether the primary session drove I/O successfully on the last spin.
12567    ///
12568    /// Convenience over [`ExecutorFfi::session_io_failures`](crate::executor::ffi::ExecutorFfi::session_io_failures) for the common
12569    /// "is my transport alive?" check.
12570    pub fn session_io_healthy(&self) -> bool {
12571        self.consecutive_io_failures == 0
12572    }
12573
12574    /// Whether the primary session is LOST: the peer is reachable and no
12575    /// longer holds it, so it will never do I/O again.
12576    ///
12577    /// On XRCE this is an Agent that restarted: it answers the session's
12578    /// liveness probe with "no session". The backend sends that probe by
12579    /// itself after `XRCE_SESSION_PROBE_MS` of silence (1000 ms by default),
12580    /// so a loop that only calls [`spin_once`](Self::spin_once) sees this turn
12581    /// `true` about a second after the new Agent is up, even on a link with no
12582    /// traffic. An Agent that is merely DOWN leaves it `false`: if the same
12583    /// Agent comes back, the session carries on.
12584    ///
12585    /// It does not clear. The remedy is to drop this executor and open a new
12586    /// one, then create the nodes and entities again. Over caller-supplied
12587    /// backing, [`open_in`](Self::open_in) with the same backing works once
12588    /// the old executor is dropped; the `alloc` [`open`](Self::open) family
12589    /// gives its default backing back on drop, so re-opening through it costs
12590    /// no new allocation either.
12591    pub fn session_lost(&self) -> bool {
12592        self.session_lost
12593    }
12594
12595    /// Drive I/O once, then dispatch EVERY callback that is ready — the tick
12596    /// primitive the rest of the family is built from.
12597    ///
12598    /// OURS-ONLY: rclcpp's `spin_once` executes the NEXT ready item
12599    /// and has no timeout; rclpy's is `spin_once(node, timeout_sec)`. Ours is a
12600    /// blocking wait with a budget, which an RTOS task that must not spin-poll
12601    /// needs and which neither upstream has a verb for. What it DOES when work
12602    /// is ready is rclcpp's `spin_some` — the whole ready set, one pass
12603    /// — so [`spin_some`](Self::spin_some) is the drain verb and
12604    /// this is the waiting one.
12605    ///
12606    /// `timeout` is the upper bound on the I/O wait. It is
12607    /// carried in MICROSECONDS all the way to the park (an
12608    /// `as_millis()` here truncated `from_micros(500)` to `0`, and a zero
12609    /// timeout selects the non-blocking path, so a sub-millisecond `spin()`
12610    /// was a 100 % CPU loop with no warning); the conversion to whatever the
12611    /// platform primitive accepts happens once, at the park, and rounds UP.
12612    /// `Duration` has no negative sentinel, which is what the old
12613    /// `timeout_ms: i32` signature used to silently mean "freeze the timers
12614    /// and poll I/O forever".
12615    pub fn spin_once(&mut self, timeout: core::time::Duration) -> SpinOnceResult {
12616        let mut discarded = None;
12617        self.spin_once_capturing(timeout, &mut discarded)
12618    }
12619
12620    // RFC-0108 D9, issue 2675.
12621    /// [`spin_once`](Self::spin_once) through a raw pointer, for a caller
12622    /// whose callbacks may call back into this executor.
12623    ///
12624    /// A C or C++ callback reaches the executor again from its handle, a raw
12625    /// pointer, and derives a fresh reference each time. `spin_once(&mut
12626    /// self)` would hold a protected `&mut` across that callback, so any such
12627    /// re-entry is undefined behaviour. This entry holds none: the pass works
12628    /// from `this` and re-derives its reference after every callback. Every
12629    /// FFI spin entry calls this, never `spin_once`.
12630    ///
12631    /// # Safety
12632    /// `this` points at a live executor. For the whole call, nothing reaches
12633    /// the executor except through `this` (or a pointer derived from it, or
12634    /// the handle it was derived from) on this thread, and no reference to the
12635    /// executor is live in the caller.
12636    pub unsafe fn spin_once_raw(this: *mut Self, timeout: core::time::Duration) -> SpinOnceResult {
12637        let mut discarded = None;
12638        // SAFETY: the caller's contract is `pass`'s for an owned pass.
12639        unsafe { Self::pass(this, PassMode::Owned, timeout, &mut discarded) }
12640    }
12641
12642    /// [`spin_once`](Self::spin_once), plus the FIRST failing callback's
12643    /// error.
12644    ///
12645    /// phase-427 — [`SpinOnceResult`] counts errors and drops their values,
12646    /// and `SpinOnceResult` is `Copy`, so widening it to carry a
12647    /// (non-`Copy`, `alloc`-variant-bearing) [`TransportError`] would change a
12648    /// public type every consumer copies. The value is needed in exactly one
12649    /// place — `SpinOptions::stop_on_first_error`, where `spin` has to return
12650    /// the first error rather than a count — so it is threaded out through an
12651    /// out-parameter that lives in the caller's frame. Nothing is added to
12652    /// `Executor`, so a no-alloc image pays nothing for it.
12653    ///
12654    /// `first_error` is written at most once: subsequent failures in the same
12655    /// pass are counted in the result and their values dropped, exactly as
12656    /// before.
12657    fn spin_once_capturing(
12658        &mut self,
12659        timeout: core::time::Duration,
12660        first_error: &mut Option<TransportError>,
12661    ) -> SpinOnceResult {
12662        // SAFETY: `self` is exclusive for the whole call, and an owned pass
12663        // never releases the executor's lock (`PassMode::Owned`), so nothing
12664        // else reaches the executor while it runs.
12665        unsafe { Self::pass(self, PassMode::Owned, timeout, first_error) }
12666    }
12667
12668    /// One pass, over a raw executor pointer (phase-509 P9b item 2, RFC-0108
12669    /// "As built in P9b"). See [`PassMode`]: an owned pass is the
12670    /// `spin_once` every image ran before; a shared pass releases the
12671    /// executor's lock around each user callback, and a band pass runs one
12672    /// worker's band.
12673    ///
12674    /// No `&mut Self` lives across a callback window: `s` is re-derived from
12675    /// `this` after each one, and nothing borrowed from the executor before a
12676    /// window is used after it.
12677    ///
12678    /// # Safety
12679    /// `this` points at a live executor. For `PassMode::Owned`, nothing else
12680    /// reaches it for the call. Otherwise the executor's lock is installed and
12681    /// held exactly once by the calling thread, and every other thread that
12682    /// reaches the executor takes the lock first.
12683    unsafe fn pass(
12684        this: *mut Self,
12685        mut mode: PassMode<'_>,
12686        timeout: core::time::Duration,
12687        first_error: &mut Option<TransportError>,
12688    ) -> SpinOnceResult {
12689        // SAFETY: the caller's contract; re-derived after every window.
12690        #[allow(unused_mut)]
12691        let mut s: &mut Self = unsafe { &mut *this };
12692        // Issue 1705 — releases deferred behind a dispatch that has since
12693        // finished are completed here, before this pass looks at the entries.
12694        s.reap_deferred_releases();
12695        // phase-509 P9b item 2 -- the lock this pass releases around each
12696        // user callback (and, item 3, around its park): only a shared or band
12697        // pass, and only when the lock can tell the callback's thread from
12698        // the others. `None` -- an owned pass, or no lock -- runs the whole
12699        // pass under the caller's hold.
12700        let window_lock = match mode {
12701            PassMode::Owned => None,
12702            _ => s.exec_lock.filter(|l| l.opens_windows()),
12703        };
12704        // phase-509 P9b item 2 -- the owned and shared passes run the
12705        // executor's own worker's prelude (sim time, services, jitter, the
12706        // park, the transport drive); a band pass runs its own clock and
12707        // (item 3) its own park.
12708        //
12709        // SAFETY: the caller's contract is the preludes'; `s` is not used
12710        // across the call and is derived again after it.
12711        let (now_us_this_spin, delta_us) = match &mut mode {
12712            PassMode::Band(w) => unsafe { Self::band_prelude(this, window_lock, w, timeout) },
12713            _ => unsafe { Self::owned_prelude(this, window_lock, timeout) },
12714        };
12715        // SAFETY: the prelude returns holding the lock again.
12716        s = unsafe { &mut *this };
12717        // phase-521 W8 (c) -- the park slot yielded to its framework's
12718        // scheduler: nothing is due (the bound was not zero) and nothing is
12719        // pending, so there is nothing to scan. The sched task runs again when its
12720        // work item is scheduled.
12721        if core::mem::take(&mut s.worker.park_yielded) {
12722            return SpinOnceResult::new();
12723        }
12724        // phase-509 P9b item 2 -- this pass's band (every level for the
12725        // one-level worker) and its slots. The scan, the sweep and the drain
12726        // see only these, so a worker never takes another band's work.
12727        let (level, band) = match &mode {
12728            PassMode::Band(w) => (w.level, w.band),
12729            _ => (s.worker.level, s.worker.band),
12730        };
12731        let band_mask = s.band_slots(level, band);
12732        let is_band_pass = matches!(mode, PassMode::Band(_));
12733        let window_thread = window_lock.and_then(|l| l.current_thread()).unwrap_or(0);
12734
12735        let arena_ptr = s.arena.as_mut_ptr() as *mut u8;
12736
12737        // Phase 1: Readiness scan (Phase 110.A.b — backed by FifoReadySet).
12738        //
12739        // `bits` carries data-readiness only (used by trigger eval +
12740        // by `InvocationMode::OnNewData`). `always_mask` carries the
12741        // `InvocationMode::Always` entries that fire regardless of
12742        // data presence. The dispatcher drains `bits | always_mask`
12743        // after the trigger passes. phase-509 P2 -- in dispatch-level
12744        // order (the sched context's bucket, and inside `Normal` the
12745        // node's rank), registration order (lowest bit first) among
12746        // equals, so an image whose nodes hold one rank is bit-identical
12747        // to the pre-refactor `for (i, meta) in entries.iter().enumerate()`
12748        // loop.
12749        use super::slot_mask::SlotMask;
12750        let mut bits = SlotMask::EMPTY;
12751        let mut count: usize = 0;
12752        let mut non_timer_mask = SlotMask::EMPTY;
12753        // Issue 2162 -- the guard conditions. A ready guard passes
12754        // `Trigger::Any` like a ready subscription does (rclc's
12755        // `rclc_executor_trigger_any` counts every handle), but an IDLE guard
12756        // never holds `Any` or `All` back, so it stays out of `non_timer_mask`.
12757        let mut guard_mask = SlotMask::EMPTY;
12758        let mut always_mask = SlotMask::EMPTY;
12759
12760        // phase-397 W3 (RFC-0084) — an ATTRIBUTED slot's readiness is pushed,
12761        // not probed. Its arrivals set its bit in the ready word (W2), so the
12762        // bit is read and `has_data` is not called. Three cases still ask:
12763        //
12764        // - a slot in `entity_recheck`, which may hold data no arrival will
12765        //   announce again (see the field);
12766        // - a subscription with a status-event callback (issue 2060,
12767        //   `entity_status_polled`), whose backend polls those events there;
12768        // - a slot whose backend cannot attribute (XRCE, uORB, a timer, a
12769        //   guard condition), exactly as before.
12770        //
12771        // The bit means the data ARRIVED, not that it is still PRESENT: an
12772        // arrival that races a drain may dispatch to an empty queue, and every
12773        // `try_process` already answers `Ok(false)` to that. A bit cleared
12774        // before its dispatch would lose a message; one that over-reports
12775        // costs one empty call.
12776        //
12777        // The word is taken AFTER the wait and the drive above, so it holds
12778        // every arrival that ended this spin's park, including those a
12779        // single-threaded backend delivered inside `drive_io`. One that lands
12780        // after the take stays in the word and has signalled the wake, so the
12781        // next spin does not park on it.
12782        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
12783        let (attributed, arrived, recheck) = {
12784            let attributed = s.entity_attributed;
12785            // phase-509 P9b item 2 -- only this band's arrivals: another
12786            // band's bits stay in the word for its worker.
12787            let arrived = s
12788                .wake_ctx
12789                .as_ref()
12790                .map_or(SlotMask::EMPTY, |ctx| take_band_bits(&ctx.ready, band_mask));
12791            let recheck = s.entity_recheck & band_mask;
12792            s.entity_recheck = s.entity_recheck.and_not(band_mask);
12793            // Issue 2060 — a slot whose status events are polled from
12794            // `has_data` is asked every pass, like a recheck that never
12795            // drains. It is folded in AFTER the clear, so it never leaks into
12796            // `entity_recheck` and leaves the moment its entry is released.
12797            let recheck = recheck | (s.entity_status_polled & band_mask);
12798            (attributed, arrived & attributed, recheck & attributed)
12799        };
12800        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
12801        let (attributed, arrived, recheck) = (SlotMask::EMPTY, SlotMask::EMPTY, SlotMask::EMPTY);
12802        // Attributed slots the scan could not settle (held mid-dispatch).
12803        let mut carry = SlotMask::EMPTY;
12804        let mut probes: u32 = 0;
12805
12806        for (i, meta) in s.entries.iter().enumerate() {
12807            let Some(meta) = meta else { continue };
12808            if !band_mask.test(i) {
12809                continue;
12810            }
12811            let bit = SlotMask::bit(i);
12812            if Self::slot_held(s.slot_tags, i) {
12813                carry |= (arrived | recheck) & bit;
12814                continue;
12815            }
12816            {
12817                let pushed = attributed.test(i);
12818                let ready = if pushed && arrived.test(i) {
12819                    true
12820                } else if pushed && !recheck.test(i) {
12821                    false
12822                } else {
12823                    probes = probes.wrapping_add(1);
12824                    let data_ptr = unsafe { arena_ptr.add(meta.offset) as *const u8 };
12825                    unsafe { (meta.has_data)(data_ptr) }
12826                };
12827                if ready {
12828                    bits |= bit;
12829                }
12830                match meta.kind {
12831                    EntryKind::Timer => {}
12832                    EntryKind::GuardCondition => guard_mask |= bit,
12833                    _ => non_timer_mask |= bit,
12834                }
12835                if matches!(meta.invocation, InvocationMode::Always) {
12836                    always_mask |= bit;
12837                }
12838                count += 1;
12839            }
12840        }
12841        // Issue 2146 -- a DEFERRED slot that is ready is queued for the
12842        // host's drain (and its notifier called), never dispatched here, and
12843        // takes no part in the trigger. Taken out before the recheck below:
12844        // the drain asks for the recheck when it runs the callback.
12845        if !s.deferred_mask.is_empty() {
12846            bits = s.defer_ready(bits);
12847            non_timer_mask = non_timer_mask.and_not(s.deferred_mask);
12848            always_mask = always_mask.and_not(s.deferred_mask);
12849        }
12850        // Every attributed slot that was ready is asked again next spin: a
12851        // dispatch takes what one call takes, and a trigger that does not
12852        // pass dispatches nothing, so either may leave data behind.
12853        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
12854        {
12855            s.entity_recheck |= carry | (bits & attributed);
12856            s.readiness_probes = s.readiness_probes.wrapping_add(probes);
12857        }
12858        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
12859        let _ = (carry, probes);
12860
12861        // phase-462 W5b — an armed deadline row's arrival evidence.
12862        if !bits.is_empty() && !s.age_table.is_empty() {
12863            super::monitor::credit_arrivals(s.age_table, bits);
12864        }
12865
12866        let snapshot = ReadinessSnapshot { bits, count };
12867
12868        // Phase 2: Trigger evaluation
12869        let trigger_passes = match &s.trigger {
12870            // Issue 2162 -- a triggered guard beside an idle subscription
12871            // waited for unrelated traffic (possibly forever) while `Any`
12872            // read only `non_timer_mask`. The `non_timer_mask == 0` arm is
12873            // unchanged: a timer/guard-only executor still passes every spin.
12874            Trigger::Any => {
12875                bits.intersects(non_timer_mask | guard_mask) || non_timer_mask.is_empty()
12876            }
12877            Trigger::All => bits.contains_all(non_timer_mask),
12878            Trigger::One(id) => snapshot.is_ready(*id),
12879            Trigger::AllOf(set) => snapshot.all_ready(*set),
12880            Trigger::AnyOf(set) => snapshot.any_ready(*set),
12881            Trigger::Always => true,
12882            Trigger::Predicate(f) => f(&snapshot),
12883            Trigger::RawPredicate { callback, context } => {
12884                // Convert ReadinessSnapshot bitmask to a bool array for the C callback
12885                let mut ready_array = [false; MAX_CALLBACK_SLOTS];
12886                for (i, slot) in ready_array
12887                    .iter_mut()
12888                    .enumerate()
12889                    .take(snapshot.count.min(MAX_CALLBACK_SLOTS))
12890                {
12891                    *slot = snapshot.bits.test(i);
12892                }
12893                // SAFETY: The callback and context are provided by the C API caller.
12894                // The ready_array is valid for snapshot.count elements.
12895                unsafe { callback(ready_array.as_ptr(), snapshot.count, *context) }
12896            }
12897        };
12898
12899        if !trigger_passes {
12900            // Timers still need delta accumulation even when trigger doesn't pass
12901            //
12902            // phase-8 — `.enumerate()` (rather than a bare `.flatten()`) because
12903            // `try_process` now carries the entry's slot index for the callback
12904            // trace hooks. This sweep FIRES timer callbacks, so it is a real
12905            // dispatch path and must attribute them like the drain below does.
12906            //
12907            // phase-474 I6 -- and it must TIME them like the drain does. This
12908            // is the path every timer takes on a node that also subscribes
12909            // (the default `Trigger::Any` fails whenever no subscription has
12910            // a sample), and it measured nothing, so `max-latency-runtime`
12911            // never judged a timer path: the safety island's 250 ms overrun of
12912            // a 206 ms path stored no verdict. One clock read before and one
12913            // after each timer's `try_process`, only when a latency contract
12914            // exists and a clock is injected; the publish-count snapshot is a
12915            // fixed array on the stack, nothing allocates. The measured span
12916            // is callback entry to exit, as in the drains; release jitter is
12917            // `release-jitter-runtime`'s.
12918            let mon_table = s.monitor_table;
12919            // phase10-B3 -- the route rule reads the same clock and snapshot:
12920            // a timer tick is where a sampled route's output is published.
12921            let lat_clock = s.clock_us_fn.filter(|_| {
12922                mon_table.iter().any(|m| m.max_latency_ms > 0)
12923                    || super::monitor::route_active(mon_table)
12924            });
12925            for i in 0..s.entries.len() {
12926                let Some(meta) = s.entries[i].as_ref() else {
12927                    continue;
12928                };
12929                if matches!(meta.kind, EntryKind::Timer)
12930                    && band_mask.test(i)
12931                    && !Self::slot_held(s.slot_tags, i)
12932                {
12933                    let data_ptr = unsafe { arena_ptr.add(meta.offset) };
12934                    let try_process = meta.try_process;
12935                    let counts_before = snapshot_pub_counts(mon_table, lat_clock.is_some());
12936                    let start_us = lat_clock.map(|c| c());
12937                    Self::begin_dispatch(s.slot_tags, i);
12938                    // phase-509 P9b item 2 -- the callback window: see the
12939                    // drain below.
12940                    let mut rec = super::exec_lock::Running {
12941                        slot: i,
12942                        thread: window_thread,
12943                        next: core::ptr::null_mut(),
12944                    };
12945                    let window = window_lock.map(|l| {
12946                        // SAFETY: `rec` outlives the window and is unlinked
12947                        // under the lock right after it.
12948                        unsafe { s.link_running(&mut rec) };
12949                        super::exec_lock::Window::open(l)
12950                    });
12951                    // phase-463 W7 -- the host profile times this sweep too:
12952                    // it is the path every timer of a node that also
12953                    // subscribes takes (see above), so missing it measured
12954                    // the talker's timer at zero invocations.
12955                    //
12956                    // The OFF arm is the original `let _ =`, untouched, and
12957                    // that is MEASURED rather than tidy: every binding tried
12958                    // in its place (`let _p`, `let p; drop(p)`) moved
12959                    // `spin_once_capturing` by 49-64 B in the Zephyr image
12960                    // (phase-463 W5 I3c). Hence the second `unsafe` block,
12961                    // recorded in the unsafe census.
12962                    #[cfg(not(feature = "profile-mode"))]
12963                    let _ = unsafe { try_process(data_ptr, delta_us, i as u8) };
12964                    #[cfg(feature = "profile-mode")]
12965                    {
12966                        super::profile::dispatch_begin(arena_ptr as usize, i);
12967                        let processed = unsafe { try_process(data_ptr, delta_us, i as u8) };
12968                        super::profile::dispatch_end(matches!(processed, Ok(true)));
12969                    }
12970                    // Read before the lock is taken back, so a wait for it
12971                    // is not counted as the callback's latency.
12972                    let swept_end_us = start_us.and(lat_clock).map(|c| c());
12973                    let windowed = window.is_some();
12974                    drop(window);
12975                    // RFC-0108 D9 (issue 2675) -- derived again after EVERY
12976                    // callback, windowed or not: the callback may have called
12977                    // back into the executor from its own handle, which a
12978                    // reference held across it would alias.
12979                    // SAFETY: the lock (if any) is held again; nothing
12980                    // borrowed from the executor before the callback is used
12981                    // after it.
12982                    s = unsafe { &mut *this };
12983                    if windowed {
12984                        s.unlink_running(&mut rec);
12985                    }
12986                    if let (Some(end_us), Some(t0)) = (swept_end_us, start_us) {
12987                        let elapsed_us = end_us.saturating_sub(t0).min(u32::MAX as u64) as u32;
12988                        attribute_latency(mon_table, true, &counts_before, elapsed_us);
12989                        let hook = s.reaction_hook.filter(|_| s.violations.counts.armed);
12990                        let violations = &mut s.violations;
12991                        super::monitor::route_judge(
12992                            mon_table,
12993                            &counts_before,
12994                            end_us,
12995                            |row, v, record, react| {
12996                                if react {
12997                                    call_route_reaction(hook, mon_table, row, &v, end_us);
12998                                }
12999                                if record {
13000                                    violations.record(v)
13001                                }
13002                            },
13003                        );
13004                    }
13005                    s.finish_dispatch(i);
13006                }
13007            }
13008
13009            // phase-509 P9b item 2 -- the executor-wide chores below are the
13010            // executor's own worker's. Issue 2020 -- the band's own
13011            // components' ticks are the band's.
13012            if is_band_pass {
13013                // SAFETY: the pass's contract; `s` is not used after it.
13014                unsafe { Self::tick_components(this, Some(level)) };
13015                return SpinOnceResult::new();
13016            }
13017
13018            // Parameter services live outside the arena and must be processed
13019            // regardless of trigger state, otherwise ROS 2 param queries time out.
13020            #[cfg(feature = "param-store")]
13021            {
13022                #[allow(unused_mut)] // only the services add to it
13023                let mut handled = 0usize;
13024                #[cfg(feature = "param-services")]
13025                if let Some(params) = &mut s.params {
13026                    {
13027                        let crate::param_store::ParamState {
13028                            server,
13029                            services,
13030                            buffers,
13031                            staged,
13032                            ..
13033                        } = &mut **params;
13034                        // phase-426 W3 — one set per node; every set is pumped,
13035                        // because `ros2 param list` addresses each node's own
13036                        // six and a set nobody polls times out.
13037                        //
13038                        // Issue 1270 -- all of them through ONE buffer pair.
13039                        // Issue 1271 -- a request that got no reply is logged
13040                        // inside, once per service; there is no error to drop.
13041                        if let Some(buffers) = buffers {
13042                            for set in services.iter_mut() {
13043                                handled += set.process(server, staged, buffers);
13044                            }
13045                        }
13046                    }
13047                }
13048                // phase-425 W3b — a `ros2 param set … use_sim_time true` arrives
13049                // through this path.
13050                s.note_param_services_ran(handled);
13051            }
13052
13053            // Same treatment for lifecycle services — `ros2 lifecycle get`
13054            // must succeed even when no callbacks fired this tick.
13055            //
13056            // Issue 1587 — `process` also drains the state machine's
13057            // announcement queue onto `~/transition_event`, so a transition
13058            // triggered from application code between two spins (autostart is
13059            // the common one) reaches a watching supervisor here.
13060            // SAFETY: see the matching invariant on the later call site.
13061            #[cfg(feature = "lifecycle-services")]
13062            for lc in s.lifecycle.iter_mut() {
13063                let _ = unsafe { lc.state.process() };
13064            }
13065
13066            // phase-474 I7 -- an idle spin is the natural slot for the queued
13067            // reports.
13068            s.flush_violation_reports();
13069
13070            return SpinOnceResult::new();
13071        }
13072
13073        // Phase 2.5: LET pre-sample (only when LogicalExecutionTime)
13074        //
13075        // Sample all subscription data into entry buffers BEFORE dispatching
13076        // any callbacks. This ensures all callbacks in this cycle see a
13077        // consistent snapshot of data from the same point in time.
13078        // Services are NOT pre-sampled (request-reply is sequential).
13079        if matches!(s.semantics, ExecutorSemantics::LogicalExecutionTime) {
13080            for (i, meta) in s.entries.iter().enumerate() {
13081                let Some(meta) = meta else { continue };
13082                if matches!(meta.kind, EntryKind::Subscription)
13083                    && band_mask.test(i)
13084                    && !Self::slot_held(s.slot_tags, i)
13085                {
13086                    let data_ptr = unsafe { arena_ptr.add(meta.offset) };
13087                    unsafe { (meta.pre_sample)(data_ptr) };
13088                }
13089            }
13090        }
13091
13092        // Phase 3: Dispatch (Phase 110.C — bucketed by SC.priority).
13093        //
13094        // Two ready-set families, each split across `Priority::COUNT`
13095        // buckets (Critical / Normal / BestEffort). Per-entry SC
13096        // `class` selects FIFO bitmap vs EDF heap; SC `priority`
13097        // selects the bucket within. Drain order:
13098        //   for each bucket in priority order (Critical first):
13099        //     drain EDF heap (deadline-priority), then FIFO bitmap
13100        //     (registration-order)
13101        // Default workloads — every entry on the auto-default Fifo SC
13102        // (Normal priority) — populate only `fifo[Normal]`, so
13103        // dispatch order is bit-identical to 110.B.b for those.
13104        const NB: usize = super::sched_context::Priority::COUNT;
13105        let mut result = SpinOnceResult::new();
13106        // TEMPORARY (phase-554 W3 slice C deletes it) -- a zero-node image's
13107        // waiting executor-level open (`open_pending_on_configured_name`).
13108        // `spin` and `spin_some` ran it already and returned its error; a bare
13109        // `spin_once` reaches it here and counts it, loudly.
13110        if s.primary_node_hook.is_some() && s.nodes.is_empty() {
13111            if let Err(e) = s.open_pending_on_configured_name() {
13112                nros_log::log_error!(
13113                    nros_log::get_logger("nros"),
13114                    "spin: an executor-level publisher waiting for this image's node \
13115                     (the /diagnostics reporter) could not be opened: {:?}",
13116                    e
13117                );
13118                result.setup_errors += 1;
13119                if first_error.is_none()
13120                    && let NodeError::Transport(t) = e
13121                {
13122                    *first_error = Some(t);
13123                }
13124            }
13125        }
13126        // phase-509 P2 (RFC-0108 D2) -- the FIFO half is ordered by dispatch
13127        // level: a bucket's reserved level, or `1 + rank` inside `Normal`, the
13128        // rank being the one the entry's node was seeded with. Equal levels
13129        // keep registration order, so an image with one rank is unchanged.
13130        let mut fifo: super::ready_set::RankedFifoSet<{ MAX_CALLBACK_SLOTS }> =
13131            super::ready_set::RankedFifoSet::new();
13132        let mut edf: super::ready_set::BucketedEdfSet<NB, { MAX_CALLBACK_SLOTS }> =
13133            super::ready_set::BucketedEdfSet::new();
13134        let active_mask = bits | always_mask;
13135
13136        // Phase 110.E — refill any Sporadic SC budgets at period
13137        // boundaries before deciding what to dispatch this cycle.
13138        // Refill is polled (not ISR-driven) — coarse but correct
13139        // upper-bound bandwidth limiter.
13140        // phase-359 W4 — was `#[cfg(feature = "std")]` with NO no_std arm, so
13141        // polled Sporadic budgets never refilled on embedded: they exhausted
13142        // once and stayed exhausted. That was a consequence of "no clock on
13143        // no_std", which is false whenever a `clock_us` hook is injected. Now it
13144        // runs on either flavour when a clock exists, and is skipped when none
13145        // does — identical to today's behaviour in that case.
13146        if let Some(now_us) = now_us_this_spin {
13147            let now_ms = now_us / 1000;
13148            // issue 0736 — REFILL only. This used to also charge the cycle's
13149            // `delta_us` as the per-SC consumption estimate ("worst-case
13150            // attribution", pending a higher-precision clock hook). That hook
13151            // landed, and the attribution was not merely coarse: `delta_us` is
13152            // the wall-clock gap between spins, not CPU the callbacks spent, so
13153            // wherever the gap exceeds the budget the SC is exhausted on every
13154            // spin regardless of what it ran. Consumption is charged from
13155            // measured callback runtime in `consume_dispatch_runtime_us`.
13156            for slot in s.sporadic_states.iter_mut().flatten() {
13157                let _ = slot.refill(now_ms);
13158            }
13159        }
13160
13161        for i in 0..s.entries.len() {
13162            if !active_mask.test(i) {
13163                continue;
13164            }
13165            let sc_idx = s.sched_context_bindings[i].0 as usize;
13166            let sc_class_priority_deadline = s
13167                .sched_contexts
13168                .get(sc_idx)
13169                .and_then(|s| s.as_ref())
13170                .map(|sc| {
13171                    (
13172                        sc.class,
13173                        sc.priority.index(),
13174                        sc.deadline_us.get().map(|nz| nz.get()).unwrap_or(u32::MAX),
13175                    )
13176                });
13177            let (sc_class, bucket, deadline_us) = sc_class_priority_deadline.unwrap_or((
13178                super::sched_context::SchedClass::Fifo,
13179                super::sched_context::Priority::Normal.index(),
13180                u32::MAX,
13181            ));
13182            // Phase 110.E — Sporadic SC dispatch is suppressed when
13183            // its budget is exhausted. Atomic path (110.E.b PlatformTimer
13184            // refill) takes precedence when registered; polled path
13185            // (cycle-level delta_us attribution) handles the unregistered
13186            // case. Either way, exhausted budget skips dispatch.
13187            if matches!(sc_class, super::sched_context::SchedClass::Sporadic) {
13188                #[cfg(feature = "alloc")]
13189                let atomic_has_budget = s
13190                    .sporadic_atomic_states
13191                    .get(sc_idx)
13192                    .and_then(|s| s.as_ref())
13193                    .map(|(state, _)| state.has_budget());
13194                #[cfg(not(feature = "alloc"))]
13195                let atomic_has_budget: Option<bool> = None;
13196                let has_budget = match atomic_has_budget {
13197                    Some(b) => b,
13198                    None => s
13199                        .sporadic_states
13200                        .get(sc_idx)
13201                        .and_then(|s| s.as_ref())
13202                        .map(|s| s.budget_remaining_us > 0)
13203                        .unwrap_or(true),
13204                };
13205                if !has_budget {
13206                    // issue 0736 — keep the TIMER'S CLOCK honest even while the
13207                    // budget gates its dispatch.
13208                    //
13209                    // A timer's `elapsed_us` only advances inside
13210                    // `timer_try_process`, which is reached only when the entry
13211                    // is DISPATCHED, and each dispatch is handed just THIS
13212                    // cycle's `delta_us`. So every cycle skipped here was
13213                    // dropped from the timer's sense of time: it did not fire,
13214                    // it did not learn that its period had passed, and — because
13215                    // the overrun counter is driven by that same `elapsed_us` —
13216                    // it did not count the activation it missed.
13217                    //
13218                    // That is why the throttle was invisible. Measured on
13219                    // nuttx-arm/rust: ~238 activations lost against ~40
13220                    // reported, so five in six missed firings were unaccounted
13221                    // ANYWHERE. The sched task ran at a quarter of its declared rate
13222                    // and the only honest signal was the delivery count itself.
13223                    //
13224                    // Advancing the clock here does not dispatch anything and
13225                    // does not defeat the budget. It makes the entry's own
13226                    // accounting independent of whether the executor CHOSE to
13227                    // run it, which is the property every "did this meet its
13228                    // declaration?" question needs, and it lets the existing
13229                    // `Skip` policy count the backlog and the existing
13230                    // `timer-overrun-runtime` rule report it.
13231                    if let Some(meta) = s.entries[i].as_ref()
13232                        && matches!(meta.kind, EntryKind::Timer)
13233                    {
13234                        // SAFETY: a Timer entry's arena slot holds a
13235                        // `TimerEntry<F>`, whose leading layout IS
13236                        // `TimerHeader` — the same cast the overrun reporter
13237                        // one screen up already relies on.
13238                        let header =
13239                            unsafe { &mut *(arena_ptr.add(meta.offset) as *mut TimerHeader) };
13240                        // Issue 1321 — on the TIMER'S clock, not the
13241                        // executor's. This line read
13242                        // `header.elapsed_us += delta_us`, which is wall
13243                        // microseconds: for a `Ros` timer that advanced a
13244                        // simulated-time counter by wall time, so a paused
13245                        // `/clock` no longer paused the timer — the one
13246                        // property a ROS-time timer has. Unbounded, unlike
13247                        // 1321's park bound, because it can fire a callback
13248                        // that no clock step earned.
13249                        super::arena::timer_advance_without_dispatch(header, delta_us);
13250                    }
13251                    // issue 0736 — a budget skip used to be a bare `continue`,
13252                    // which is the silent-drop shape 0737 gated one layer out:
13253                    // the entry is simply not dispatched and nothing anywhere
13254                    // says so, so a permanently starved sched task is
13255                    // indistinguishable from an idle one. It took a hand-run
13256                    // 45 s image and a per-executor probe to learn that this
13257                    // line was skipping 96 % of one sched task's spins.
13258                    // The rolling window catches a budget that THROTTLES; the
13259                    // streak below catches one that starves outright. issue
13260                    // 0736 needed both: the measured case skipped ~3 spins in
13261                    // 4 without ever reaching a streak, so the sched task ran at a
13262                    // quarter of its declared rate in silence.
13263                    if let Some((skips, total)) = s
13264                        .sporadic_states
13265                        .get_mut(sc_idx)
13266                        .and_then(|st| st.as_mut())
13267                        .and_then(|st| st.take_budget_window())
13268                    {
13269                        nros_log::log_warn!(
13270                            nros_log::get_logger("nros"),
13271                            "sporadic budget throttled sched context {}: {} of the last {} dispatch opportunities were skipped for want of budget. The declared budget_us/period_us cannot sustain this sched task's callbacks on this target.",
13272                            sc_idx,
13273                            skips,
13274                            total
13275                        );
13276                    }
13277                    if let Some(streak) = s
13278                        .sporadic_states
13279                        .get_mut(sc_idx)
13280                        .and_then(|st| st.as_mut())
13281                        .and_then(|st| st.note_budget_skip())
13282                    {
13283                        nros_log::log_warn!(
13284                            nros_log::get_logger("nros"),
13285                            "sporadic budget exhausted for {} consecutive spins (sched context {}): its callbacks are not being dispatched. Either the callback runtime exceeds the declared budget_us per period_us, or the declaration is unsatisfiable on this target.",
13286                            streak,
13287                            sc_idx
13288                        );
13289                    }
13290                    continue;
13291                }
13292                // Phase 110.E.b follow-up — per-callback runtime
13293                // accounting (replaces this cycle-level attribution)
13294                // is applied at dispatch time below via
13295                // `consume_dispatch_runtime_us`. We only update the
13296                // polled-path `SporadicState` (no_std fallback) here
13297                // because the atomic path now records actual
13298                // wall-clock per-callback runtime. The
13299                // `delta_us` over-attribution that previously hit the
13300                // atomic state was a worst-case bandwidth limiter;
13301                // per-callback measurement is strictly tighter.
13302                #[cfg(not(feature = "alloc"))]
13303                {
13304                    let _ = sc_idx; // polled-state path lives in
13305                    // `sporadic_states`; this branch is a no-op when
13306                    // the atomic path is enabled.
13307                }
13308            }
13309            // Phase 110.G — TT window gate, orthogonal to class.
13310            // Skips dispatch when the SC has a TT window AND the
13311            // current monotonic time is outside it. Both gates apply
13312            // independently — a Sporadic SC with a TT window must
13313            // pass both.
13314            if s.major_frame_us > 0 {
13315                let sc_opt = s.sched_contexts.get(sc_idx).and_then(|s| s.as_ref());
13316                if let Some(sc) = sc_opt {
13317                    let off = sc.tt_window_offset_us.get().map(|nz| nz.get()).unwrap_or(0);
13318                    let dur = sc
13319                        .tt_window_duration_us
13320                        .get()
13321                        .map(|nz| nz.get())
13322                        .unwrap_or(0);
13323                    if dur > 0 {
13324                        // Compute current phase within the major
13325                        // frame using the accumulated `delta_us` clock
13326                        // (std-only precise; no_std uses `delta_us`
13327                        // approximation from spin cadence).
13328                        // phase-359 W4 — the shared read. The no_std arm used
13329                        // to be `now_us = delta_us`, i.e. a per-spin INTERVAL
13330                        // used as an absolute phase clock, which the comment
13331                        // above called an approximation. It is now the real
13332                        // clock when one is injected, and falls back to the old
13333                        // approximation only when none is.
13334                        let now_us = now_us_this_spin.unwrap_or(delta_us);
13335                        let phase = (now_us % s.major_frame_us as u64) as u32;
13336                        let in_window = if off + dur <= s.major_frame_us {
13337                            phase >= off && phase < off + dur
13338                        } else {
13339                            // Window wraps the major frame boundary.
13340                            let end = (off as u64 + dur as u64) % s.major_frame_us as u64;
13341                            phase >= off || (phase as u64) < end
13342                        };
13343                        if !in_window {
13344                            continue;
13345                        }
13346                    }
13347                }
13348            }
13349            let is_edf = matches!(sc_class, super::sched_context::SchedClass::Edf);
13350            let job = super::types::ActiveJob {
13351                sort_key: if is_edf { deadline_us } else { i as u32 },
13352                desc_idx: i as super::types::DescIdx,
13353            };
13354            if is_edf {
13355                let _ = edf.insert_into(bucket, job);
13356            } else {
13357                let rank = s.slot_tags.get(i).map_or(0, |t| t.rank);
13358                let level = super::sched_context::Priority::from_index(bucket).dispatch_level(rank);
13359                // phase-509 P6 / P9b item 2 -- the scan saw only this pass's
13360                // band, so nothing it queued is another band's.
13361                debug_assert!(
13362                    s.worker.registering_level != super::scheduler::NO_OWNING_LEVEL
13363                        || band.contains(level)
13364                );
13365                let _ = fifo.insert_at(level, job);
13366            }
13367        }
13368        // phase-509 P3 -- every slot this pass has already settled: queued
13369        // above, or held back by a gate (budget, window, worker). A slot in
13370        // it never joins the pass again, so each entry runs at most once per
13371        // pass (a timer's clock advances by one `delta_us` per pass, and a
13372        // callback that readies itself cannot hold the pass forever).
13373        let mut settled: SlotMask = active_mask;
13374        // phase-509 P3 -- the LET semantics dispatch the pass's snapshot,
13375        // sampled before any callback ran; nothing joins it mid-pass.
13376        // A trigger narrower than "any" (`One`, `AllOf`, a predicate) chose
13377        // this pass's work from the scan; it stays the scan's.
13378        let repick = !matches!(s.semantics, ExecutorSemantics::LogicalExecutionTime)
13379            && matches!(s.trigger, Trigger::Any | Trigger::Always);
13380
13381        // SAFETY: each `desc_idx` we pop was set above only when the
13382        // corresponding `entries[i]` slot was `Some`; no Executor
13383        // mutation happens between that scan and this dispatch.
13384        let mut dispatch_one = |meta: &CallbackMeta,
13385                                desc_idx: usize,
13386                                arena_ptr: *mut u8,
13387                                delta_us: u64,
13388                                result: &mut SpinOnceResult| {
13389            // Phase 141.B.2 — capture T1 at subscription dispatch
13390            // entry. Probe pairs it with the most recent T0 from
13391            // `nros_rmw_runtime_wake_cb` (std + alloc variants)
13392            // and pushes T1 - T0 onto the ring buffer 141.C
13393            // drains. No-op when the probe feature is off or
13394            // no cycle reader is installed. Other entry kinds
13395            // (Service / Timer / GuardCondition) skip the probe
13396            // because the 141 acceptance is specifically
13397            // wake-to-subscription-dispatch latency.
13398            #[cfg(feature = "wake-latency-probe")]
13399            if matches!(meta.kind, EntryKind::Subscription) {
13400                super::wake_probe::on_dispatch();
13401            }
13402            let data_ptr = unsafe { arena_ptr.add(meta.offset) };
13403            // phase-8 — `desc_idx` is the entry slot index, threaded through so
13404            // the leaf hooks in `arena.rs` can name the callback they bracket.
13405            // `MAX_CALLBACK_SLOTS` is at most 256 (asserted in `crate::config`),
13406            // so the `as u8` cannot truncate a live slot.
13407            // phase-463 W7 — time the dispatch and attribute its publishes
13408            // (host `profile-mode` only). ONE call site for both builds, so no
13409            // second `unsafe` block; the binding is the only change an RTOS
13410            // image sees, and its loadable bytes measured identical (phase-463
13411            // W5 I3c, Zephyr cpp/talker).
13412            #[cfg(feature = "profile-mode")]
13413            super::profile::dispatch_begin(arena_ptr as usize, desc_idx);
13414            let processed = unsafe { (meta.try_process)(data_ptr, delta_us, desc_idx as u8) };
13415            #[cfg(feature = "profile-mode")]
13416            super::profile::dispatch_end(matches!(processed, Ok(true)));
13417            match processed {
13418                Ok(true) => match meta.kind {
13419                    EntryKind::Subscription => result.subscriptions_processed += 1,
13420                    EntryKind::Service
13421                    | EntryKind::ServiceClient
13422                    | EntryKind::ActionServer
13423                    | EntryKind::ActionClient => result.services_handled += 1,
13424                    EntryKind::Timer => result.timers_fired += 1,
13425                    EntryKind::GuardCondition => {}
13426                },
13427                Ok(false) => {}
13428                Err(e) => {
13429                    // phase-427 — the first one is kept, the rest are counted.
13430                    // `stop_on_first_error` is what reads it; when nobody
13431                    // asked, the `Option` is a local the optimiser drops.
13432                    if first_error.is_none() {
13433                        *first_error = Some(e);
13434                    }
13435                    match meta.kind {
13436                        EntryKind::Subscription => result.subscription_errors += 1,
13437                        EntryKind::Service
13438                        | EntryKind::ServiceClient
13439                        | EntryKind::ActionServer
13440                        | EntryKind::ActionClient => result.service_errors += 1,
13441                        EntryKind::Timer | EntryKind::GuardCondition => {}
13442                    }
13443                }
13444            }
13445        };
13446
13447        // Phase 110.E.b follow-up — per-callback runtime accounting
13448        // for Sporadic SCs. Wall-clock-measure each dispatch and
13449        // consume the elapsed microseconds from the bound SC's
13450        // atomic budget. This replaces the cycle-level over-
13451        // attribution that previously charged the FULL `delta_us`
13452        // against every Sporadic SC regardless of which entries
13453        // actually fired — accurate per-callback measurement is the
13454        // shape the design doc's per-callback runtime acceptance
13455        // calls out.
13456        //
13457        // phase-359 W10 — this was `feature = "std"`-gated, because it "needs a
13458        // `core::time::Instant`-equivalent monotonic clock ... until a
13459        // board-side monotonic-microsecond accessor lands". That accessor
13460        // landed: `now_us()` reads the platform monotonic counter on every
13461        // flavour. So per-callback sporadic accounting is no longer something
13462        // only a hosted build gets, and the no_std fallback to polled
13463        // `SporadicState` cycle deltas is no longer the only option on target.
13464        let consume_dispatch_runtime_us =
13465            |desc_idx: usize,
13466             elapsed_us: u32,
13467             sched_context_bindings: &[super::sched_context::SchedContextId],
13468             sched_contexts: &[Option<super::sched_context::SchedContext>],
13469             sporadic_states: &mut [Option<super::sched_context::SporadicState>],
13470             alive_slots: &mut [super::monitor::AliveSlot],
13471             #[cfg(feature = "alloc")] sporadic_atomic_states: &[Option<(
13472                portable_atomic_util::Arc<super::sched_context::AtomicSporadicState>,
13473                OpaqueTimerHandle,
13474            )>]| {
13475                let sc_idx = sched_context_bindings[desc_idx].0 as usize;
13476                // Alive supervision counts EVERY dispatch, before the class
13477                // gate below: a Fifo or time-triggered context can fall
13478                // silent exactly as a sporadic one can, and the rule that
13479                // notices must not be scoped to the class that happens to
13480                // carry a budget.
13481                if let Some(slot) = alive_slots.get_mut(sc_idx) {
13482                    slot.dispatches = slot.dispatches.wrapping_add(1);
13483                }
13484                let sc_class = sched_contexts
13485                    .get(sc_idx)
13486                    .and_then(|s| s.as_ref())
13487                    .map(|sc| sc.class)
13488                    .unwrap_or(super::sched_context::SchedClass::Fifo);
13489                if !matches!(sc_class, super::sched_context::SchedClass::Sporadic) {
13490                    return;
13491                }
13492                #[cfg(feature = "alloc")]
13493                if let Some((state, _)) =
13494                    sporadic_atomic_states.get(sc_idx).and_then(|s| s.as_ref())
13495                {
13496                    state.consume(elapsed_us);
13497                    // Unconditional, unlike the overrun record below: the
13498                    // budget is sized FROM this number, so it has to exist
13499                    // before the budget is right rather than only after it
13500                    // is wrong.
13501                    state.record_exec(elapsed_us);
13502                    // Phase 110.E.b — overrun detection. Cooperative
13503                    // single-thread can't preempt a runaway callback,
13504                    // so post-dispatch wall-clock comparison delivers
13505                    // the same observable signal as the design's
13506                    // oneshot-IRQ-and-cancel pattern, without needing
13507                    // a separate timer per SC. `budget_capacity_us` is
13508                    // the per-period budget the SC was sized against;
13509                    // any callback exceeding that has run past its
13510                    // bandwidth allotment.
13511                    if elapsed_us > state.budget_capacity_us {
13512                        state.record_overrun(elapsed_us - state.budget_capacity_us);
13513                    }
13514                }
13515                // issue 0736 — the POLLED state is charged unconditionally,
13516                // and it is the one that matters: `has_budget` prefers the
13517                // atomic state only when a refill timer was registered, which
13518                // no board or entry does. Before this, the alloc arm charged a
13519                // state nothing populated and the no_std arm discarded the
13520                // measurement outright (`let _ = (sc_idx, elapsed_us)`), so no
13521                // shipped image recorded per-callback runtime anywhere — while
13522                // the comment above claimed it did.
13523                if let Some(state) = sporadic_states.get_mut(sc_idx).and_then(|s| s.as_mut()) {
13524                    state.consume(elapsed_us);
13525                }
13526            };
13527
13528        // W3b.5 — post-dispatch contract checks. `lat_active` gates the
13529        // per-dispatch publish-count snapshot (attribution of dispatch
13530        // elapsed time to monitored publishers whose counter advanced);
13531        // `dl_active` gates elapsed measurement for deadline actions. The third
13532        // term used to be `cfg!(feature = "std")` — "std measures anyway for
13533        // the sporadic path" — which made a COMPILE-TIME flavour stand in for
13534        // "is there a clock". It is now the runtime question it always was.
13535        let mon_table = s.monitor_table;
13536        let lat_active = mon_table.iter().any(|m| m.max_latency_ms > 0);
13537        let dl_active = s.sched_contexts.iter().flatten().any(|sc| {
13538            sc.deadline_us.is_some()
13539                && !matches!(
13540                    sc.deadline_action,
13541                    super::sched_context::DeadlineAction::Ignore
13542                )
13543        });
13544        let mon_clock = s.clock_us_fn;
13545        // phase10-B3 -- the route rule needs the clock and the publish-count
13546        // snapshot, and nothing else; without a clock it judges nothing.
13547        let route_on = mon_clock.is_some() && super::monitor::route_active(mon_table);
13548        // phase-503 -- a late supervised route reacts at completion too; not
13549        // before the monitors are armed (phase-474 I2), as after the park.
13550        let route_hook = s.reaction_hook.filter(|_| s.violations.counts.armed);
13551        let counts_on = lat_active || route_on;
13552        // phase-359 W4 — one predicate, no cfg block. `cfg!` is an expression,
13553        // so the flavour difference stays a value instead of a branch: std
13554        // measures unconditionally because the sporadic runtime accounting
13555        // below (itself std-only) consumes the result, which is exactly what
13556        // the comment above described and what the four-arm sites encoded.
13557        let measure_us = counts_on || dl_active || mon_clock.is_some();
13558        // phase-359 W4 — ONE hoisted µs reader for the per-dispatch latency
13559        // measurement below. Hoisted because `now_us()` takes `&mut self` and
13560        // the dispatch loop already holds borrows; the std arm copies the epoch
13561        // (a `Copy` `Instant`) so reading inside the loop touches no `self`.
13562        // This is the last cfg pair in the timing path: the two call sites it
13563        // serves each had FOUR arms (start + elapsed, per flavour).
13564        let read_us = move || mon_clock.map(|c| c()).unwrap_or(0);
13565        // Deferred deadline-miss violations (the loop body holds an
13566        // immutable borrow of `s.entries`, so the ring is fed after).
13567        let mut deadline_misses: heapless::Vec<
13568            super::monitor::Violation,
13569            { super::monitor::MAX_VIOLATIONS },
13570        > = heapless::Vec::new();
13571        // SCs whose remaining callbacks this cycle are skipped
13572        // (`DeadlineAction::Skip`) — bitmask over SC slots.
13573        let mut skipped_scs: u64 = 0;
13574
13575        // For each priority bucket (Critical → Normal → BestEffort),
13576        // drain EDF first then FIFO so an EDF callback in this bucket
13577        // beats a FIFO peer at the same priority, but no lower-priority
13578        // entry runs while a higher-priority bucket has work pending.
13579        // Strict static priority across buckets; non-preemptive within
13580        // an in-flight callback (see Phase 110.D).
13581        // phase-509 P3 (RFC-0108 D2) -- one pick at a time. Each pick is the
13582        // most urgent queued job (bucket by bucket: EDF heap, then the ranked
13583        // FIFO's levels), and after each callback the ready set is merged
13584        // with what became ready while it ran, so an urgent callback made
13585        // ready by a less urgent one runs before the rest of the pass. Was a
13586        // drain of the scan's snapshot, bucket by bucket.
13587        loop {
13588            let mut next = None;
13589            for bucket in 0..NB {
13590                if let Some(job) = edf.pop_from(bucket) {
13591                    next = Some(job);
13592                    break;
13593                }
13594                let (level_lo, level_hi) =
13595                    super::sched_context::Priority::from_index(bucket).level_range();
13596                if let Some(job) = fifo.pop_in(level_lo, level_hi) {
13597                    next = Some(job);
13598                    break;
13599                }
13600            }
13601            let Some(job) = next else { break };
13602            let i = job.desc_idx as usize;
13603            let sc_idx = s.sched_context_bindings[i].0 as usize;
13604            if sc_idx < 64 && skipped_scs & (1u64 << sc_idx) != 0 {
13605                continue; // W3b.5 DeadlineAction::Skip containment
13606            }
13607            if let Some(meta) = s.entries[i]
13608                && !Self::slot_held(s.slot_tags, i)
13609            {
13610                let counts_before = snapshot_pub_counts(mon_table, counts_on);
13611                // Measured only when a consumer wants it, matching the
13612                // no_std arm this replaces — the std arm used to measure
13613                // unconditionally.
13614                let start_us = measure_us.then(read_us);
13615                let took_before = result.subscriptions_processed;
13616                Self::begin_dispatch(s.slot_tags, i);
13617                // phase-509 P9b item 2 (RFC-0108 "As built in P9b") -- the
13618                // callback window. With a lock that can tell threads apart,
13619                // a shared or band pass gives it for the callback, so a more
13620                // urgent worker (or an FFI caller) reaches the executor
13621                // while this callback runs. What crosses the window is a
13622                // copy of the entry's meta and its pinned arena address; the
13623                // running mark (`begin_dispatch`) keeps every other pass off
13624                // the entry and defers its release, and `rec` names this
13625                // thread as the one running it. `s` is derived again after.
13626                let mut rec = super::exec_lock::Running {
13627                    slot: i,
13628                    thread: window_thread,
13629                    next: core::ptr::null_mut(),
13630                };
13631                let window = window_lock.map(|l| {
13632                    // SAFETY: `rec` outlives the window and is unlinked under
13633                    // the lock right after it.
13634                    unsafe { s.link_running(&mut rec) };
13635                    super::exec_lock::Window::open(l)
13636                });
13637                dispatch_one(&meta, i, arena_ptr, delta_us, &mut result);
13638                let end_us = start_us.map(|_| read_us());
13639                let windowed = window.is_some();
13640                drop(window);
13641                // RFC-0108 D9 (issue 2675) -- derived again after EVERY
13642                // callback, windowed or not (see the timer sweep above).
13643                // SAFETY: the lock (if any) is held again; nothing borrowed
13644                // from the executor before the callback is used after it.
13645                s = unsafe { &mut *this };
13646                if windowed {
13647                    s.unlink_running(&mut rec);
13648                }
13649                let elapsed_us: Option<u32> = start_us
13650                    .zip(end_us)
13651                    .map(|(t0, t1)| t1.saturating_sub(t0))
13652                    .map(|d| d.min(u32::MAX as u64) as u32);
13653                // phase10-B3 -- a subscription dispatch takes its sample
13654                // first, so the dispatch start is the take.
13655                if route_on && let (Some(t0), Some(t1)) = (start_us, end_us) {
13656                    if result.subscriptions_processed != took_before {
13657                        super::monitor::route_take(mon_table, i, t0);
13658                    }
13659                    super::monitor::route_judge(
13660                        mon_table,
13661                        &counts_before,
13662                        t1,
13663                        |row, v, record, react| {
13664                            if react {
13665                                call_route_reaction(route_hook, mon_table, row, &v, t1);
13666                            }
13667                            if record {
13668                                let _ = deadline_misses.push(v);
13669                            }
13670                        },
13671                    );
13672                }
13673                if let Some(elapsed_us) = elapsed_us {
13674                    consume_dispatch_runtime_us(
13675                        i,
13676                        elapsed_us,
13677                        &s.sched_context_bindings[..],
13678                        &s.sched_contexts[..],
13679                        &mut s.sporadic_states[..],
13680                        &mut s.alive_slots[..],
13681                        #[cfg(feature = "alloc")]
13682                        &s.sporadic_atomic_states[..],
13683                    );
13684                }
13685                if let Some(elapsed_us) = elapsed_us {
13686                    attribute_latency(mon_table, lat_active, &counts_before, elapsed_us);
13687                    check_deadline_miss(
13688                        s.sched_contexts.get(sc_idx).and_then(|s| s.as_ref()),
13689                        sc_idx,
13690                        elapsed_us,
13691                        &mut deadline_misses,
13692                        &mut skipped_scs,
13693                        s.fault_fn,
13694                        s.reaction_hook,
13695                        end_us.unwrap_or(0),
13696                    );
13697                }
13698                s.finish_dispatch(i);
13699            }
13700            if repick {
13701                s.merge_mid_pass(&mut fifo, &mut edf, &mut settled, arena_ptr, band_mask);
13702            }
13703        }
13704
13705        // W3b.5 — feed deferred deadline misses into the violation ring.
13706        for v in deadline_misses {
13707            s.violations.record(v);
13708        }
13709        // phase-509 P9b item 2 -- the rules and the executor-wide chores
13710        // below are the executor's own worker's. Issue 2020 -- the band's
13711        // own components' ticks are the band's.
13712        if is_band_pass {
13713            // SAFETY: the pass's contract; `s` is not used after it.
13714            unsafe { Self::tick_components(this, Some(level)) };
13715            return result;
13716        }
13717
13718        // Issue #505 — same ring, same cycle. This runs AFTER dispatch,
13719        // unlike the windowed rate/age/latency rules at the top of the
13720        // spin: the activations it reports were dropped by the dispatch
13721        // that just happened, and a sched task that is stalling should not have
13722        // to wait for the next spin to say so.
13723        s.check_timer_overruns();
13724        s.check_release_jitter_rule();
13725        s.check_stack_headroom_rule();
13726        s.check_alive_supervision();
13727        // phase-474 I7 -- the queued /diagnostics reports, after this spin's
13728        // dispatches and rules, when the next timer leaves room for them.
13729        s.flush_violation_reports();
13730        // phase-474 I1 -- the opt-in drain-and-report hook, after every rule of
13731        // this spin has had its say.
13732        s.violations.drain_and_report();
13733
13734        // Process parameter services (outside the arena)
13735        #[cfg(feature = "param-store")]
13736        #[allow(unused_mut)] // only the services add to it
13737        let mut handled = 0usize;
13738        #[cfg(feature = "param-services")]
13739        if let Some(params) = &mut s.params {
13740            {
13741                let crate::param_store::ParamState {
13742                    server,
13743                    services,
13744                    buffers,
13745                    staged,
13746                    ..
13747                } = &mut **params;
13748                // phase-426 W3 -- one set per node; see the sibling site above,
13749                // including why nothing here can discard an error (1270/1271).
13750                if let Some(buffers) = buffers {
13751                    for set in services.iter_mut() {
13752                        let n = set.process(server, staged, buffers);
13753                        result.services_handled += n;
13754                        handled += n;
13755                    }
13756                }
13757            }
13758        }
13759        #[cfg(feature = "param-store")]
13760        s.note_param_services_ran(handled);
13761
13762        // Process lifecycle services (outside the arena).
13763        //
13764        // SAFETY: `change_state` dispatches a user-supplied C callback through a
13765        // raw function pointer stored in `LifecyclePollingNodeCtx`. The caller
13766        // of `register_lifecycle_services` guarantees the callback/context pair
13767        // stays live for as long as the executor (see that method's docs).
13768        #[cfg(feature = "lifecycle-services")]
13769        for lc in s.lifecycle.iter_mut() {
13770            if let Ok(n) = unsafe { lc.state.process() } {
13771                result.services_handled += n;
13772            }
13773        }
13774
13775        // Phase 258 (Track 2, 2a) — executor-owned component tick pass.
13776        // Mirrors `ExecutorNodeRuntime::run_ticks`: after the transport +
13777        // callbacks have been pumped, drive each enrolled component's `tick`
13778        // (service-client/action poll, etc.). `exec_ctx` hands the component
13779        // the whole executor as a raw `*mut Executor` so its tick can
13780        // reborrow it (the same disjoint-field raw-ptr pattern run_ticks
13781        // uses). Index-iterate over `Copy` slots so no borrow of
13782        // `s.component_slots` is held while `tick` runs (which aliases
13783        // `self` through `exec_ctx`).
13784        //
13785        // Issue 2020 -- only the components this pass's level owns.
13786        // SAFETY: the pass's contract; `s` is not used after the call.
13787        unsafe { Self::tick_components(this, None) };
13788
13789        result
13790    }
13791
13792    /// Phase 258 (Track 2, 2a) -- the component tick pass at the tail of a
13793    /// pass: each enrolled component's `tick` (service-client polls,
13794    /// action-server completion and feedback), with the whole executor as
13795    /// `exec_ctx`. Issue 2020 -- only the components the pass's level owns
13796    /// ([`Self::pass_ticks_owner`]): `band_level` is a band pass's level,
13797    /// `None` for the executor's own worker.
13798    ///
13799    /// The lock stays held across every tick, as it always was: a component
13800    /// is ticked by one level's thread only, and never by two at once.
13801    ///
13802    /// # Safety
13803    /// As [`Self::pass`], called with the lock held (when installed) and no
13804    /// reference to the executor live in the caller.
13805    unsafe fn tick_components(this: *mut Self, band_level: Option<u8>) {
13806        let exec_ctx = this as *mut core::ffi::c_void;
13807        let mut i = 0;
13808        loop {
13809            // SAFETY: re-derived after each tick, which aliases the executor
13810            // through `exec_ctx`; the slot is copied out, so no borrow of
13811            // `component_slots` is outstanding during the call.
13812            let s: &Self = unsafe { &*this };
13813            let Some(slot) = s.component_slots.get(i).copied() else {
13814                break;
13815            };
13816            i += 1;
13817            let owner = (slot.level != super::scheduler::NO_OWNING_LEVEL).then_some(slot.level);
13818            if !s.pass_ticks_owner(band_level, owner) {
13819                continue;
13820            }
13821            // SAFETY: `slot.state` is the leaked cell the matching `tick`
13822            // expects (enrolled via `enroll_component`); `exec_ctx` is a live
13823            // `*mut Executor`.
13824            unsafe { (slot.tick)(slot.state, exec_ctx) };
13825        }
13826    }
13827
13828    /// The executor's own worker's prelude to a pass: everything
13829    /// `spin_once` did before its readiness scan. Returns the pass's clock
13830    /// read and the elapsed time its timers are credited.
13831    /// # Safety
13832    /// As [`Self::pass`]; `window_lock` is the pass's (`None` for an owned
13833    /// pass), and with it the calling thread holds the lock exactly once.
13834    unsafe fn owned_prelude(
13835        this: *mut Self,
13836        window_lock: Option<super::exec_lock::ExecLock>,
13837        timeout: core::time::Duration,
13838    ) -> (Option<u64>, u64) {
13839        // SAFETY: the caller's contract; re-derived after every window.
13840        #[allow(unused_mut)]
13841        let mut s: &mut Self = unsafe { &mut *this };
13842        // phase-509 P7 (RFC-0108 D8.2) -- this level is alive: it reached a
13843        // spin. A level stuck in a callback stops checking in, which is what
13844        // the image's watchdog feed (`take_every_level_alive`) waits on.
13845        let now = s.now_us();
13846        super::level_liveness::LEVELS.check_in(s.worker.level, now);
13847        // phase-436 W2 (issue 1193) — the budget is carried in MICROSECONDS.
13848        // This was `as_millis()`, which truncates: `from_micros(500)` became
13849        // `0`, and a zero timeout selects the non-blocking path — so a
13850        // sub-millisecond `spin()` was a 100 % CPU loop with no warning. The
13851        // conversion to whatever the platform primitive accepts happens once,
13852        // at the park, and rounds UP. The budget itself is `grid_budget_us`
13853        // below (phase-474 I11).
13854
13855        // phase-425 W3b — bring the `/clock` subscription in line with
13856        // `use_sim_time`. One bool comparison in the settled case; the work only
13857        // happens on a transition, or while a request is waiting for its first
13858        // node to exist.
13859        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
13860        {
13861            #[cfg(feature = "param-store")]
13862            s.settle_builder_reserved_parameters();
13863            s.reconcile_ros_time_source();
13864        }
13865
13866        // phase-426 W3 — attach the six parameter services to any node that
13867        // does not have them yet. Same reason as the reconcile above: the
13868        // request routinely arrives before there is a node to publish under
13869        // (`nros::main!` emits `apply_param_services` ahead of its per-node
13870        // `register` calls, by design). One length comparison once settled.
13871        //
13872        // Issue 1271 -- a failure is LOGGED, once, rather than discarded. On
13873        // Cyclone this fails on every spin with `Transport(Unsupported)`
13874        // (issue 1268), and with the result dropped "this node has no
13875        // parameter services" was a fact nothing on the image stated.
13876        #[cfg(feature = "param-services")]
13877        if s.parameter_services_pending()
13878            && let Err(e) = s.reconcile_parameter_services()
13879        {
13880            s.report_parameter_service_reconcile_failure(e);
13881        }
13882
13883        // phase-556 W13 -- every node's `/rosout` writer, created on the spin
13884        // after the node (a node table scan once settled), then the queue
13885        // pumped into them. Both out of line: the pump's frame holds one `Log`
13886        // and one encode buffer, which `spin_once`'s frame must not carry on
13887        // every spin (issue 0756's rule). Entered only when there is work.
13888        #[cfg(feature = "rosout")]
13889        {
13890            if s.rosout_pending() {
13891                s.reconcile_rosout();
13892            }
13893            if crate::rosout::has_work() {
13894                s.pump_rosout();
13895            }
13896        }
13897
13898        // Release jitter, measured HERE rather than in `spin_period`, because
13899        // this is the function every driver goes through.
13900        //
13901        // The first version instrumented `spin_period` only, and that was the
13902        // same mistake issue 0736 records one layer down: a measurement placed
13903        // on a path no shipped image takes. `nros-cpp`'s sched task trampoline paces
13904        // itself with a `spin_once` loop at `spin_period_us` (see its
13905        // `run_components` docs, step 4), so `spin_period` is not what the C++
13906        // entry -- and therefore not what the Zephyr lane -- actually calls.
13907        // The field recorded zero forever while claiming to measure cadence.
13908        //
13909        // `timeout` is the caller's intended pacing quantum: `spin_period`
13910        // passes its period, and the generated entries pass 10 ms. phase-474
13911        // I11 -- with no declared cadence it is the period of an absolute
13912        // release grid, and the park budget is the time to the next grid
13913        // point (see `record_release_jitter`); the release is judged after the
13914        // park, against the grid (`record_grid_release`). A zero timeout means
13915        // "poll, no cadence claimed", so it is neither judged nor gridded.
13916        let grid_budget_us = s.record_release_jitter(timeout);
13917
13918        // issue 0900 — one-shot advisory when the arena is far larger than what
13919        // registered. First spin rather than "end of registration", because
13920        // there is no such point: an app may register lazily.
13921        super::arena::maybe_report_arena_headroom(s.arena_used, s.arena.len());
13922
13923        // phase-412 -- the same moment, recorded where a board with no log sink
13924        // can still be asked. Reaching this stage is the positive result the
13925        // advisory above cannot deliver on the island: registration completed.
13926        crate::boot_report::checkpoint(crate::boot_report::Stage::FirstSpin);
13927
13928        // Phase 110.0 — the backend's next internal-event deadline (lease
13929        // keepalive, heartbeat, ACK-NACK timeout, ...). Default backend impl
13930        // returns `None`, so this contributes nothing unless the active
13931        // backend opts in.
13932        //
13933        // phase-436 W6 — a CANDIDATE now, not a pre-cap. Folding it into the
13934        // budget here meant a park the session won was attributed to
13935        // `CallerBudget`, so the one number that explains a wake named the
13936        // wrong source.
13937        let session_us = s
13938            .session
13939            .next_deadline_ms()
13940            .map(|next| (next as u64).saturating_mul(1000));
13941
13942        // phase-436 W1 (issue 1192) — and by the next TIMER deadline, which is
13943        // the one class of deadline the executor itself owns. Before this the
13944        // park was bounded by the caller's budget narrowed only by the
13945        // BACKEND's next event, so ~~`spin_default`~~'s 50 ms slept straight past
13946        // a registered 10 ms timer.
13947        //
13948        // Attribution is recorded here rather than derived later: this is the
13949        // only point where the losing candidates are still in hand.
13950        let (park_bound_us, park_source) =
13951            s.next_wake_bound_attributed_us(grid_budget_us, session_us);
13952        s.worker.last_park_bound_us = park_bound_us;
13953        s.worker.last_park_source = park_source;
13954        // phase-436 W2 (issue 1193) — round UP to what the primitive can
13955        // express. The old `as_millis()` truncated, so a sub-millisecond
13956        // request became a zero park: the non-blocking path, a busy loop.
13957        let park_achieved_us = s.round_park_up_us(park_bound_us);
13958        s.worker.last_park_achieved_us = park_achieved_us;
13959
13960        // phase-436 W6 — a port that installed a park primitive does its
13961        // waiting HERE, on the bound every source agreed on, and the transport
13962        // is then drained non-blockingly.
13963        //
13964        // This is the path bare metal needs: a `ParkUntilFn` can arm a
13965        // timer compare before `wfi`, which `sleep(duration)` cannot express —
13966        // and `nros-baremetal-common` notes that `wfi` with no pending
13967        // interrupt deadlocks, so arming first is not optional there.
13968        //
13969        // Additive by construction: with no primitive installed this is a
13970        // no-op and every existing port keeps the behaviour it has.
13971        // phase-436 — park only when something can END the park early. A
13972        // park ends on the bound or on the wake object; with a poll-only
13973        // backend (XRCE), or a session whose wake callback is gone, nothing
13974        // signals that object, so the park would be a blind sleep and data
13975        // arriving mid-park would wait out the whole bound — the Phase
13976        // 127.C.4 stall (a reliable stream whose ACK lands in a session nobody
13977        // drives). Those executors wait on the wake object below, on the short
13978        // entry budget (`entry_spin_budget`).
13979        let park_can_be_woken = s.park_can_be_woken();
13980
13981        // phase-521 W3 (RFC-0113 D3) -- a session whose readiness is a
13982        // WAITABLE handle (a socket on POSIX / NuttX) is parked on: the port
13983        // multiplexes the handles with this executor's own wake object, so
13984        // data arriving ends the park and a guard trigger still does too. The
13985        // sched task then drains its sessions non-blockingly below, instead of
13986        // blocking inside the transport's `recv` (and slicing that wait for
13987        // a guard condition, phase-436 D5). A port that cannot wait on handles
13988        // answers `None` and the wait below is the one it always had.
13989        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
13990        let handle_parked = if park_achieved_us > 0 {
13991            let mut handles = [0i32; MAX_WAITABLE_HANDLES];
13992            let n = s.waitable_handles(&mut handles);
13993            match s.node_wake.as_ref() {
13994                Some(wake) if n > 0 => {
13995                    let wake: *const super::node_wake::NodeWake = &**wake;
13996                    let _window = window_lock.map(super::exec_lock::Window::open);
13997                    // SAFETY: the wake object is the executor's (`Arc`, set at
13998                    // open and never replaced), so it outlives the window.
13999                    unsafe { &*wake }
14000                        .park_handles_us(&handles[..n], park_achieved_us)
14001                        .is_some()
14002                }
14003                _ => false,
14004            }
14005        } else {
14006            false
14007        };
14008        #[cfg(not(all(feature = "alloc", feature = "rmw-cffi")))]
14009        let handle_parked = false;
14010        // SAFETY: the lock is held again (the window, if any, has closed).
14011        s = unsafe { &mut *this };
14012
14013        // phase-509 P9b item 3 -- a shared pass parks with the lock released
14014        // (a window), so the band workers run while the executor's own
14015        // worker waits. Nothing borrowed from the executor crosses it.
14016        let mut yielded = false;
14017        let parked = handle_parked
14018            || match s.worker.park_primitive {
14019                Some((park, ctx)) if park_achieved_us > 0 && park_can_be_woken => {
14020                    let _window = window_lock.map(super::exec_lock::Window::open);
14021                    // SAFETY: `park` and `ctx` were supplied together by the port
14022                    // through `set_park_primitive` and outlive the executor by its
14023                    // contract.
14024                    //
14025                    // phase-436 — a negative answer is "cannot park": the ABI's
14026                    // own contract, and what a Rust-implemented port's trait
14027                    // default returns at once. Counting that as a park would
14028                    // drop the drain below to non-blocking and spin hot, so the
14029                    // spin falls back to the wait it would have had uninstalled.
14030                    let rc = unsafe { park(ctx, park_achieved_us) };
14031                    yielded = rc == PARK_YIELDED;
14032                    rc >= 0
14033                }
14034                _ => false,
14035            };
14036        // SAFETY: the lock is held again (the window, if any, has closed).
14037        s = unsafe { &mut *this };
14038        // phase-521 W8 (c) -- a YIELDED slot did not wait: its framework runs
14039        // this sched task again at the bound or on an arrival, so the pass returns.
14040        // Not while a wake is already pending, though: then the work is here
14041        // now, and the answer counts as a park that ended at once.
14042        #[cfg(feature = "alloc")]
14043        let pending = s.wake_flag.load(portable_atomic::Ordering::SeqCst);
14044        #[cfg(not(feature = "alloc"))]
14045        let pending = false;
14046        s.worker.park_yielded = yielded && !pending;
14047
14048        // Having already waited, the transport drain must not block again —
14049        // otherwise the park and the drive would sum, and the cadence would be
14050        // up to twice what was asked. Same trap as passing a period to
14051        // `spin_once` instead of declaring it (#648).
14052        let timeout_ms = if parked {
14053            0
14054        } else {
14055            (park_achieved_us / 1000).min(i32::MAX as u64) as i32
14056        };
14057
14058        // Wall-clock-accurate timer accumulation. Measure real time
14059        // since the previous `spin_once` exited (or, on the first call,
14060        // since `drive_io` started). Two failure modes the requested
14061        // `timeout_ms` doesn't capture:
14062        //  1. `drive_io` returns early — e.g. zenoh-pico's condvar wakes
14063        //     on data arrival, well under 1 ms.
14064        //  2. The caller spends time outside `spin_once` (explicit sleep,
14065        //     ROS-2 cooperative scheduling, etc.) and that time should
14066        //     still count toward timers.
14067        // Crediting the requested timeout to timers in either case ticks
14068        // them faster than wall-clock — observed as a 30 Hz control loop
14069        // overshooting to >200 Hz under sustained traffic. Carry the
14070        // sub-ms remainder across calls so precision is preserved.
14071        // phase-359 W4 — the spin-ENTRY read, one spelling. Kept distinct from
14072        // the post-IO read below because the first spin's delta is measured from
14073        // entry; collapsing them would make that delta 0 on the first call only.
14074        let spin_start_us = s.now_us();
14075
14076        // phase-474 I2 -- arm the monitors when the policy says start-up is over,
14077        // before any rule of this spin can judge.
14078        s.update_monitor_arming(spin_start_us);
14079        // phase-462 W4 -- and switch to the requested mode's tables, before
14080        // any rule of this spin judges by them.
14081        s.update_mode(spin_start_us);
14082
14083        // RFC-0052 W3b.4 — contract monitors tick once per spin (window
14084        // logic inside; single branch when the baked table is empty).
14085        s.run_contract_monitors();
14086
14087        // Phase 104.C.6 — shared executor wake. Swap-and-clear the
14088        // wake flag; if it was set before this `spin_once` entered,
14089        // skip the blocking wait on the primary session and poll
14090        // every session non-blockingly. Lets a wake signal from any
14091        // thread (or, post-104.C.6.b, any backend's vtable hook)
14092        // pre-empt whichever session the executor would otherwise
14093        // sleep on. Cost on the no-wake path is one atomic swap.
14094        // phase-359 W10 — ONE swap, at `alloc` scope.
14095        //
14096        // This was `#[cfg(feature = "std")]` while the alloc wait arm did its
14097        // own swap further down. Merging the two arms made that two swaps of
14098        // one flag per spin, the first consuming what the second tested, so the
14099        // arm would have read `was_woken == false` forever. Deleting the outer
14100        // one instead broke a different thing: `wake_flag` is `alloc`-gated and
14101        // "spin_once consumes the wake flag" is an invariant of every alloc
14102        // build, but the merged arm only runs with `rmw-cffi` — so a
14103        // `std`-without-`rmw-cffi` build stopped clearing it, which
14104        // `test_wake_cleared_each_spin` catches. It belongs here, at the scope
14105        // of the field it reads.
14106        #[cfg(feature = "alloc")]
14107        #[allow(unused_variables)]
14108        let was_woken = s.wake_flag.swap(false, portable_atomic::Ordering::SeqCst);
14109
14110        // Phase 124.B.4 — condvar-blocked wait.
14111        //
14112        // RT contract:
14113        //  * cv.wait_timeout_while: bounded by `timeout_ms`.
14114        //    Predicate is O(1) — one atomic swap + Instant::now.
14115        //    No allocation. PI-mutex consideration: wake_mu held
14116        //    only during predicate check (microseconds);
14117        //    contended worst-case = notify_all execution time
14118        //    (~10s of µs).
14119        //  * Backend's `set_wake_callback`-installed cb is called
14120        //    on async data arrival from its transport-notify path
14121        //    (worker thread, ISR-safe variant via 124.B.7). The
14122        //    runtime cb writes wake_flag + signals wake_cv,
14123        //    unblocking this loop sub-poll-period.
14124        //  * Poll-only backends (XRCE, bare-metal) leave the slot
14125        //    NULL; the cv wait still fires on its deadline, then
14126        //    drive_io(0) drains whatever the backend's internal
14127        //    poll has buffered. Equivalent to their pre-124
14128        //    behaviour minus the blocking wait inside drive_io.
14129        //
14130        // Lost-wakeup safe: SeqCst flag write happens-before
14131        // notify, and the waiter checks the flag under wake_mu in
14132        // the predicate. If wake fires between drain and cv.wait
14133        // entry, the predicate sees flag=true on first eval and
14134        // exits immediately.
14135        // Phase 130.4 — only sleep in the wake wait when a backend actually
14136        // installed `set_wake_callback`. Poll-only backends (XRCE) leave the
14137        // vtable slot NULL → `has_async_wake == false` →
14138        // drive_io for the caller's full timeout instead of sleeping in a
14139        // never-signaled wait that starves reliable retransmission (Phase
14140        // 127.C.4 root cause: the server's `send_response` flushes 100 ms once,
14141        // then a blind `wait_ms(100)` sleeps with zero session activity, so the
14142        // agent's ACK arrives into a stalled session and reliable redelivery
14143        // never fires).
14144        //
14145        // Phase 248 (C2) — which primitive is a RUNTIME choice from the
14146        // platform vtable's wake probe, not a compile-time per-RTOS `cfg`:
14147        // `node_wake.is_some()` means `nros_platform_wake_*` is linked and
14148        // `nros_rmw_runtime_wake_cb` signals it on transport arrival.
14149        // phase-359 W10 — ONE arm. This was a `std` arm and an `alloc` arm with
14150        // the same body: block on the platform wake primitive when a backend
14151        // installed the callback and nothing has woken us yet, else drive the
14152        // transport for the caller's full timeout. They stopped differing when
14153        // the condvar fallback was deleted — the std arm's `else` branch had
14154        // already become "drive for the full timeout", which is what the alloc
14155        // arm always did — so keeping two was keeping a fork that agreed.
14156        // phase-417 W4.e — the FIRST arm is what the swap-and-clear above says
14157        // it is for, and it was missing: a wake that landed BETWEEN two spins
14158        // set the flag, and this expression then took the `else` and drove the
14159        // transport for the caller's FULL timeout, so the pending work waited
14160        // out the very budget the wake exists to cut short. Measured with a
14161        // guard condition triggered from another thread just before a 400 ms
14162        // spin: 400 ms to dispatch, against 50 ms for the same trigger issued
14163        // while the spin was already parked in `wait_ms`. Being woken means
14164        // there IS work, so the right timeout is 0 — poll every session
14165        // non-blockingly and go dispatch it, which is what the comment at the
14166        // swap has claimed since Phase 104.C.6.
14167        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
14168        let primary_drive_timeout_ms = {
14169            if was_woken {
14170                // Issue 1385 — drain the wake PRIMITIVE too.
14171                //
14172                // `nros_rmw_runtime_wake_cb` sets both halves of one signal:
14173                // the flag, and the platform primitive. The swap above
14174                // consumed the flag and this arm returns without entering the
14175                // wait, so a primitive left posted makes the NEXT spin's
14176                // `wait_ms` return instantly on a signal already acted on —
14177                // that spin does not wait at all, and whatever it should have
14178                // waited for is dispatched a whole spin late.
14179                //
14180                // `wait_ms(0)` is the non-blocking take: every port's wait is a
14181                // deadline (`sem_timedwait`, `k_sem_take`, `xSemaphoreTake`),
14182                // so zero means "take it if it is there", never "wait
14183                // forever".
14184                //
14185                // Measured, not reasoned: with the C executor installing a
14186                // callback (the other half of 1385), an arrival taken by this
14187                // arm left the spin after it returning in 0 ms where it owed
14188                // 60 ms of waiting — which is what `node_guard_condition.c`'s
14189                // mid-spin case caught, and what `executor_backend_wake.c`'s
14190                // second lower bound now pins. Latent until then only because
14191                // no C spin had ever entered the wait arm.
14192                if let Some(wake) = s.node_wake.as_ref() {
14193                    let _ = wake.wait_ms(0);
14194                }
14195                0
14196            } else if let Some(wake) = s.node_wake.as_ref() {
14197                // phase-521 W6 (RFC-0113 D2) — the wait is on the wake object
14198                // whatever the session's form. A session that states no
14199                // readiness form is refused at open (D5), so the transport's
14200                // own `recv` is never the wait any more. A `Notify` session
14201                // whose callback is live posts this object on an arrival; a
14202                // `Waitable` session was parked on above. What reaches here
14203                // unwoken by its data (a wake fan-out with no free member, more
14204                // waitable sessions than one park multiplexes) is the case
14205                // `entry_spin_budget` keeps on the short budget, so the wait
14206                // stays bounded by it and the drain below picks the data up.
14207                // phase-436 — after a park this wait has a zero timeout and
14208                // the park has already waited on this same object, so it is a
14209                // second syscall that can only time out. Measured on a native
14210                // sched task: one extra futex wait per iteration, doubling the idle
14211                // context switches. A signal that lands between the park's
14212                // return and here stays posted and ends the next park at once,
14213                // which costs one spin and loses nothing.
14214                if !parked {
14215                    // phase-509 P9b item 3 -- the wait is a window too: the
14216                    // wake object is the executor's (`Arc`, set at open and
14217                    // never replaced), reached through a raw pointer.
14218                    let wake: *const super::node_wake::NodeWake = &**wake;
14219                    let _window = window_lock.map(super::exec_lock::Window::open);
14220                    // SAFETY: the object outlives the executor's open window.
14221                    let _ = unsafe { &*wake }.wait_ms(timeout_ms as u32);
14222                }
14223                // SAFETY: the lock is held again.
14224                s = unsafe { &mut *this };
14225                // Drain any flag the cb set while we were waiting.
14226                let _ = s.wake_flag.swap(false, portable_atomic::Ordering::SeqCst);
14227                0
14228            } else {
14229                // No wake object linked (a port that supplies no
14230                // `nros_platform_wake_*`): the backend's drive is the only
14231                // wait there is.
14232                timeout_ms
14233            }
14234        };
14235
14236        // std builds without rmw-cffi (mock-session tests, future alternative
14237        // backends) keep the original "drive_io is non-blocking" assumption.
14238        // `std` implies `alloc`, so this is the only std configuration the arm
14239        // above does not cover.
14240        #[cfg(all(feature = "alloc", not(feature = "rmw-cffi")))]
14241        let primary_drive_timeout_ms = 0;
14242
14243        // no_std without (alloc + rmw-cffi) keeps the legacy
14244        // full-timeout drive_io call.
14245        #[cfg(all(
14246            not(feature = "alloc"),
14247            not(all(feature = "alloc", feature = "rmw-cffi"))
14248        ))]
14249        let primary_drive_timeout_ms = timeout_ms;
14250
14251        // issue 0324 — the primary session's I/O result is TRACKED, not
14252        // discarded. See `consecutive_io_failures` for why this is a counter
14253        // rather than an early return.
14254        match s.drive_primary(primary_drive_timeout_ms) {
14255            Ok(()) => s.consecutive_io_failures = 0,
14256            Err(e) => {
14257                // Issue 2576 — the one failure that is a verdict, kept apart
14258                // from the tally so a caller can tell it from a transient.
14259                if e == TransportError::SessionLost {
14260                    s.session_lost = true;
14261                }
14262                s.consecutive_io_failures = s.consecutive_io_failures.saturating_add(1)
14263            }
14264        }
14265        for extra in s.extra_sessions.iter_mut() {
14266            // Best-effort BY DESIGN: extra sessions are bridge / multi-domain
14267            // attachments, and one of them failing must not stall the primary
14268            // spin. The old code expressed this the same way it expressed the
14269            // primary's discarded error — identically — so the intent was
14270            // invisible. It is now the only `let _ =` of the two.
14271            let _ = extra.drive_io(0);
14272        }
14273
14274        // phase-359 W4 — ONE clock read per spin, shared by the delta below and
14275        // every consumer further down. Replaces the std/no_std delta pair AND
14276        // two ad-hoc `static EPOCH: OnceLock<Instant>` blocks that each kept
14277        // their own std-only epoch.
14278        let now_us_this_spin = s.now_us();
14279        // phase-474 I11 -- the release instant is the end of the park, so it
14280        // is judged on this read, before any dispatch of this spin.
14281        if let Some(now) = now_us_this_spin {
14282            s.record_grid_release(now);
14283        }
14284
14285        // Same rule on both flavours: measure elapsed when a clock exists, else
14286        // credit the REQUESTED timeout. That fallback was previously reachable
14287        // only on no_std; on std `Instant` always answered. It stays unreachable
14288        // on std for the same reason — `now_us()` is infallible there — so this
14289        // is one expression, not a behaviour change.
14290        let delta_us = match now_us_this_spin {
14291            Some(now) => {
14292                let prev = s
14293                    .last_spin_end_us
14294                    .unwrap_or_else(|| spin_start_us.unwrap_or(now));
14295                s.last_spin_end_us = Some(now);
14296                now.saturating_sub(prev)
14297            }
14298            None => (timeout_ms as u64).saturating_mul(1000),
14299        };
14300
14301        // phase-430 W1 — the silence watch is credited the SAME `delta_us` the
14302        // wall timers below are, which is the whole of its unit argument: the
14303        // diagnostic arrives after as much time as this image's own wall timers
14304        // believe has passed, on whatever clock it actually has.
14305        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
14306        s.note_sim_time_silence(delta_us);
14307
14308        if !s.spin_quantization_checked && timeout_ms > 0 {
14309            s.spin_quantization_checked = true;
14310            // The TIER's declared cadence, not the capped park bound. Since
14311            // phase-436 W1 the two differ whenever a timer is due sooner than
14312            // the budget, and auditing the cap would compare the timer period
14313            // against itself — an exact multiple every time, so issue 0515's
14314            // warning would go silent on precisely the images that have a
14315            // timer to quantize. `spin_nominal_us` is the declared cadence
14316            // (`set_spin_nominal_us`, else the caller's timeout), recorded at
14317            // the top of this spin before any capping.
14318            s.spin_quantization_us = s.spin_nominal_us;
14319            s.audit_spin_quantization(s.spin_quantization_us);
14320        }
14321        (now_us_this_spin, delta_us)
14322    }
14323
14324    /// Drive I/O and dispatch callbacks forever — the body of an RTOS task.
14325    ///
14326    /// EXTENSION. Not a rename of upstream's `spin`: the `!` is the
14327    /// point. A bare-metal entry has no shutdown source to return TO, and
14328    /// declaring that lets the compiler drop the epilogue and lets the caller
14329    /// write it as the last expression of a `-> !` task body with no
14330    /// `unreachable!()`. [`spin`](Self::spin) is the verb that can end, and it
14331    /// is upstream's.
14332    ///
14333    /// Was `spin(Duration) -> !`, which squatted on rclrs's name
14334    /// with a different contract (a ported `executor.spin(SpinOptions)` line
14335    /// had to be renamed by hand, the one edit on the tutorial's happy path
14336    /// that no real difference forced). ~~`spin_default()`~~ went with it: it named
14337    /// a 50 ms poll interval and had zero call sites, and the interval is now
14338    /// [`SpinOptions::poll_interval`], defaulting to
14339    /// [`DEFAULT_SPIN_POLL_INTERVAL`](super::types::DEFAULT_SPIN_POLL_INTERVAL).
14340    ///
14341    /// **Envelope.** Only `poll_interval` and `stop_on_first_error` can mean
14342    /// anything here; `timeout`, `only_next` and `max_callbacks` are ENDING
14343    /// conditions and this verb does not end. Passing one is a caller error and
14344    /// says so at `LOG_ERR` on entry rather than being quietly dropped — a
14345    /// discarded ending condition is precisely the "compiles and differs" case
14346    /// the ROS 2 adoption rule exists to make loud, and a `-> !` signature has no other
14347    /// channel. `stop_on_first_error` likewise cannot RETURN the error; it
14348    /// logs it and keeps spinning, because a task body has nowhere to put it.
14349    ///
14350    /// ```ignore
14351    /// let mut executor = Executor::open(&config)?;
14352    /// executor.register_subscription::<Int32, _>("/topic", |msg| { /* ... */ })?;
14353    /// executor.spin_forever(SpinOptions::default()); // never returns
14354    /// ```
14355    pub fn spin_forever(&mut self, opts: SpinOptions) -> ! {
14356        if opts.timeout.is_some() || opts.only_next || opts.max_callbacks.is_some() {
14357            nros_log::log_error!(
14358                nros_log::get_logger("nros"),
14359                "spin_forever: an ending condition (timeout / only_next / max_callbacks) \
14360                 was supplied to a verb that never returns and is being IGNORED \
14361                 -- use `Executor::spin` for a loop that can end"
14362            );
14363        }
14364        let poll = opts.poll_interval;
14365        let report_errors = opts.stop_on_first_error;
14366        loop {
14367            let mut first_error = None;
14368            self.spin_once_capturing(poll, &mut first_error);
14369            if report_errors && let Some(e) = first_error {
14370                nros_log::log_error!(
14371                    nros_log::get_logger("nros"),
14372                    "spin_forever: a callback failed ({:?}); `stop_on_first_error` cannot \
14373                     end a `-> !` loop, so this is a report, not a stop",
14374                    e
14375                );
14376            }
14377        }
14378    }
14379
14380    /// Execute the work that is ready NOW and return — rclcpp's
14381    /// `Executor::spin_some(max_duration)`.
14382    ///
14383    /// ADOPT-BOUNDED. Upstream's drain verb: collect what is ready,
14384    /// execute it, come back. It never waits for new work — that is
14385    /// [`spin_once`](Self::spin_once), which takes a budget and blocks on the
14386    /// transport until it expires.
14387    ///
14388    /// **Envelope, two ways it is weaker than rclcpp's:**
14389    ///
14390    /// * rclcpp collects the ready set ONCE and executes it. One
14391    ///   `spin_once(0)` here is already that whole set, so this
14392    ///   would be a single call — except a callback may enqueue work for
14393    ///   another entity, which rclcpp's `spin_all` re-collects and its
14394    ///   `spin_some` leaves for the next call. Ours re-drains until a pass does
14395    ///   NO work, which is `spin_all`'s answer, because the alternative is
14396    ///   work sitting in the arena until someone spins again. Bounded by
14397    ///   `max`, so a callback that feeds itself cannot wedge the caller.
14398    /// * `max` is checked BETWEEN passes, never inside one, so it is a floor on
14399    ///   when this returns and not a ceiling: a single long callback overruns
14400    ///   it. There is no preemption here to make it a ceiling.
14401    ///
14402    /// `max` of [`Duration::ZERO`](core::time::Duration::ZERO) means no limit —
14403    /// rclcpp's own default — and is the spelling a build with no clock must
14404    /// use. A non-zero `max` on a clockless build is an ERROR rather than an
14405    /// unbounded drain (the same rule as `spin`'s `timeout`).
14406    ///
14407    /// The `Result` is about that PRECONDITION and nothing else. A failed
14408    /// callback is counted in each pass's `SpinOnceResult` and does not end the
14409    /// drain, matching `spin`'s default (`SpinOptions::stop_on_first_error` is
14410    /// `false`); rclcpp's `spin_some` returns `void` and reports callback
14411    /// failures nowhere at all.
14412    ///
14413    /// # Example
14414    ///
14415    /// ```ignore
14416    /// // Drain the ready set, then get on with the caller's own work.
14417    /// executor.spin_some(core::time::Duration::ZERO)?;
14418    /// ```
14419    pub fn spin_some(&mut self, max: core::time::Duration) -> Result<(), NodeError> {
14420        let bounded = !max.is_zero();
14421        let start_us = self.now_us();
14422        if bounded && start_us.is_none() {
14423            // issue 0709
14424            nros_log::log_error!(
14425                nros_log::get_logger("nros"),
14426                "spin_some: a max duration was requested but this build has no clock \
14427                 - install one with `ExecutorConfig::clock_us`, or pass \
14428                 `Duration::ZERO` for rclcpp's unbounded default"
14429            );
14430            return Err(NodeError::NotInitialized);
14431        }
14432        let max_us = max.as_micros().min(u64::MAX as u128) as u64;
14433
14434        // TEMPORARY (phase-554 W3 slice C deletes it) -- as in `spin`.
14435        self.open_pending_on_configured_name()?;
14436
14437        // No `enter_spin_loop` here, deliberately: `is_spinning` answers "a
14438        // blocking loop is running that a peer's `cancel()` has to reach", and
14439        // this verb returns on its own. Raising the flag for the length of a
14440        // drain would make a `cancel()` from another task look acted-upon when
14441        // nothing was waiting for it.
14442        loop {
14443            let result = self.spin_once(core::time::Duration::ZERO);
14444            if !result.any_work() {
14445                break;
14446            }
14447            if bounded
14448                && let (Some(start), Some(now)) = (start_us, self.now_us())
14449                && now.saturating_sub(start) >= max_us
14450            {
14451                break;
14452            }
14453        }
14454        Ok(())
14455    }
14456
14457    // RFC-0108 D9, issue 2675.
14458    /// [`spin_some`](Self::spin_some) through a raw pointer, for a caller
14459    /// whose callbacks may call back into this executor: each pass is a
14460    /// [`spin_once_raw`](Self::spin_once_raw), and the clock is read through
14461    /// a reference that lives for that read alone.
14462    ///
14463    /// # Safety
14464    /// As [`spin_once_raw`](Self::spin_once_raw).
14465    pub unsafe fn spin_some_raw(
14466        this: *mut Self,
14467        max: core::time::Duration,
14468    ) -> Result<(), NodeError> {
14469        let bounded = !max.is_zero();
14470        // SAFETY: the caller's contract; the reference ends with the read.
14471        let now_us = || unsafe { (*this).now_us() };
14472        let start_us = now_us();
14473        if bounded && start_us.is_none() {
14474            // issue 0709 -- as `spin_some`.
14475            nros_log::log_error!(
14476                nros_log::get_logger("nros"),
14477                "spin_some: a max duration was requested but this build has no clock \
14478                 - install one with `ExecutorConfig::clock_us`, or pass \
14479                 `Duration::ZERO` for rclcpp's unbounded default"
14480            );
14481            return Err(NodeError::NotInitialized);
14482        }
14483        let max_us = max.as_micros().min(u64::MAX as u128) as u64;
14484        loop {
14485            // SAFETY: the caller's contract.
14486            let result = unsafe { Self::spin_once_raw(this, core::time::Duration::ZERO) };
14487            if !result.any_work() {
14488                break;
14489            }
14490            if bounded
14491                && let (Some(start), Some(now)) = (start_us, now_us())
14492                && now.saturating_sub(start) >= max_us
14493            {
14494                break;
14495            }
14496        }
14497        Ok(())
14498    }
14499
14500    // ========================================================================
14501    // spin_one_period (no_std)
14502    // ========================================================================
14503
14504    /// Process one iteration and return remaining sleep time.
14505    ///
14506    /// This is `no_std` compatible — the caller is responsible for the actual
14507    /// delay using platform-specific sleep.
14508    ///
14509    /// # Arguments
14510    /// * `period_ms` - Target period in milliseconds
14511    /// * `elapsed_ms` - Time elapsed since last call (used for timer ticking)
14512    ///
14513    /// # Example
14514    ///
14515    /// ```ignore
14516    /// loop {
14517    ///     let r = executor.spin_one_period(10, elapsed_ms);
14518    ///     platform_sleep_ms(r.remaining_ms);
14519    /// }
14520    /// ```
14521    pub fn spin_one_period(&mut self, period_ms: u64, elapsed_ms: u64) -> SpinPeriodPollingResult {
14522        let result = self.spin_once(core::time::Duration::from_millis(elapsed_ms));
14523        SpinPeriodPollingResult {
14524            work: result,
14525            remaining_ms: period_ms.saturating_sub(elapsed_ms),
14526        }
14527    }
14528}
14529
14530// ============================================================================
14531// `/rosout` (cfg rosout) -- phase-556 W13
14532// ============================================================================
14533
14534#[cfg(feature = "rosout")]
14535impl<'s> Executor<'s> {
14536    /// Is there a node whose `/rosout` writer has not been created yet?
14537    #[inline]
14538    pub(crate) fn rosout_pending(&self) -> bool {
14539        self.nodes
14540            .iter()
14541            .any(|r| matches!(r.rosout, super::node_record::RosoutWriter::Pending))
14542    }
14543
14544    /// Create the `/rosout` writer of every node that does not have one yet.
14545    ///
14546    /// A reconcile at the head of the spin, as the parameter services are,
14547    /// for their reason: a node may be built before the transport can serve
14548    /// it, and an entry builds its nodes before it spins. A failure is
14549    /// reported once per node and not retried: the usual cause is a pool the
14550    /// image did not size, which a later spin cannot change.
14551    #[inline(never)]
14552    pub(crate) fn reconcile_rosout(&mut self) {
14553        use super::node_record::RosoutWriter;
14554        for index in 0..self.nodes.len() {
14555            if !matches!(self.nodes[index].rosout, RosoutWriter::Pending) {
14556                continue;
14557            }
14558            let node = super::node_record::NodeId::from_raw(index as u8);
14559            let created = create_rosout_pub(self, node);
14560            let state = match created {
14561                Ok(handle) => RosoutWriter::Up(handle),
14562                Err(e) => {
14563                    let mut fqn = heapless::String::<256>::new();
14564                    let r = &self.nodes[index];
14565                    if let Ok(f) = crate::names::fully_qualified_name(&r.name, &r.namespace) {
14566                        let _ = fqn.push_str(f.as_str());
14567                    }
14568                    report_rosout_refused(fqn.as_str(), e);
14569                    RosoutWriter::Refused
14570                }
14571            };
14572            self.nodes[index].rosout = state;
14573        }
14574        // The node builder already asked; asking again is free once installed,
14575        // and a refusal here is the one that is reported.
14576        if !crate::rosout::enable() {
14577            Self::report_rosout_queue_refused();
14578        }
14579    }
14580
14581    /// Say, once, that the `/rosout` queue could not be installed.
14582    #[cold]
14583    #[inline(never)]
14584    fn report_rosout_queue_refused() {
14585        static REPORTED: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false);
14586        if REPORTED.swap(true, portable_atomic::Ordering::Relaxed) {
14587            return;
14588        }
14589        nros_log::log_error!(
14590            nros_log::get_logger("nros"),
14591            "the /rosout log queue could not be installed because the log sink table is \
14592             full ({} sinks); no record reaches /rosout.",
14593            nros_log::MAX_ADDED_SINKS
14594        );
14595    }
14596
14597    /// Publish every queued log record on the `/rosout` writer of the node
14598    /// whose logger raised it.
14599    ///
14600    /// Routing: a record from a node's logger, or from a logger below it
14601    /// (`<node>.<child>`, Iron and Jazzy), goes to that node's writer; any
14602    /// other record (the pump's own loss report, a scope that admits free
14603    /// loggers) goes to the first node's. No allocation.
14604    #[inline(never)]
14605    pub(crate) fn pump_rosout(&mut self) {
14606        if !self.nodes.iter().any(|r| r.rosout.publisher().is_some()) {
14607            // Nowhere to publish. Leave the queue alone: a node outside the
14608            // table (a legacy C `rclc_node_init_default` node) may be pumping
14609            // it through the explicit spelling.
14610            return;
14611        }
14612        let nodes = &self.nodes;
14613        let result = crate::rosout::pump_routed(|logger, bytes| {
14614            use nros_rmw::Publisher as _;
14615            match rosout_route(nodes, logger) {
14616                Some(p) => p.publish_raw(bytes).map_err(|_| ()),
14617                None => Err(()),
14618            }
14619        });
14620        if let Err((_, e)) = result {
14621            Self::report_rosout_publish_failed(e);
14622        }
14623    }
14624
14625    /// Say, once, that a `/rosout` publish was refused. Once, because the
14626    /// line itself is a log record bound for `/rosout`.
14627    #[cold]
14628    #[inline(never)]
14629    fn report_rosout_publish_failed(e: NodeError) {
14630        static REPORTED: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false);
14631        if REPORTED.swap(true, portable_atomic::Ordering::Relaxed) {
14632            return;
14633        }
14634        nros_log::log_warn!(
14635            nros_log::get_logger("nros"),
14636            "a /rosout publish was refused ({:?}); records are lost until the transport \
14637             accepts them again. Reported once.",
14638            e
14639        );
14640    }
14641
14642    /// `node` publishes no `/rosout` (rclcpp's `NodeOptions::enable_rosout(false)`).
14643    /// Drops its writer if it has one, and keeps the next spin from creating
14644    /// it. Its logger's records then go to the first node that still has a
14645    /// writer.
14646    pub fn disable_rosout_on(&mut self, node: super::node_record::NodeId) {
14647        if let Some(r) = self.nodes.get_mut(node.index()) {
14648            r.rosout = super::node_record::RosoutWriter::Off;
14649        }
14650    }
14651
14652    /// Whether `node`'s runtime-owned `/rosout` writer is up.
14653    #[must_use]
14654    pub fn rosout_writer_is_up(&self, node: super::node_record::NodeId) -> bool {
14655        self.nodes
14656            .get(node.index())
14657            .is_some_and(|r| r.rosout.publisher().is_some())
14658    }
14659
14660    /// Drop every node's `/rosout` writer (close and drop). Every node is
14661    /// left `Off`, so a later spin does not recreate one.
14662    pub(crate) fn release_rosout(&mut self) {
14663        for r in self.nodes.iter_mut() {
14664            r.rosout = super::node_record::RosoutWriter::Off;
14665        }
14666    }
14667}
14668
14669// ============================================================================
14670// Parameter services (cfg param-services)
14671// ============================================================================
14672
14673#[cfg(feature = "param-services")]
14674impl<'s> Executor<'s> {
14675    /// Register the 6 ROS 2 parameter services for this node.
14676    ///
14677    /// Creates service servers for `get_parameters`, `set_parameters`,
14678    /// `set_parameters_atomically`, `list_parameters`, `describe_parameters`,
14679    /// and `get_parameter_types`.
14680    ///
14681    /// The service names follow the ROS 2 convention: `/{namespace}/{node_name}/{suffix}`.
14682    /// For the default namespace `/`, this becomes `/{node_name}/{suffix}` (e.g.
14683    /// `/sentinel/list_parameters`).
14684    ///
14685    /// Parameter services are stored outside the arena and don't consume
14686    /// callback slots.
14687    ///
14688    /// Every node served this way also PUBLISHES
14689    /// `/parameter_events` (`rcl_interfaces/msg/ParameterEvent`), rclcpp's and
14690    /// rclrs's default: a start-up event, then one event per declare, set and
14691    /// undeclare. One VOLATILE publisher per node, as stock
14692    /// ([`PARAM_EVENT_PUBLISHERS`](crate::parameter_services::PARAM_EVENT_PUBLISHERS)).
14693    /// A node opts out with
14694    /// [`disable_parameter_events_on`](Self::disable_parameter_events_on)
14695    /// (rclc's `notify_changed_over_dds = false`).
14696    ///
14697    /// # Example
14698    ///
14699    /// ```ignore
14700    /// let config = ExecutorConfig::from_env().node_name("talker");
14701    /// let mut executor = Executor::open(&config)?;
14702    /// executor.register_parameter_services()?;
14703    /// executor.declare_parameter("start_value", ParameterValue::Integer(0));
14704    /// ```
14705    pub fn register_parameter_services(&mut self) -> Result<(), NodeError> {
14706        // Issue 1706 -- six services over a store that does not exist would
14707        // answer every request with "not declared"; say what went wrong
14708        // instead (`report_parameter_store_refused` has named the size).
14709        if !self.ensure_parameter_store() {
14710            return Err(NodeError::Transport(TransportError::BadAlloc));
14711        }
14712        if let Some(params) = &mut self.params {
14713            params.requested = true;
14714        }
14715        // phase-426 W3 — with no node yet, RECORD the request and stop. The
14716        // reconcile's no-node fallback publishes under the executor's own
14717        // identity, and taking it here would pin node 0 to that name before the
14718        // node that IS node 0 has been built — which is the pre-W3 behaviour
14719        // this work item exists to remove. Every generated entry arrives in
14720        // exactly this state (`apply_param_services` runs ahead of the per-node
14721        // `register` calls, by design), so the fallback belongs on the spin
14722        // path, where "no node" has stopped being merely "not yet".
14723        if self.nodes.is_empty() {
14724            return Ok(());
14725        }
14726        // Issue 2304 -- an explicit caller (the C and C++ APIs) gets the error
14727        // AND the line naming the node and the service, through the reporter
14728        // the spin uses (once; issue 1271). The C API used to turn this into a
14729        // bare RCL_RET_ERROR with nothing on the console.
14730        let result = self.reconcile_parameter_services();
14731        if let Err(e) = &result {
14732            self.report_parameter_service_reconcile_failure(e.clone());
14733        }
14734        result
14735    }
14736
14737    /// phase-426 W3 — is there a node whose six services are not up yet?
14738    ///
14739    /// The cheap half of the reconcile, kept separate so `spin_once` can test
14740    /// it without carrying the reconcile's frame (see below).
14741    #[inline]
14742    pub(crate) fn parameter_services_pending(&self) -> bool {
14743        self.params.as_deref().is_some_and(|p| {
14744            p.requested
14745                && p.services.len() < self.nodes.len().max(1)
14746                // Issue 1268 — a failure that cannot change is not pending
14747                // work. This used to retry six `create_service` calls on EVERY
14748                // spin, for the life of an image that would never serve them,
14749                // and the result was discarded; 1271 made it say so once, which
14750                // left the retrying. An explicit
14751                // `register_parameter_services()` still tries, because that is
14752                // a caller asking rather than the spin guessing.
14753                && p.reconcile_failure.as_ref().is_none_or(|f| !f.permanent)
14754        })
14755    }
14756
14757    /// Issue 1271 -- say, once, that the parameter services could not be
14758    /// created, instead of discarding the result on every spin.
14759    ///
14760    /// The spin keeps retrying (a node registered later, or a transport that
14761    /// comes up late, may still succeed); this only decides whether anyone is
14762    /// told. Cold and out of line: it formats, and `spin_once`'s frame must
14763    /// not carry that.
14764    #[cold]
14765    #[inline(never)]
14766    fn report_parameter_service_reconcile_failure(&mut self, e: NodeError) {
14767        let Some(params) = self.params.as_deref_mut() else {
14768            return;
14769        };
14770        if params.reconcile_failure_reported {
14771            return;
14772        }
14773        params.reconcile_failure_reported = true;
14774        // Issue 1268 — name the node and the service. "could not be created
14775        // ({:?})" named neither, so a reader could not tell a name too long for
14776        // one node from a backend that will serve none of the six.
14777        let (node_fqn, service, permanent) = match params.reconcile_failure.as_ref() {
14778            Some(f) => (f.node_fqn.as_str(), f.service, f.permanent),
14779            None => ("<unknown node>", "<unknown service>", false),
14780        };
14781        // issues 1271, 1268
14782        nros_log::log_error!(
14783            nros_log::get_logger("nros"),
14784            "parameter services could not be created for node {} at service {}: {:?}. \
14785             `ros2 param` cannot reach {} of this image's {} node(s). {}",
14786            node_fqn,
14787            service,
14788            e,
14789            self.nodes.len().max(1) - params.services.len(),
14790            self.nodes.len().max(1),
14791            if permanent {
14792                "Not retrying: this failure cannot change without a rebuild."
14793            } else {
14794                "Retrying on every spin; logged once."
14795            }
14796        );
14797    }
14798
14799    /// phase-426 W3 — publish one set of six under every node that does not
14800    /// have one yet.
14801    ///
14802    /// **Why a reconcile and not a registration.** `nros::main!` emits
14803    /// `apply_param_services` BEFORE its per-node `register` calls, by design:
14804    /// the store has to exist when each component cell captures it. So at the
14805    /// moment the request is made the node table is EMPTY and there is no FQN
14806    /// to publish under — registering there is how the six ended up pinned to
14807    /// the executor's own identity in the first place. The request is recorded
14808    /// and satisfied here, at the head of every spin, exactly as
14809    /// `reconcile_ros_time_source` does for `use_sim_time` and for the same
14810    /// reason.
14811    ///
14812    /// **An executor with no registered node still gets one set**, under its
14813    /// own `node_name`/`namespace` and keyed `NodeId::PRIMARY` — the identity
14814    /// [`declare_parameter`](Self::declare_parameter) writes to. That is the
14815    /// pre-W3 behaviour, preserved for the direct-API images that never call
14816    /// `node_builder` (`param-chatter-talker` is one), and it is keyed the same
14817    /// as the first node record, so a node registered later inherits the set
14818    /// rather than getting a second one under a different name.
14819    ///
14820    /// Cheap in the settled case: one length comparison — but the FRAME is not
14821    /// cheap, so it is `inline(never)` and the spin site tests
14822    /// [`parameter_services_pending`](Self::parameter_services_pending) first.
14823    /// Building one set used to materialise six `EmbeddedServiceServer`s by
14824    /// value (2 x `PARAM_SERVICE_BUFFER_SIZE` each, ~48 KiB at the 4096
14825    /// default) before they were boxed; inlined into `spin_once` that landed
14826    /// on every spin frame whether or not the branch was taken. Issue 1270
14827    /// took the buffers out of the set -- one pair per executor, allocated on
14828    /// the heap directly -- but the set still carries six backend handles and
14829    /// a name, so the frame stays out of `spin_once`. Issue 0756's rule one
14830    /// call up — a parameter-service frame does not fit an embedded thread
14831    /// stack, and `test_open_threaded_spawn_and_halt` died with a bare SIGSEGV
14832    /// the first time this was reachable from the spin path.
14833    #[inline(never)]
14834    pub(crate) fn reconcile_parameter_services(&mut self) -> Result<(), NodeError> {
14835        let Some(params) = self.params.as_deref() else {
14836            return Ok(());
14837        };
14838        if !params.requested {
14839            return Ok(());
14840        }
14841        // The nodes wanted, minus the ones already served. Collected first
14842        // because building a set borrows `self.session` mutably while
14843        // `self.nodes` / `self.params` are still borrowed by the scan.
14844        let want = self.nodes.len().max(1);
14845        if params.services.len() >= want {
14846            return Ok(());
14847        }
14848        //
14849        // Issue 2815 -- INDICES only. This list used to carry each node's name
14850        // and namespace (two `String<64>`s, ~130 bytes) for every slot the
14851        // node table can hold, which made this frame 9,344 bytes on a
14852        // Cortex-M. Called from `pass` (9,472 more), it overflowed a 16 KiB
14853        // main stack in ONE `sub sp`, past the MPU guard and into `.data`, so
14854        // the image faulted somewhere unrelated with no guard fault. The
14855        // names are read per node in the loop below, one pair at a time.
14856        let mut todo: heapless::Vec<u8, { crate::param_sizing::MAX_SERVICE_SETS }> =
14857            heapless::Vec::new();
14858        for index in 0..want {
14859            let key = nros_params::NodeKey::new(index as u8);
14860            if params.services.iter().any(|set| set.param_node() == key) {
14861                continue;
14862            }
14863            if todo.push(index as u8).is_err() {
14864                return Err(NodeError::NodeTableFull);
14865            }
14866        }
14867        // Issue 1270 -- the ONE buffer pair every set is answered through,
14868        // allocated with the first set so an image that declares parameters
14869        // and serves none pays nothing for it. `params` is `Some` here: the
14870        // scan above returned early otherwise.
14871        // Issue 1812 -- a carved home hands its pair over with the state, so
14872        // this is reached only on the heap fallback.
14873        if let Some(params) = self.params.as_deref_mut()
14874            && params.buffers.is_none()
14875        {
14876            // Issue 1551 — an exhausted heap is an error this fn returns, not
14877            // an abort through libstd's OOM hook.
14878            #[cfg(feature = "alloc")]
14879            {
14880                params.buffers = Some(
14881                    crate::parameter_services::ParamServiceBuffers::try_with_capacity(
14882                        crate::parameter_services::param_service_buffer_bytes(),
14883                    )
14884                    .ok_or(NodeError::Transport(TransportError::BadAlloc))?,
14885                );
14886            }
14887            #[cfg(not(feature = "alloc"))]
14888            return Err(NodeError::Transport(TransportError::BadAlloc));
14889        }
14890        for index in todo {
14891            let (name, namespace) = match self.nodes.get(usize::from(index)) {
14892                Some(record) => (record.name.clone(), record.namespace.clone()),
14893                // No node table entry: the executor's own implicit primary
14894                // identity, which is what `NodeId::PRIMARY` means.
14895                None => (self.node_name.clone(), self.namespace.clone()),
14896            };
14897            // Issue 2387 -- the set is built IN PLACE, in the state's next
14898            // inline slot. It used to come back from the builder by value and
14899            // be pushed, which moved six backend handles and a name through
14900            // this frame and the builder's; on the S32K344 island that
14901            // overflowed main's 16 KiB while the entities registered. `params`
14902            // is `Some`: the scan above returned early otherwise (issue 0756:
14903            // a `ParamState` is never built by value either).
14904            let Some(params) = self.params.as_deref_mut() else {
14905                return Err(NodeError::Transport(TransportError::BadAlloc));
14906            };
14907            let services = &mut params.services;
14908            if services.is_full() {
14909                return Err(NodeError::NodeTableFull);
14910            }
14911            let len = services.len();
14912            // SAFETY: `len < capacity`, so the slot is inside the vector's
14913            // storage and past its initialised prefix; `set_len` below runs
14914            // only once the builder has initialised it.
14915            let slot = unsafe { services.as_mut_ptr().add(len) };
14916            let built = unsafe {
14917                Self::build_parameter_service_set_at(
14918                    &mut self.session,
14919                    self.domain_id,
14920                    slot,
14921                    nros_params::NodeKey::new(index),
14922                    &name,
14923                    &namespace,
14924                )
14925            };
14926            match built {
14927                // SAFETY: the builder initialised the slot at `len`.
14928                Ok(()) => unsafe { services.set_len(len + 1) },
14929                Err((e, service)) => {
14930                    // Issue 1268 — keep WHAT failed and WHERE, for the one log
14931                    // line, and decide once whether retrying could ever help.
14932                    // `Unsupported` from the transport is a property of the
14933                    // build (the backend has no descriptor for the
14934                    // `rcl_interfaces` types), so a later spin asks the same
14935                    // question and gets the same answer.
14936                    let permanent = matches!(e, NodeError::Transport(TransportError::Unsupported));
14937                    let mut node_fqn = heapless::String::<256>::new();
14938                    if let Ok(fqn) = crate::names::fully_qualified_name(&name, &namespace) {
14939                        let _ = node_fqn.push_str(fqn.as_str());
14940                    }
14941                    params.reconcile_failure =
14942                        Some(crate::parameter_services::ParamServiceReconcileFailure {
14943                            node_fqn,
14944                            service,
14945                            permanent,
14946                        });
14947                    return Err(e);
14948                }
14949            }
14950            // phase-430 W2 — "declare `use_sim_time` on EVERY node, as rclcpp
14951            // does", said where the nodes finally exist. This is the only place
14952            // that knows the full set: `ensure_parameter_store` runs before any
14953            // node record does, so it can only seed the implicit PRIMARY, and
14954            // the further nodes an image composes onto one executor arrive
14955            // later. Seeding as each set of six goes up keeps the two in step —
14956            // the parameter is declared on exactly the nodes a
14957            // `ros2 param set <node> use_sim_time true` can reach.
14958            //
14959            // Idempotent by construction: `declare` refuses a name the node
14960            // already holds and the placeholder flag is only raised on
14961            // acceptance, so re-seeding PRIMARY here neither duplicates the
14962            // entry nor re-marks an application's own declaration as ours.
14963            self.seed_use_sim_time_default(super::node_record::NodeId::from_raw(index));
14964            // Issue 2023 — and `/parameter_events`, as rclcpp's and rclrs's
14965            // node does from its constructor. Seeded AFTER `use_sim_time`, so
14966            // the node's start-up event names it, as upstream's does.
14967            self.start_parameter_events_for_served_node(super::node_record::NodeId::from_raw(
14968                index,
14969            ));
14970        }
14971        // Issue 1271 -- every node is served now, so a later failure (a node
14972        // registered after this one) is news again and earns its own line.
14973        if let Some(params) = self.params.as_deref_mut() {
14974            params.reconcile_failure_reported = false;
14975            // Issue 1268 -- and drop the record with it, so a later failure is
14976            // reported against the node it actually happened on.
14977            params.reconcile_failure = None;
14978        }
14979        Ok(())
14980    }
14981
14982    /// phase-426 W3 — create the six service servers for ONE node.
14983    ///
14984    /// Split out of [`register_parameter_services`](Self::register_parameter_services)
14985    /// because there are now N of these per image rather than one, and because
14986    /// the six `create_param_srv` call sites are what
14987    /// `check-infra-queryable-counts` reads to hold `PARAM_SERVICE_QUERYABLES`
14988    /// to the number of queryables a set actually claims.
14989    ///
14990    /// Issue 2387 -- the set is written at `slot`
14991    /// ([`ParameterServiceServers::init_at`]), never returned by value. An
14992    /// associated fn over the session alone, so the caller can hold the slot
14993    /// (inside `self.params`) while the session creates the handles.
14994    ///
14995    /// # Safety
14996    ///
14997    /// As [`ParameterServiceServers::init_at`]: `slot` is valid for writes and
14998    /// holds no live value; on `Ok` it holds an initialised set.
14999    #[inline(never)]
15000    unsafe fn build_parameter_service_set_at(
15001        session: &mut session::ConcreteSession,
15002        domain_id: u32,
15003        slot: *mut crate::parameter_services::ParameterServiceServers,
15004        node: nros_params::NodeKey,
15005        node_name: &str,
15006        namespace: &str,
15007    ) -> Result<(), (NodeError, &'static str)> {
15008        use crate::parameter_services::{
15009            DescribeParameters, GetParameterTypes, GetParameters, ListParameters,
15010            ParamService as Svc6, ParameterServiceServers, SetParameters, SetParametersAtomically,
15011        };
15012        use nros_core::RosService;
15013
15014        // The node FQN, from the one implementation. This was the third
15015        // hand-rolled copy of the same join (`crate::names::fully_qualified_name`
15016        // is the first, `Node::fully_qualified_name` was the second) — and the
15017        // three did not agree: this one absolutised a bare namespace, that one
15018        // did not. A join with three spellings has no answer to "what does the
15019        // tree do with `my_ns`".
15020        let node_fqn = crate::names::fully_qualified_name(node_name, namespace)
15021            .map_err(|()| (NodeError::NameTooLong, "get_parameters"))?;
15022        // The service names below still take the two halves separately.
15023        let ns: &str = namespace;
15024        let nn: &str = node_name;
15025
15026        /// Build a service name like `{node_fqn}/{suffix}` and create the server handle.
15027        ///
15028        /// Issue 1268 — the error carries the SUFFIX, so a failure can name the
15029        /// service a tool would have called instead of "one of six".
15030        ///
15031        /// Issue 2387 -- never inlined: its name buffer and `ServiceInfo`
15032        /// are one frame at a time, not six side by side in the builder's.
15033        #[inline(never)]
15034        fn create_param_srv<Svc>(
15035            session: &mut session::ConcreteSession,
15036            domain_id: u32,
15037            node_fqn: &str,
15038            namespace: &str,
15039            node_name: &str,
15040            suffix: &'static str,
15041        ) -> Result<session::RmwServiceServer, (NodeError, &'static str)>
15042        where
15043            Svc: RosService,
15044            Svc::Request: crate::rmw_type_registry::MessageForRmw,
15045            Svc::Reply: crate::rmw_type_registry::MessageForRmw,
15046        {
15047            // Issue 1268 — REGISTER THE TYPES FIRST, exactly as a typed user
15048            // service does (`register_service_sized`). A backend that keys
15049            // topics on a registered type descriptor — Cyclone does — fails
15050            // `create_service` with `Unsupported` for a type it has never been
15051            // told about, and nothing else in the image registers the
15052            // `rcl_interfaces` service types: the generated typesupport of a
15053            // downstream covers ITS OWN message packages, and the backend bakes
15054            // in only `ParticipantEntitiesInfo` for the graph. So the six
15055            // parameter services failed on every spin while the image's own
15056            // services worked, which is what made the cause look like "no
15057            // service support" for two phases (the issue-0745 comment).
15058            //
15059            // A no-op on backends that need no descriptors (zenoh, xrce), which
15060            // is why zenoh served this same image all along.
15061            let register = |e: NodeError| (e, suffix);
15062            crate::rmw_type_registry::register_type::<Svc::Request>().map_err(register)?;
15063            crate::rmw_type_registry::register_type::<Svc::Reply>().map_err(register)?;
15064            let mut name = heapless::String::<256>::new();
15065            name.push_str(node_fqn)
15066                .map_err(|_| (NodeError::NameTooLong, suffix))?;
15067            name.push_str("/")
15068                .map_err(|_| (NodeError::NameTooLong, suffix))?;
15069            name.push_str(suffix)
15070                .map_err(|_| (NodeError::NameTooLong, suffix))?;
15071            let mut info = ServiceInfo::new(&name, Svc::SERVICE_NAME, Svc::SERVICE_HASH)
15072                // issue 0824 follow-up — `domain_id` is a PARAMETER, not `self.domain_id`:
15073                // this is a nested `fn`, not a method, so `self` is not in scope and
15074                // the original spelling was E0434. It only fails under feature sets
15075                // that compile this arm, which is why `--all-features` caught it and
15076                // the narrower lanes did not.
15077                .with_domain(domain_id)
15078                .with_namespace(namespace);
15079            if !node_name.is_empty() {
15080                info = info.with_node_name(node_name);
15081            }
15082            // issue 0793 — the parameter services get the PARAMETER profile
15083            // (`rmw_qos_profile_parameters`: KEEP_LAST(1000), reliable,
15084            // volatile), not the generic services one. `QOS_PROFILE_PARAMETERS`
15085            // existed with the right depth and had no caller, so every parameter
15086            // server ran on a depth-10 queue while ROS 2 gives them 1000 — which
15087            // matters exactly when a tool sets many parameters at once, the case
15088            // the deep queue is for.
15089            // Issue 2920 -- the runtime's own profile: fitted, never refused.
15090            let supported = Session::supported_qos_policies(&*session);
15091            let qos = super::node::fit_runtime_qos(
15092                QoSProfile::parameter_services_default(),
15093                supported,
15094                "service",
15095                &name,
15096            );
15097            session
15098                .create_service(&info, qos)
15099                .map_err(|e| (NodeError::Transport(e), suffix))
15100        }
15101
15102        // SAFETY: the caller's contract is `init_at`'s, passed through.
15103        unsafe {
15104            ParameterServiceServers::init_at(
15105                slot,
15106                // phase-426 W3 — the set carries the node whose parameters it
15107                // serves, so a handler can never read the store without saying
15108                // whose parameters it means.
15109                node,
15110                // Issue 1271 -- carried so a dropped request is reported
15111                // against the service a tool actually called.
15112                node_fqn.as_str(),
15113                // Issue 1270 -- handles only. The buffers are the executor's
15114                // one shared pair (`ParamState::buffers`), not six per node.
15115                |svc| match svc {
15116                    Svc6::Get => {
15117                        let h = create_param_srv::<GetParameters>(
15118                            session,
15119                            domain_id,
15120                            &node_fqn,
15121                            ns,
15122                            nn,
15123                            "get_parameters",
15124                        )?;
15125                        Ok(h)
15126                    }
15127                    Svc6::Set => {
15128                        let h = create_param_srv::<SetParameters>(
15129                            session,
15130                            domain_id,
15131                            &node_fqn,
15132                            ns,
15133                            nn,
15134                            "set_parameters",
15135                        )?;
15136                        Ok(h)
15137                    }
15138                    Svc6::SetAtomically => {
15139                        let h = create_param_srv::<SetParametersAtomically>(
15140                            session,
15141                            domain_id,
15142                            &node_fqn,
15143                            ns,
15144                            nn,
15145                            "set_parameters_atomically",
15146                        )?;
15147                        Ok(h)
15148                    }
15149                    Svc6::List => {
15150                        let h = create_param_srv::<ListParameters>(
15151                            session,
15152                            domain_id,
15153                            &node_fqn,
15154                            ns,
15155                            nn,
15156                            "list_parameters",
15157                        )?;
15158                        Ok(h)
15159                    }
15160                    Svc6::Describe => {
15161                        let h = create_param_srv::<DescribeParameters>(
15162                            session,
15163                            domain_id,
15164                            &node_fqn,
15165                            ns,
15166                            nn,
15167                            "describe_parameters",
15168                        )?;
15169                        Ok(h)
15170                    }
15171                    Svc6::GetTypes => {
15172                        let h = create_param_srv::<GetParameterTypes>(
15173                            session,
15174                            domain_id,
15175                            &node_fqn,
15176                            ns,
15177                            nn,
15178                            "get_parameter_types",
15179                        )?;
15180                        Ok(h)
15181                    }
15182                },
15183            )
15184        }
15185    }
15186
15187    /// The node FQNs this executor publishes parameter services
15188    /// under, in registration order.
15189    ///
15190    /// The acceptance question for W3 ("does a two-node image expose both
15191    /// FQNs?") answered without a wire: the six services are created from
15192    /// exactly this list, so asserting it asserts what `ros2 param list` will
15193    /// enumerate. The wire assertion is W6.
15194    pub fn parameter_service_node_names(
15195        &self,
15196    ) -> heapless::Vec<crate::names::ResolvedName, { crate::param_sizing::MAX_SERVICE_SETS }> {
15197        let mut out = heapless::Vec::new();
15198        let Some(params) = self.params.as_deref() else {
15199            return out;
15200        };
15201        for set in params.services.iter() {
15202            let index = set.param_node().raw() as usize;
15203            let (name, namespace) = match self.nodes.get(index) {
15204                Some(record) => (record.name.as_str(), record.namespace.as_str()),
15205                None => (self.node_name.as_str(), self.namespace.as_str()),
15206            };
15207            if let Ok(fqn) = crate::names::fully_qualified_name(name, namespace) {
15208                let _ = out.push(fqn);
15209            }
15210        }
15211        out
15212    }
15213
15214    // phase-359 W10 / issue 0080 — ~~`enable_parameter_persistence{,_with}`~~ are
15215    // GONE with the seam they attached. Issue 0080 ruled on-device parameter
15216    // persistence a non-goal in July and listed both by name; nothing in the
15217    // tree ever called them, and the only backend that could be passed
15218    // (~~`FileParamStore`~~) is deleted. Runtime get/set/describe stay — it is the
15219    // PERSISTENCE half that was dropped.
15220}
15221
15222// ============================================================================
15223// Lifecycle services (cfg lifecycle-services)
15224// ============================================================================
15225
15226/// RFC-0128 D2 (phase-554 W2.b) -- tell a metadata probe that a node's own
15227/// code made it a lifecycle node. Called by the CODE-facing registrations
15228/// only, after their machine exists, so a refused registration reports
15229/// nothing and a launch file's machine (`register_managed_node_on`) is not
15230/// mistaken for the code's.
15231#[cfg(feature = "lifecycle-services")]
15232#[cfg_attr(not(feature = "registration-observer"), allow(unused_variables))]
15233fn observe_code_managed(namespace: &str, name: &str) {
15234    #[cfg(feature = "registration-observer")]
15235    super::registration_observer::observe_lifecycle(
15236        super::registration_observer::ObservedLifecycle { name, namespace },
15237    );
15238}
15239
15240#[cfg(feature = "lifecycle-services")]
15241impl<'s> Executor<'s> {
15242    /// Register the five REP-2002 lifecycle services on this executor.
15243    ///
15244    /// After this call, `ros2 lifecycle set|get|list|nodes` can drive the
15245    /// stored [`LifecyclePollingNodeCtx`](crate::lifecycle::LifecyclePollingNodeCtx)
15246    /// through the node's lifecycle. The state machine is created fresh
15247    /// (starting in `Unconfigured`); callers register their transition
15248    /// callbacks via [`Executor::lifecycle_state_machine_mut`].
15249    ///
15250    /// # Safety
15251    /// Registered callbacks on the state machine are C FFI function pointers.
15252    /// The caller must keep the callback code and any context it captures
15253    /// valid for as long as the executor processes services.
15254    ///
15255    /// The machine is served under the image's PRIMARY node, the one
15256    /// [`entity_identity`](Self::entity_identity) gives every executor-level
15257    /// entity, so `ros2 lifecycle get /<node>` finds it. Only an image that declares no node keeps the executor's
15258    /// configured name; with none, it is refused
15259    /// ([`NodeError::LifecycleNodeUnnamed`]) rather than served as
15260    /// `//get_state`. The machine keeps the executor-scoped key, so the
15261    /// executor-scoped accessors behave as before, and the primary node
15262    /// cannot get a second one through
15263    /// [`register_lifecycle_services_on`](Self::register_lifecycle_services_on).
15264    // RFC-0128 D8; issues 2626 and 2429.
15265    pub fn register_lifecycle_services(&mut self) -> Result<(), NodeError> {
15266        let (nn, ns, _) = self.entity_identity(None)?;
15267        self.register_lifecycle_services_named(None, &ns, &nn)?;
15268        observe_code_managed(&ns, &nn);
15269        Ok(())
15270    }
15271
15272    /// The node a lifecycle machine key is served under: its own node, or for
15273    /// the executor-scoped key the primary node when the image has one
15274    /// (RFC-0128 D8). `None` only for a zero-node image's machine.
15275    fn lifecycle_served_on(
15276        &self,
15277        key: Option<super::node_record::NodeId>,
15278    ) -> Option<super::node_record::NodeId> {
15279        key.or_else(|| (!self.nodes.is_empty()).then_some(super::node_record::NodeId::PRIMARY))
15280    }
15281
15282    /// [`register_lifecycle_services`](Self::register_lifecycle_services),
15283    /// named after `node` rather than the executor's own identity.
15284    ///
15285    /// A hosted C++ `rclcpp_lifecycle::LifecycleNode` (as Nav2 uses)
15286    /// is a node CREATED on the process executor, whose own identity is the
15287    /// default `node`. Registering through the executor served
15288    /// `/node/change_state` beside a phantom `/node`, and `ros2 lifecycle get
15289    /// /velocity_smoother` answered "Node not found". Parameter services were
15290    /// already per node (the reconcile); this is the same for lifecycle.
15291    pub fn register_lifecycle_services_on(
15292        &mut self,
15293        node: super::node_record::NodeId,
15294    ) -> Result<(), NodeError> {
15295        let (ns, nn) = self.node_identity(node)?;
15296        self.register_lifecycle_services_named(Some(node), &ns, &nn)?;
15297        observe_code_managed(&ns, &nn);
15298        Ok(())
15299    }
15300
15301    /// `node`'s namespace and final name, as the node table holds them.
15302    fn node_identity(
15303        &self,
15304        node: super::node_record::NodeId,
15305    ) -> Result<(heapless::String<64>, heapless::String<64>), NodeError> {
15306        let r = self.node(node).ok_or(NodeError::NotInitialized)?;
15307        Ok((r.namespace.clone(), r.name.clone()))
15308    }
15309
15310    /// RFC-0128 D1: adds `key`'s machine to the table. A node that already
15311    /// has one is refused rather than replaced (a replacement dropped the
15312    /// first machine's servers silently, and two C++ `LifecycleNode`s on one
15313    /// executor overwrote each other that way); a full table is refused with
15314    /// the error that names the node-table knob.
15315    fn register_lifecycle_services_named(
15316        &mut self,
15317        key: Option<super::node_record::NodeId>,
15318        ns: &str,
15319        nn: &str,
15320    ) -> Result<(), NodeError> {
15321        // RFC-0128 D8 (issue 2429): a machine is named after a declared
15322        // node. An empty name would serve `//get_state`, which no
15323        // `ros2 lifecycle` command can reach.
15324        if nn.is_empty() {
15325            return Err(NodeError::LifecycleNodeUnnamed);
15326        }
15327        // One machine per node it is SERVED on (issue 2626): the
15328        // executor-scoped machine is served on the primary node, so a second
15329        // registration on that node, by either spelling, is refused.
15330        let served = self.lifecycle_served_on(key);
15331        if self
15332            .lifecycle
15333            .iter()
15334            .any(|e| e.node == key || (served.is_some() && e.served_on == served))
15335        {
15336            return Err(NodeError::LifecycleAlreadyRegistered);
15337        }
15338        if self.lifecycle.len() >= crate::lifecycle_services::MAX_LIFECYCLE_MACHINES {
15339            return Err(NodeError::NodeTableFull);
15340        }
15341        use crate::{
15342            lifecycle::LifecyclePollingNodeCtx,
15343            lifecycle_services::{
15344                ChangeState, GetAvailableStates, GetAvailableTransitions, GetState,
15345                LifecycleRuntimeState, LifecycleServiceServers,
15346            },
15347        };
15348        use nros_core::RosService;
15349
15350        // Build the node FQN from namespace + node_name (same convention as
15351        // register_parameter_services).
15352        let mut node_fqn = heapless::String::<256>::new();
15353        if ns.is_empty() || ns == "/" {
15354            node_fqn.push_str("/").map_err(|_| NodeError::NameTooLong)?;
15355            node_fqn.push_str(nn).map_err(|_| NodeError::NameTooLong)?;
15356        } else {
15357            node_fqn.push_str("/").map_err(|_| NodeError::NameTooLong)?;
15358            node_fqn
15359                .push_str(ns.trim_matches('/'))
15360                .map_err(|_| NodeError::NameTooLong)?;
15361            node_fqn.push_str("/").map_err(|_| NodeError::NameTooLong)?;
15362            node_fqn.push_str(nn).map_err(|_| NodeError::NameTooLong)?;
15363        }
15364
15365        fn create_lc_srv<Svc>(
15366            session: &mut session::ConcreteSession,
15367            domain_id: u32,
15368            node_fqn: &str,
15369            namespace: &str,
15370            node_name: &str,
15371            suffix: &str,
15372        ) -> Result<session::RmwServiceServer, NodeError>
15373        where
15374            Svc: RosService,
15375            Svc::Request: crate::rmw_type_registry::MessageForRmw,
15376            Svc::Reply: crate::rmw_type_registry::MessageForRmw,
15377        {
15378            // Issue 1293 — register both halves first, as `create_param_srv`
15379            // does since issue 1268: Cyclone creates a topic only for a type it
15380            // holds a descriptor for. Three of the five request types are
15381            // EMPTY, and an empty schema had no descriptor until codegen gave
15382            // it rosidl's `structure_needs_at_least_one_member` byte. A no-op
15383            // on backends that need no descriptors (zenoh, xrce).
15384            crate::rmw_type_registry::register_type::<Svc::Request>()?;
15385            crate::rmw_type_registry::register_type::<Svc::Reply>()?;
15386            let mut name = heapless::String::<256>::new();
15387            name.push_str(node_fqn)
15388                .map_err(|_| NodeError::NameTooLong)?;
15389            name.push_str("/").map_err(|_| NodeError::NameTooLong)?;
15390            name.push_str(suffix).map_err(|_| NodeError::NameTooLong)?;
15391            let mut info = ServiceInfo::new(&name, Svc::SERVICE_NAME, Svc::SERVICE_HASH)
15392                .with_domain(domain_id)
15393                .with_namespace(namespace);
15394            if !node_name.is_empty() {
15395                info = info.with_node_name(node_name);
15396            }
15397            // Issue 2920 -- the runtime's own profile: fitted, never refused.
15398            let supported = Session::supported_qos_policies(&*session);
15399            let qos = super::node::fit_runtime_qos(
15400                QoSProfile::services_default(),
15401                supported,
15402                "service",
15403                &name,
15404            );
15405            session
15406                .create_service(&info, qos)
15407                .map_err(NodeError::Transport)
15408        }
15409
15410        /// Issue 1587 — the ONE publisher the REP-2002 family claims,
15411        /// `~/transition_event`. Shaped like `create_lc_srv` beside it both
15412        /// because the naming rule is the same (node FQN + suffix) and
15413        /// because `check-infra-queryable-counts` counts the creation sites
15414        /// to hold `LIFECYCLE_SERVICE_PUBLISHERS` to them, exactly as it
15415        /// already holds `LIFECYCLE_SERVICE_QUERYABLES` to the five above.
15416        fn create_lc_pub<Msg: crate::rmw_type_registry::MessageForRmw>(
15417            session: &mut session::ConcreteSession,
15418            domain_id: u32,
15419            node_fqn: &str,
15420            namespace: &str,
15421            node_name: &str,
15422            suffix: &str,
15423            qos: QoSProfile,
15424        ) -> Result<session::RmwPublisher, NodeError> {
15425            // Issue 1293 — same rule as `create_lc_srv`: Cyclone needs the
15426            // `TransitionEvent` descriptor before it can create the topic.
15427            crate::rmw_type_registry::register_type::<Msg>()?;
15428            let mut name = heapless::String::<256>::new();
15429            name.push_str(node_fqn)
15430                .map_err(|_| NodeError::NameTooLong)?;
15431            name.push_str("/").map_err(|_| NodeError::NameTooLong)?;
15432            name.push_str(suffix).map_err(|_| NodeError::NameTooLong)?;
15433            let mut info = TopicInfo::new(
15434                &name,
15435                <Msg as nros_core::RosMessage>::TYPE_NAME,
15436                Msg::TYPE_HASH,
15437            )
15438            .with_domain(domain_id)
15439            .with_namespace(namespace);
15440            if !node_name.is_empty() {
15441                info = info.with_node_name(node_name);
15442            }
15443            // Issue 2920 -- the runtime's own profile: fitted, never refused.
15444            let supported = Session::supported_qos_policies(&*session);
15445            let qos = super::node::fit_runtime_qos(qos, supported, "publisher", &name);
15446            session
15447                .create_publisher(&info, qos)
15448                .map_err(NodeError::Transport)
15449        }
15450
15451        let cs_handle = create_lc_srv::<ChangeState>(
15452            &mut self.session,
15453            self.domain_id,
15454            &node_fqn,
15455            ns,
15456            nn,
15457            "change_state",
15458        )?;
15459        let gs_handle = create_lc_srv::<GetState>(
15460            &mut self.session,
15461            self.domain_id,
15462            &node_fqn,
15463            ns,
15464            nn,
15465            "get_state",
15466        )?;
15467        let gas_handle = create_lc_srv::<GetAvailableStates>(
15468            &mut self.session,
15469            self.domain_id,
15470            &node_fqn,
15471            ns,
15472            nn,
15473            "get_available_states",
15474        )?;
15475        let gat_handle = create_lc_srv::<GetAvailableTransitions>(
15476            &mut self.session,
15477            self.domain_id,
15478            &node_fqn,
15479            ns,
15480            nn,
15481            "get_available_transitions",
15482        )?;
15483        let gtg_handle = create_lc_srv::<GetAvailableTransitions>(
15484            &mut self.session,
15485            self.domain_id,
15486            &node_fqn,
15487            ns,
15488            nn,
15489            "get_transition_graph",
15490        )?;
15491
15492        // Issue 1587 — REP-2002's communication interface is the five
15493        // services PLUS this. VOLATILE, so it costs a publisher slot and a
15494        // liveliness token and NO queryable; see
15495        // `LIFECYCLE_SERVICE_PUBLISHERS` for the measurement that settled it.
15496        let te_handle = create_lc_pub::<nros_lifecycle_msgs::msg::TransitionEvent>(
15497            &mut self.session,
15498            self.domain_id,
15499            &node_fqn,
15500            ns,
15501            nn,
15502            crate::lifecycle_services::TRANSITION_EVENT_SUFFIX,
15503            crate::lifecycle_services::transition_event_qos(),
15504        )?;
15505
15506        // Issue 2070 -- built in their allocation, never on this frame.
15507        let servers = LifecycleServiceServers::try_new_boxed([
15508            cs_handle, gs_handle, gas_handle, gat_handle, gtg_handle,
15509        ])
15510        .ok_or(NodeError::Transport(TransportError::BadAlloc))?;
15511
15512        let mut state = alloc::boxed::Box::new(LifecycleRuntimeState {
15513            state_machine: LifecyclePollingNodeCtx::new(),
15514            services: servers,
15515            transition_event: te_handle,
15516        });
15517        // RFC-0128 D3: the served node's publishers follow this machine from
15518        // now on. A zero-node image's machine has no node and gates nothing.
15519        if let Some(r) = served.and_then(|id| self.nodes.get(id.index())) {
15520            state
15521                .state_machine
15522                .bind_publish_gate(core::ptr::NonNull::from(&r.publish_gate));
15523        }
15524        self.lifecycle
15525            .try_reserve(1)
15526            .map_err(|_| NodeError::Transport(TransportError::BadAlloc))?;
15527        self.lifecycle
15528            .push(crate::lifecycle_services::LifecycleEntry {
15529                node: key,
15530                served_on: served,
15531                state,
15532            });
15533
15534        Ok(())
15535    }
15536
15537    /// The `~/transition_event` publisher, for the tests that assert what
15538    /// reached the wire. Not a public capability: the executor announces, and
15539    /// a second publisher on the same topic would be a second source of truth.
15540    /// Its only callers are the mock-session tests, which a `rmw-cffi` build
15541    /// does not compile.
15542    #[cfg(all(test, not(feature = "rmw-cffi")))]
15543    pub(crate) fn lifecycle_service_names(
15544        &self,
15545        node: Option<super::node_record::NodeId>,
15546    ) -> Option<[alloc::string::String; 5]> {
15547        self.lifecycle_entry(node)
15548            .map(|lc| lc.state.services.service_names())
15549    }
15550
15551    /// The `~/transition_event` publisher (see above).
15552    #[cfg(all(test, not(feature = "rmw-cffi")))]
15553    pub(crate) fn lifecycle_transition_event_publisher(&self) -> Option<&session::RmwPublisher> {
15554        self.lifecycle_entry(None)
15555            .map(|lc| &lc.state.transition_event)
15556    }
15557
15558    /// The single-machine view the executor-scoped accessors keep (RFC-0128
15559    /// D1): the machine registered on the executor's own identity, else the
15560    /// only machine there is. With several node machines and none on the
15561    /// identity it is `None`, because "the" machine is not defined; callers
15562    /// that know their node use the `_on` accessors.
15563    fn lifecycle_entry(
15564        &self,
15565        node: Option<super::node_record::NodeId>,
15566    ) -> Option<&crate::lifecycle_services::LifecycleEntry> {
15567        match node {
15568            Some(id) => self
15569                .lifecycle
15570                .iter()
15571                .find(|e| e.node == node)
15572                .or_else(|| self.lifecycle.iter().find(|e| e.served_on == Some(id))),
15573            None => self.lifecycle.iter().find(|e| e.node.is_none()).or(
15574                match self.lifecycle.as_slice() {
15575                    [only] => Some(only),
15576                    _ => None,
15577                },
15578            ),
15579        }
15580    }
15581
15582    fn lifecycle_entry_mut(
15583        &mut self,
15584        node: Option<super::node_record::NodeId>,
15585    ) -> Option<&mut crate::lifecycle_services::LifecycleEntry> {
15586        let idx = match node {
15587            Some(id) => self
15588                .lifecycle
15589                .iter()
15590                .position(|e| e.node == node)
15591                .or_else(|| self.lifecycle.iter().position(|e| e.served_on == Some(id))),
15592            None => self
15593                .lifecycle
15594                .iter()
15595                .position(|e| e.node.is_none())
15596                .or_else(|| (self.lifecycle.len() == 1).then_some(0)),
15597        }?;
15598        self.lifecycle.get_mut(idx)
15599    }
15600
15601    /// Mutable access to the lifecycle state machine, if registered.
15602    ///
15603    /// Used to register transition callbacks before spinning and to read the
15604    /// current state from application code.
15605    pub fn lifecycle_state_machine_mut(
15606        &mut self,
15607    ) -> Option<&mut crate::lifecycle::LifecyclePollingNodeCtx> {
15608        self.lifecycle_entry_mut(None)
15609            .map(|lc| &mut lc.state.state_machine)
15610    }
15611
15612    /// `node`'s own lifecycle state machine, if it registered one
15613    /// (per-node lifecycle).
15614    pub fn lifecycle_state_machine_on_mut(
15615        &mut self,
15616        node: super::node_record::NodeId,
15617    ) -> Option<&mut crate::lifecycle::LifecyclePollingNodeCtx> {
15618        self.lifecycle_entry_mut(Some(node))
15619            .map(|lc| &mut lc.state.state_machine)
15620    }
15621
15622    /// `node`'s own lifecycle state machine, if it registered one
15623    /// (per-node lifecycle).
15624    pub fn lifecycle_state_machine_on(
15625        &self,
15626        node: super::node_record::NodeId,
15627    ) -> Option<&crate::lifecycle::LifecyclePollingNodeCtx> {
15628        self.lifecycle_entry(Some(node))
15629            .map(|lc| &lc.state.state_machine)
15630    }
15631
15632    /// Immutable access to the lifecycle state machine, if registered.
15633    pub fn lifecycle_state_machine(&self) -> Option<&crate::lifecycle::LifecyclePollingNodeCtx> {
15634        self.lifecycle_entry(None).map(|lc| &lc.state.state_machine)
15635    }
15636
15637    /// Register a safe lifecycle node.
15638    ///
15639    /// Binds the five REP-2002 lifecycle services and wires each transition to
15640    /// the [`LifecycleCallbacks`](crate::lifecycle::LifecycleCallbacks) trait
15641    /// impl — the safe Rust counterpart to the C++ `nros::LifecycleNode`. No
15642    /// `unsafe` in user code; alloc-free (monomorphized trampolines).
15643    ///
15644    /// `node` must outlive this executor's lifecycle registration: the context
15645    /// pointer stored here is dereferenced on every transition until the
15646    /// executor is finalized. The executor spins single-threaded, so the
15647    /// `&mut node` reconstituted inside a callback is never aliased.
15648    pub fn register_lifecycle_node<T: crate::lifecycle::LifecycleCallbacks>(
15649        &mut self,
15650        node: &mut T,
15651    ) -> Result<(), NodeError> {
15652        use crate::lifecycle::{LifecycleCallbackSlot as Slot, trampolines};
15653
15654        self.register_lifecycle_services()?;
15655        let sm = self
15656            .lifecycle_state_machine_mut()
15657            .ok_or(NodeError::NotInitialized)?;
15658        sm.set_context(node as *mut T as *mut core::ffi::c_void);
15659        sm.register(Slot::Configure, Some(trampolines::on_configure::<T>));
15660        sm.register(Slot::Activate, Some(trampolines::on_activate::<T>));
15661        sm.register(Slot::Deactivate, Some(trampolines::on_deactivate::<T>));
15662        sm.register(Slot::Cleanup, Some(trampolines::on_cleanup::<T>));
15663        sm.register(Slot::Shutdown, Some(trampolines::on_shutdown::<T>));
15664        sm.register(Slot::Error, Some(trampolines::on_error::<T>));
15665        Ok(())
15666    }
15667
15668    /// [`register_lifecycle_node`](Self::register_lifecycle_node) for one
15669    /// node of several: the machine is `node`'s own, served
15670    /// under its name, and independent of every other node's.
15671    pub fn register_lifecycle_node_on<T: crate::lifecycle::LifecycleCallbacks>(
15672        &mut self,
15673        node_id: super::node_record::NodeId,
15674        node: &mut T,
15675    ) -> Result<(), NodeError> {
15676        use crate::lifecycle::{LifecycleCallbackSlot as Slot, trampolines};
15677
15678        self.register_lifecycle_services_on(node_id)?;
15679        let sm = self
15680            .lifecycle_state_machine_on_mut(node_id)
15681            .ok_or(NodeError::NotInitialized)?;
15682        sm.set_context(node as *mut T as *mut core::ffi::c_void);
15683        sm.register(Slot::Configure, Some(trampolines::on_configure::<T>));
15684        sm.register(Slot::Activate, Some(trampolines::on_activate::<T>));
15685        sm.register(Slot::Deactivate, Some(trampolines::on_deactivate::<T>));
15686        sm.register(Slot::Cleanup, Some(trampolines::on_cleanup::<T>));
15687        sm.register(Slot::Shutdown, Some(trampolines::on_shutdown::<T>));
15688        sm.register(Slot::Error, Some(trampolines::on_error::<T>));
15689        Ok(())
15690    }
15691
15692    /// The nodes that hold a lifecycle state machine, in registration order.
15693    /// `None` is the machine on the executor's own identity.
15694    pub fn lifecycle_machine_nodes(
15695        &self,
15696    ) -> impl Iterator<Item = Option<super::node_record::NodeId>> + '_ {
15697        self.lifecycle.iter().map(|e| e.node)
15698    }
15699
15700    /// The node a generated entry names as
15701    /// managed, found by its final name and namespace.
15702    ///
15703    /// The namespace is compared without its leading and trailing `/`, so the
15704    /// model's `/` (root) and a node built with `""` or `/` are one namespace,
15705    /// as they are in the node's FQN.
15706    pub fn managed_node_id(
15707        &self,
15708        name: &str,
15709        namespace: &str,
15710    ) -> Option<super::node_record::NodeId> {
15711        let want = namespace.trim_matches('/');
15712        self.nodes
15713            .iter()
15714            .enumerate()
15715            .find(|(_, n)| {
15716                n.name.as_str() == name && n.namespace.as_str().trim_matches('/') == want
15717            })
15718            .map(|(index, _)| super::node_record::NodeId::from_raw(index as u8))
15719    }
15720
15721    /// Make `node` a managed node: give it a
15722    /// machine, served under its own name, unless it already has one.
15723    ///
15724    /// "Already has one" is the component-declared case: a C++ component
15725    /// deriving `rclcpp_lifecycle::LifecycleNode` registers its own machine
15726    /// (with its callbacks) while it is constructed, and the launch file may
15727    /// also say `<lifecycle_node>`. Both say the same thing, so the existing
15728    /// machine is kept rather than refused.
15729    pub fn register_managed_node_on(
15730        &mut self,
15731        node: super::node_record::NodeId,
15732    ) -> Result<(), NodeError> {
15733        if self.lifecycle_state_machine_on(node).is_some() {
15734            return Ok(());
15735        }
15736        // Not through `register_lifecycle_services_on`: this machine is the
15737        // LAUNCH file's, not the code's, so a metadata probe must not record
15738        // it as a code-managed node (phase-554 W2.b). A plain node a launch
15739        // file marks would otherwise be managed under every other launch file.
15740        let (ns, nn) = self.node_identity(node)?;
15741        self.register_lifecycle_services_named(Some(node), &ns, &nn)
15742    }
15743
15744    /// Drive `node`'s machine toward its boot `autostart`
15745    /// (0 none, 1 configure, 2 active).
15746    ///
15747    /// Each step runs only from the state it starts from (`configure` from
15748    /// `unconfigured`, `activate` from `inactive`), so a component that
15749    /// already drove its own machine is left where it put itself. A node
15750    /// with no machine has nothing to drive, so this returns `Ok`.
15751    ///
15752    /// # Safety
15753    /// The machine's registered transition callbacks run here; the caller
15754    /// must keep them and their context valid (as for
15755    /// [`LifecyclePollingNodeCtx::trigger_transition`](crate::lifecycle::LifecyclePollingNodeCtx::trigger_transition)).
15756    pub unsafe fn drive_lifecycle_autostart_on(
15757        &mut self,
15758        node: super::node_record::NodeId,
15759        autostart: u8,
15760    ) -> Result<(), crate::lifecycle::LifecycleError> {
15761        use crate::{LifecycleState, LifecycleTransition};
15762        let Some(sm) = self.lifecycle_state_machine_on_mut(node) else {
15763            return Ok(());
15764        };
15765        if autostart >= 1 && sm.state() == LifecycleState::Unconfigured {
15766            // SAFETY: forwarded through this function's contract.
15767            unsafe { sm.trigger_transition(LifecycleTransition::Configure) }?;
15768        }
15769        if autostart >= 2 && sm.state() == LifecycleState::Inactive {
15770            // SAFETY: forwarded through this function's contract.
15771            unsafe { sm.trigger_transition(LifecycleTransition::Activate) }?;
15772        }
15773        Ok(())
15774    }
15775
15776    /// Per-node lifecycle ("the code decides, as in ROS 2") —
15777    /// drive every node whose own code registered a lifecycle machine to
15778    /// `autostart`, in node-table order, and return how many were driven.
15779    ///
15780    /// This is a self-bringup's whole managed set: it has no launch file to
15781    /// mark a node, so a node is managed exactly when its component made it a
15782    /// lifecycle node. A node with no machine is plain and is left alone;
15783    /// nothing is inferred from which node was built first.
15784    ///
15785    /// # Safety
15786    /// As [`drive_lifecycle_autostart_on`](Self::drive_lifecycle_autostart_on).
15787    pub unsafe fn drive_code_managed_autostart(
15788        &mut self,
15789        autostart: u8,
15790    ) -> Result<usize, crate::lifecycle::LifecycleError> {
15791        let mut driven = 0;
15792        for index in 0..self.nodes.len() {
15793            let node = super::node_record::NodeId::from_raw(index as u8);
15794            if self.lifecycle_state_machine_on(node).is_none() {
15795                continue;
15796            }
15797            // SAFETY: forwarded through this function's contract.
15798            unsafe { self.drive_lifecycle_autostart_on(node, autostart) }?;
15799            driven += 1;
15800        }
15801        Ok(driven)
15802    }
15803}
15804
15805// ============================================================================
15806// phase-446 W6 -- the contract's declared parameters (cfg param-services)
15807// ============================================================================
15808
15809#[cfg(feature = "param-store")]
15810impl<'s> Executor<'s> {
15811    /// Hand the executor the parameters each node's contract declares.
15812    ///
15813    /// The entry calls this before any node registers. It only RECORDS the
15814    /// table: the check runs where an application declares a parameter (the
15815    /// `nros` node runtime), not in [`Self::declare_parameter_on`], because
15816    /// that funnel also carries the launch seed, whose value type is still
15817    /// inferred from text and was already held to the contract by the
15818    /// resolver.
15819    pub fn set_declared_params(&mut self, declared: nros_params::DeclaredParams) {
15820        self.declared_params = declared;
15821    }
15822
15823    /// The table [`Self::set_declared_params`] recorded (empty by default).
15824    pub fn declared_params(&self) -> nros_params::DeclaredParams {
15825        self.declared_params
15826    }
15827}
15828
15829// ============================================================================
15830// Parameter declaration API (cfg param-services)
15831// ============================================================================
15832
15833#[cfg(feature = "param-store")]
15834impl<'s> Executor<'s> {
15835    /// Issue 2670 -- tell a metadata probe that Rust code declared a parameter
15836    /// through one of this crate's own declaration routes. Called by those
15837    /// four routes only (see
15838    /// [`ObservedParameterDeclare`](super::registration_observer::ObservedParameterDeclare)),
15839    /// before the store answers. Compiles to nothing without
15840    /// `registration-observer`.
15841    #[inline]
15842    #[cfg_attr(not(feature = "registration-observer"), allow(unused_variables))]
15843    pub(crate) fn observe_code_parameter_declare(
15844        &self,
15845        node: super::node_record::NodeId,
15846        name: &str,
15847        value: Option<&nros_params::ParameterValue>,
15848        parameter_type: nros_params::ParameterType,
15849    ) {
15850        #[cfg(feature = "registration-observer")]
15851        if let Some(record) = self.nodes.get(node.index()) {
15852            super::registration_observer::observe_parameter_declare(
15853                super::registration_observer::ObservedParameterDeclare {
15854                    node_name: record.name.as_str(),
15855                    node_namespace: record.namespace.as_str(),
15856                    name,
15857                    value,
15858                    parameter_type,
15859                },
15860            );
15861        }
15862    }
15863
15864    // Issue 2964.
15865    /// Tell a metadata probe that `node` opted into undeclared parameters, so
15866    /// its recorded declarations are a floor, not a count. Compiles to nothing
15867    /// without `registration-observer`.
15868    #[inline]
15869    #[cfg_attr(not(feature = "registration-observer"), allow(unused_variables))]
15870    pub(crate) fn observe_undeclared_parameters(&self, node: super::node_record::NodeId) {
15871        #[cfg(feature = "registration-observer")]
15872        if let Some(record) = self.nodes.get(node.index()) {
15873            super::registration_observer::observe_undeclared_parameters(
15874                super::registration_observer::ObservedUndeclaredParameters {
15875                    node_name: record.name.as_str(),
15876                    node_namespace: record.namespace.as_str(),
15877                },
15878            );
15879        }
15880    }
15881
15882    /// Build the parameter STORE and register no service.
15883    ///
15884    /// What an image declaring the `params` axis (and not `param_services`)
15885    /// calls ahead of its nodes: launch seeds and `declare_parameter` land in
15886    /// the store, and `ros2 param` reaches none of it, because no queryable
15887    /// was created. The primary node's `use_sim_time` placeholder is seeded
15888    /// as it is for a served store; nothing can SET it here, which is the
15889    /// axis' stated limit.
15890    ///
15891    /// Idempotent, and a later [`Self::register_parameter_services`] keeps
15892    /// this store and adds the six services on top of it.
15893    pub fn register_parameter_store(&mut self) -> Result<(), NodeError> {
15894        if self.ensure_parameter_store() {
15895            Ok(())
15896        } else {
15897            Err(NodeError::Transport(TransportError::BadAlloc))
15898        }
15899    }
15900
15901    /// Issue 0745 — lazily create the parameter STORE (no services yet).
15902    /// Launch-param seeding runs before any node is constructed; the six
15903    /// service servers attach later in `register_parameter_services`,
15904    /// which preserves this store.
15905    /// `true` when the store exists afterwards. `false` only when the platform
15906    /// heap refused its allocation (issue 1706), which is reported once, here,
15907    /// with the size it asked for.
15908    fn ensure_parameter_store(&mut self) -> bool {
15909        if self.params.is_none() {
15910            if self.param_store_refused {
15911                return false;
15912            }
15913            let Some(state) = Self::new_param_state(
15914                core::mem::take(&mut self.param_slots),
15915                core::mem::take(&mut self.param_home),
15916            ) else {
15917                self.param_store_refused = true;
15918                report_parameter_store_refused();
15919                return false;
15920            };
15921            self.params = Some(state);
15922            // phase-430 W2 — the executor's implicit PRIMARY node exists the
15923            // moment the store does, whether or not a node record has been
15924            // built yet, so it is seeded here. The other node keys are seeded
15925            // in `reconcile_parameter_services`, as each one's set of six goes
15926            // up.
15927            self.seed_use_sim_time_default(super::node_record::NodeId::PRIMARY);
15928        }
15929        true
15930    }
15931
15932    /// phase-430 W2 — declare `use_sim_time = false`, as rclcpp does on EVERY
15933    /// node.
15934    ///
15935    /// Upstream auto-declares the parameter in `rclcpp::Node`'s constructor, so
15936    /// `ros2 param list` shows it and `ros2 param set <node> use_sim_time true`
15937    /// reaches a node whose author never wrote a line about simulated time.
15938    /// Ours honoured the parameter only if the APP had declared it: the store
15939    /// refuses an undeclared set (`allow_undeclared` is false), so the runtime
15940    /// switch worked on exactly the nodes that least needed it.
15941    ///
15942    /// The seed is a PLACEHOLDER, tracked by `ParamState::sim_time_seeded`,
15943    /// because the store refuses a duplicate name: without that flag, seeding
15944    /// here would turn an application's own `declare_parameter("use_sim_time",
15945    /// Bool(true))` into a refusal and the auto-declared default would silently
15946    /// beat the app. `yield_seeded_use_sim_time` steps the placeholder aside
15947    /// for the first real declaration, whatever value or descriptor it carries.
15948    ///
15949    /// PER NODE, both here and in the flag. phase-426 keyed the store and the
15950    /// six services by node, so "every node" is now literally expressible and
15951    /// this is where it is said: `ensure_parameter_store` seeds the executor's
15952    /// implicit PRIMARY, and `reconcile_parameter_services` seeds each further
15953    /// node key as its set of six goes up — which is exactly the set of nodes a
15954    /// `ros2 param set <node> use_sim_time true` can reach.
15955    ///
15956    /// It deliberately does NOT go through `note_reserved_parameter`, so
15957    /// `sim_time_stated` stays false: an auto-declared default is not a
15958    /// STATEMENT by anyone. Recording it as one would make every executor with
15959    /// parameter services write `set_active(false)` onto a PROCESS-GLOBAL gate
15960    /// on its first spin — switching off a simulated clock another executor in
15961    /// the same image installed, which is exactly the collision
15962    /// `sim_time_stated` was added for (issue 1104). That property is per node
15963    /// too: seeding N nodes must still be N statements by nobody.
15964    ///
15965    /// Gated on `sim-time` as well as `param-services`: an image that cannot
15966    /// act on the parameter should not advertise it, because a settable knob
15967    /// that does nothing is worse than an absent one.
15968    fn seed_use_sim_time_default(&mut self, node: super::node_record::NodeId) {
15969        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
15970        if let Some(params) = self.params.as_deref_mut()
15971            && let Some(seeded) = params.sim_time_seeded.get_mut(node.index())
15972            // Issue 2815 -- written into its slot: a `ParameterValue::Bool`
15973            // passed by value is ~8 KiB of this frame, and this runs on the
15974            // registration path of every node.
15975            && params.server.declare_with(
15976                node.into(),
15977                crate::time_source::USE_SIM_TIME_PARAM,
15978                &mut |slot| *slot = nros_params::ParameterValue::Bool(false),
15979            )
15980        {
15981            *seeded = true;
15982        }
15983        let _ = node;
15984    }
15985
15986    /// phase-430 W2 — step the seeded `use_sim_time` aside for an application
15987    /// that declares it itself on `node`. Returns whether it did.
15988    ///
15989    /// The app's declaration must WIN — its own default, its own descriptor —
15990    /// and a declaration is refused when the name is already taken, so the
15991    /// placeholder has to leave before the real one arrives. Only ever the
15992    /// placeholder: once a real declaration has landed the flag is false and a
15993    /// second declaration is refused exactly as it was before W2.
15994    ///
15995    /// Only ever THIS node's placeholder, too: an app that names
15996    /// `use_sim_time` on one node of an image has said nothing about the
15997    /// others, and their seeds stay placeholders for whoever declares next.
15998    fn yield_seeded_use_sim_time(&mut self, node: super::node_record::NodeId, name: &str) -> bool {
15999        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
16000        if name == crate::time_source::USE_SIM_TIME_PARAM
16001            && let Some(params) = self.params.as_deref_mut()
16002            && let Some(seeded) = params.sim_time_seeded.get_mut(node.index())
16003            && core::mem::replace(seeded, false)
16004        {
16005            return params.server.remove(node.into(), name);
16006        }
16007        let _ = (node, name);
16008        false
16009    }
16010
16011    /// The HEAP home for the parameter slot table, used only when the
16012    /// executor's backing carved none.
16013    ///
16014    /// phase-382 W2' — `ParameterServer` no longer OWNS its slots; it borrows
16015    /// a caller-placed [`nros_params::ParameterTable`]. phase-382 W3' carves
16016    /// that table out of the caller's executor backing whenever the build
16017    /// KNOWS the image builds a store ([`ExecutorSizing::params`](super::storage::ExecutorSizing::params), from
16018    /// `nros_params::IMPLIED_STORE_SLOTS`); this function is what remains for a
16019    /// store the build could not see — one reached only from application
16020    /// code — and for an executor opened with a sizing that carves none. It
16021    /// makes a single heap allocation, leaked, one per such executor that
16022    /// touches parameters. The leak is what buys the `'static`
16023    /// the borrow needs without making `ParamState` self-referential (a
16024    /// `ParamState` that owned the storage AND a server borrowing it is not
16025    /// expressible), and it is bounded — `ensure_parameter_store` runs this
16026    /// at most once per executor.
16027    ///
16028    /// Issue 0756 — the placement dance is still here because the SIZE is
16029    /// still here; it only moved off `ParameterServer` and onto
16030    /// `ParameterStorage`. That storage is 285,184 bytes at the default
16031    /// `MAX_PARAMETERS=32` and 2,281,472 at 256 (`ParameterValue` is sized by
16032    /// its `StringArray` variant, so every slot costs ~8.5 KiB regardless of
16033    /// what it holds). `Box::new(ParameterStorage::new())` materialises all of
16034    /// that on the caller's stack before copying it into the allocation,
16035    /// because Rust has no placement-new. On the Zephyr lane that silently
16036    /// overran the thread stack: an image built with 256 slots boots to
16037    /// `dds_create_participant` and hangs with no fault and no output, while
16038    /// 32 — which fits the 512 KiB main stack the cyclonedds snippet asks for
16039    /// — runs clean. Initialising through the allocation bounds the largest
16040    /// stack temporary at one slot, so the knob no longer decides whether boot
16041    /// survives.
16042    ///
16043    /// Issue 1706 -- FALLIBLE. This is the one allocation every parameter
16044    /// declaration reaches, in every language and on every RTOS, and it is the
16045    /// largest single request most images make. `Box::new_uninit` sent a
16046    /// failure to the OOM handler: Zephyr printed `HEAP EXHAUSTED` and died in
16047    /// issue 0589's recursion, FreeRTOS heap_4 hung in `MALLOC FAILED`. Every
16048    /// caller already has a refusal to return (`declare_parameter` is a
16049    /// `bool`), so the failure is now one, named by
16050    /// [`report_parameter_store_refused`] with the size it asked for.
16051    ///
16052    /// Issue 1812 -- `alloc` only. Without a heap there is no fallback, and
16053    /// the store is the carved one or none (see `new_param_state`).
16054    #[cfg(feature = "alloc")]
16055    fn leak_parameter_storage() -> Option<nros_params::ParameterTable<'static>> {
16056        #[cfg(all(test, feature = "alloc"))]
16057        if RefuseParameterStore::armed() {
16058            return None;
16059        }
16060        let mut uninit = nros_rmw::fallible::try_box_uninit::<nros_params::ParameterStorage>()?;
16061        // Safety: `try_box_uninit` gives a correctly-sized, correctly-aligned
16062        // allocation for exactly this type, and `init_in_place` writes every
16063        // slot exactly once before `assume_init` observes it.
16064        unsafe {
16065            nros_params::ParameterStorage::init_in_place(uninit.as_mut_ptr());
16066            Some(alloc::boxed::Box::leak(uninit.assume_init()).as_table())
16067        }
16068    }
16069
16070    /// Build the executor's `ParamState`.
16071    ///
16072    /// phase-382 W3' — `carved` are the backing's store slots: non-empty, they
16073    /// ARE the store and the heap is not asked; empty, the store falls back to
16074    /// [`leak_parameter_storage`](Self::leak_parameter_storage).
16075    ///
16076    /// Issue 1812 — and `home` is the services' carved region, which the
16077    /// backing places on the same condition: non-empty, the state, its service
16078    /// sets, the buffer pair and the staging slot are built IN it and nothing
16079    /// here allocates. Otherwise the state is one heap allocation, initialised
16080    /// in place (`ParamState::try_boxed` — it is several KiB now, so never a
16081    /// by-value `Box::new`). Without `alloc` that fallback does not exist and
16082    /// an executor whose backing carved nothing gets `None`, which every caller
16083    /// reports as the named refusal (`report_parameter_store_refused`).
16084    fn new_param_state(
16085        carved: &'s mut [MaybeUninit<nros_params::ParameterSlot>],
16086        home: &'s mut [MaybeUninit<super::storage::ParamHome>],
16087    ) -> Option<crate::param_store::Placed<'s, crate::param_store::ParamState<'s>>> {
16088        let table = if carved.is_empty() {
16089            #[cfg(feature = "alloc")]
16090            {
16091                Self::leak_parameter_storage()?
16092            }
16093            #[cfg(not(feature = "alloc"))]
16094            {
16095                return None;
16096            }
16097        } else {
16098            // Said once per store, so a boot log answers "where did the store
16099            // come from" without a debugger: issue 1706's measurements were
16100            // all heap-peak arithmetic, and this line is the direct answer.
16101            nros_log::log_info!(
16102                nros_log::get_logger("nros"),
16103                "parameter store: {} slots ({} B) + {} ({} B) carved from the executor backing",
16104                carved.len(),
16105                core::mem::size_of_val(carved),
16106                // Issue 1897 -- the home is the store's state, plus the
16107                // services' sets and buffers only where they are compiled.
16108                if cfg!(feature = "param-services") {
16109                    "state and services"
16110                } else {
16111                    "state"
16112                },
16113                core::mem::size_of_val(home)
16114            );
16115            nros_params::ParameterTable::init_in(carved)
16116        };
16117        let server = nros_params::ParameterServer::new_in(table);
16118        match home.first_mut() {
16119            Some(home) => Some(crate::param_store::ParamHome::init_in(home, server)),
16120            #[cfg(feature = "alloc")]
16121            None => crate::param_store::ParamState::try_boxed(server),
16122            #[cfg(not(feature = "alloc"))]
16123            None => None,
16124        }
16125    }
16126
16127    /// Install `-p` / `--params-file` parameter overrides.
16128    ///
16129    /// They are applied when a parameter is DECLARED: the declaration's value
16130    /// is replaced by the override's, typed by it (~~`apply_argv_param_override`~~).
16131    /// So an override reaches a parameter on every road that declares through
16132    /// this executor — C, C++ and Rust — including the launch file's baked
16133    /// values, which the generated entry declares through the same seam.
16134    ///
16135    /// That makes argv WIN over a launch-baked parameter, the opposite of the
16136    /// remap tiers, deliberately: overriding a baked value at run time without
16137    /// a rebuild is what the launch-tree orchestration asks for ("a runtime override has
16138    /// identical effect to a `set_parameter` request after boot"), and upstream
16139    /// agrees — a launch file's parameters reach the node as command-line
16140    /// arguments themselves, where the later one wins.
16141    ///
16142    /// Overrides accumulate in argv order and the LAST one that matches a
16143    /// declaration wins, as rcl's do. A `node:` override matches the node of
16144    /// that NAME; one without matches every node.
16145    ///
16146    /// Fails only when the parameter store could not be allocated,
16147    /// in which case nothing is installed.
16148    #[cfg(feature = "alloc")]
16149    pub fn install_argv_params<'p, I>(&mut self, params: I) -> Result<usize, NodeError>
16150    where
16151        I: IntoIterator<Item = crate::ros_args::ParamArg<'p>>,
16152    {
16153        if !self.ensure_parameter_store() {
16154            return Err(NodeError::Transport(TransportError::BadAlloc));
16155        }
16156        let Some(state) = self.params.as_deref_mut() else {
16157            return Err(NodeError::Transport(TransportError::BadAlloc));
16158        };
16159        let mut n = 0;
16160        for p in params {
16161            state
16162                .argv_overrides
16163                .push(crate::param_store::ArgvParamOverride {
16164                    node: p.node.map(alloc::string::String::from),
16165                    name: alloc::string::String::from(p.name),
16166                    value: alloc::string::String::from(p.value),
16167                });
16168            n += 1;
16169        }
16170        Ok(n)
16171    }
16172
16173    /// The `-p` / `--params-file` overrides that apply to `node`, one per
16174    /// name — issue 2057, for rclcpp's
16175    /// `NodeParametersInterface::get_parameter_overrides()`.
16176    ///
16177    /// The selection is the one a declaration makes
16178    /// (`argv_param_override`): the LAST override of a name that applies
16179    /// wins, and a `node:` override applies only to the node of that name.
16180    /// Each text is typed as a declaration with no default types it (bool,
16181    /// integer, double, then string), because a listing has no declared type
16182    /// to follow. An override no type accepts (a string past the store's
16183    /// bound) is left out. Yields in argv order of the winning override.
16184    #[cfg(all(feature = "param-store", feature = "alloc"))]
16185    pub(crate) fn argv_param_overrides_on(
16186        &self,
16187        node: super::node_record::NodeId,
16188    ) -> impl Iterator<Item = (&str, nros_params::ParameterValue)> + '_ {
16189        let node_name = self.node(node).map(|r| r.name.as_str()).unwrap_or("");
16190        let list: &[crate::param_store::ArgvParamOverride] = self
16191            .params
16192            .as_deref()
16193            .map(|s| s.argv_overrides.as_slice())
16194            .unwrap_or(&[]);
16195        let applies = move |o: &crate::param_store::ArgvParamOverride| {
16196            o.node.as_deref().is_none_or(|n| n == node_name)
16197        };
16198        list.iter()
16199            .enumerate()
16200            .filter(move |(i, o)| {
16201                applies(o) && !list[i + 1..].iter().any(|l| l.name == o.name && applies(l))
16202            })
16203            .filter_map(|(_, o)| {
16204                typed_param_override(&o.value, &nros_params::ParameterValue::NotSet)
16205                    .map(|v| (o.name.as_str(), v))
16206            })
16207    }
16208
16209    /// [`argv_param_overrides_on`](Self::argv_param_overrides_on), one call of
16210    /// `f` per override with the typed value BORROWED (issue 2104). An
16211    /// iterator hands each ~8 KiB value out by value through its `next`
16212    /// frame and then into the caller's; here ONE value is refilled per
16213    /// override (issue 2118), which took `nros_cpp_node_list_param_overrides`
16214    /// from 17.3 KiB to 9.0 KiB on Cortex-M3.
16215    #[cfg(all(feature = "param-store", feature = "alloc"))]
16216    pub(crate) fn for_each_argv_param_override_on(
16217        &self,
16218        node: super::node_record::NodeId,
16219        mut f: impl FnMut(&str, &nros_params::ParameterValue),
16220    ) -> usize {
16221        let node_name = self.node(node).map(|r| r.name.as_str()).unwrap_or("");
16222        let list: &[crate::param_store::ArgvParamOverride] = self
16223            .params
16224            .as_deref()
16225            .map(|s| s.argv_overrides.as_slice())
16226            .unwrap_or(&[]);
16227        let applies = |o: &crate::param_store::ArgvParamOverride| {
16228            o.node.as_deref().is_none_or(|n| n == node_name)
16229        };
16230        // Issue 2118 -- ONE value for the whole walk, refilled per override.
16231        let mut value = nros_params::ParameterValue::NotSet;
16232        let mut n = 0;
16233        for (i, o) in list.iter().enumerate() {
16234            if !applies(o) || list[i + 1..].iter().any(|l| l.name == o.name && applies(l)) {
16235                continue;
16236            }
16237            if typed_param_override_into(&o.value, &nros_params::ParameterValue::NotSet, &mut value)
16238            {
16239                f(o.name.as_str(), &value);
16240                n += 1;
16241            }
16242        }
16243        n
16244    }
16245
16246    /// Issue 2070 — does an argv override name this parameter? The cheap
16247    /// question [`declare_parameter_on_ref`](Self::declare_parameter_on_ref)
16248    /// asks before it enters the frame that types one.
16249    #[cfg(not(feature = "alloc"))]
16250    fn has_argv_param_override(&self, _node: super::node_record::NodeId, _name: &str) -> bool {
16251        false
16252    }
16253
16254    #[cfg(feature = "alloc")]
16255    fn has_argv_param_override(&self, node: super::node_record::NodeId, name: &str) -> bool {
16256        let Some(state) = self.params.as_deref() else {
16257            return false;
16258        };
16259        if state.argv_overrides.is_empty() {
16260            return false;
16261        }
16262        let node_name = self.node(node).map(|r| r.name.as_str()).unwrap_or("");
16263        state
16264            .argv_overrides
16265            .iter()
16266            .any(|o| o.name == name && o.node.as_deref().is_none_or(|n| n == node_name))
16267    }
16268
16269    /// The value the last matching argv override gives a declaration of
16270    /// `name` on `node`, typed by `declared` and written into `out`; `false`
16271    /// when no override applies and `declared` stands.
16272    ///
16273    /// An override whose text does not parse as the declared type is NOT
16274    /// applied: it is logged at error severity, naming the parameter, the text
16275    /// and the type, and the declared default stands (RFC-0015 §9.6 — "log +
16276    /// ignore, never panic"). An array-typed declaration takes no override yet.
16277    ///
16278    /// Issue 2104 -- `declared` is borrowed and only the override is
16279    /// produced. Taking a clone of it and handing back a `(value, bool)` held
16280    /// three ~8 KiB values across two frames (25.5 KiB on Cortex-M3). Issue
16281    /// 2118 -- and the override is written into the caller's slot rather than
16282    /// returned, which held two (17 KiB).
16283    #[cfg(not(feature = "alloc"))]
16284    fn argv_param_override(
16285        &self,
16286        _node: super::node_record::NodeId,
16287        _name: &str,
16288        _declared: &nros_params::ParameterValue,
16289        _out: &mut nros_params::ParameterValue,
16290    ) -> bool {
16291        // Issue 1812 -- argv overrides are a hosted-edge input installed
16292        // through `install_argv_params`, which is `alloc`-only.
16293        false
16294    }
16295
16296    #[cfg(feature = "alloc")]
16297    fn argv_param_override(
16298        &self,
16299        node: super::node_record::NodeId,
16300        name: &str,
16301        declared: &nros_params::ParameterValue,
16302        out: &mut nros_params::ParameterValue,
16303    ) -> bool {
16304        let Some(state) = self.params.as_deref() else {
16305            return false;
16306        };
16307        if state.argv_overrides.is_empty() {
16308            return false;
16309        }
16310        let node_name = self.node(node).map(|r| r.name.as_str()).unwrap_or("");
16311        let Some(o) = state
16312            .argv_overrides
16313            .iter()
16314            .rev()
16315            .find(|o| o.name == name && o.node.as_deref().is_none_or(|n| n == node_name))
16316        else {
16317            return false;
16318        };
16319        let typed = typed_param_override_into(&o.value, declared, out);
16320        if !typed {
16321            nros_log::log_error!(
16322                nros_log::get_logger("nros"),
16323                "parameter override `{}:={}` is not a {:?}; the declared default stands",
16324                name,
16325                o.value,
16326                declared.param_type()
16327            );
16328        }
16329        typed
16330    }
16331
16332    /// Declare a parameter with a value on the executor's PRIMARY node.
16333    ///
16334    /// The store is keyed by node, and this is the spelling for
16335    /// the executor's implicit primary node (`NodeId::PRIMARY`), which is the
16336    /// identity `register_parameter_services` publishes and the one every
16337    /// single-node entry means. Name a different node with
16338    /// [`declare_parameter_on`](Self::declare_parameter_on).
16339    ///
16340    /// `#[must_use]`, for the reason `[[nodiscard]]` went on
16341    /// C++'s `Result`: the `else { false }` arm is silently discarded at a
16342    /// call site that drops the value, and `Node::logger` two files over
16343    /// already carries the attribute — so this was inconsistency, not house
16344    /// style. A declare that failed and was ignored is a parameter the program
16345    /// believes it has.
16346    #[must_use]
16347    // phase-515 R10 -- the node is the parameter receiver.
16348    #[deprecated(
16349        since = "0.6.0",
16350        note = "the node is the parameter receiver: call `node.declare_parameter::<T>(name).default(value).mandatory()` on the `Node` that `create_node` / `node_mut(id)` returns"
16351    )]
16352    pub fn declare_parameter(&mut self, name: &str, value: nros_params::ParameterValue) -> bool {
16353        let node = super::node_record::NodeId::PRIMARY;
16354        self.observe_code_parameter_declare(node, name, Some(&value), value.param_type());
16355        self.declare_parameter_on(node, name, value)
16356    }
16357
16358    /// Declare a parameter with a value on a named node.
16359    ///
16360    /// `#[must_use]` for the reason [`declare_parameter`](Self::declare_parameter)
16361    /// carries it: issue 1257's two dropped results moved to THIS method when
16362    /// they were fixed, so the attribute on the wrapper alone guarded nothing
16363    /// a launch-seed site could still drop.
16364    #[must_use]
16365    pub(crate) fn declare_parameter_on(
16366        &mut self,
16367        node: super::node_record::NodeId,
16368        name: &str,
16369        value: nros_params::ParameterValue,
16370    ) -> bool {
16371        self.declare_parameter_on_ref(node, name, &value)
16372    }
16373
16374    // Issue 2969.
16375    /// Declare `name` on `node` from a LAUNCH file: the value an entry seeds
16376    /// before the node's code runs. It is declared like any value, then
16377    /// marked, so the code's first declaration of the name adopts it
16378    /// ([`adopt_launch_seed_on`](Self::adopt_launch_seed_on)) rather than being
16379    /// refused as a duplicate. Every seeding path calls this (the Rust board
16380    /// entry, the Rust probe, nros-cpp's seed for C and C++ entries).
16381    #[must_use]
16382    pub(crate) fn seed_launch_parameter_on_ref(
16383        &mut self,
16384        node: super::node_record::NodeId,
16385        name: &str,
16386        value: &nros_params::ParameterValue,
16387    ) -> bool {
16388        if !self.declare_parameter_on_ref(node, name, value) {
16389            return false;
16390        }
16391        if let Some(params) = self.params.as_deref_mut() {
16392            params.server.mark_launch_seed(node.into(), name);
16393        }
16394        true
16395    }
16396
16397    // Issue 2969.
16398    /// The code declares `name` on `node` as `param_type`: adopt its launch
16399    /// seed if it has one (see `ParameterServer::adopt_launch_seed`). `None`
16400    /// when there is none, or no store: declare as usual.
16401    pub(crate) fn adopt_launch_seed_on(
16402        &mut self,
16403        node: super::node_record::NodeId,
16404        name: &str,
16405        param_type: nros_params::ParameterType,
16406        descriptor: Option<&nros_params::ParameterDescriptor>,
16407    ) -> Option<Result<(), nros_params::DeclarationError>> {
16408        self.params.as_deref_mut()?.server.adopt_launch_seed(
16409            node.into(),
16410            name,
16411            param_type,
16412            descriptor,
16413        )
16414    }
16415
16416    /// [`declare_parameter_on`](Self::declare_parameter_on), borrowing the
16417    /// value — issue 2070, and THE declare path the by-value spelling forwards
16418    /// to. A `ParameterValue` is ~8 KiB at the default capacities, and moving
16419    /// it through each frame of the declare path cost ~57 KiB of stack for one
16420    /// `declare_parameter<double>` (aarch64; ~67 KiB on Cortex-M3). Borrowed,
16421    /// it is copied once, into its slot.
16422    #[must_use]
16423    pub(crate) fn declare_parameter_on_ref(
16424        &mut self,
16425        node: super::node_record::NodeId,
16426        name: &str,
16427        value: &nros_params::ParameterValue,
16428    ) -> bool {
16429        self.ensure_parameter_store();
16430        // The argv override is a hosted-edge input and rare; its frame (which
16431        // holds the typed override) is entered only when one applies, so the
16432        // common path carries no second value.
16433        if self.has_argv_param_override(node, name) {
16434            return self.declare_parameter_overridden(node, name, value);
16435        }
16436        self.declare_parameter_resolved(node, name, value)
16437    }
16438
16439    /// Issue 2070 — the override branch of
16440    /// [`declare_parameter_on_ref`](Self::declare_parameter_on_ref), in its
16441    /// own frame.
16442    #[inline(never)]
16443    fn declare_parameter_overridden(
16444        &mut self,
16445        node: super::node_record::NodeId,
16446        name: &str,
16447        declared: &nros_params::ParameterValue,
16448    ) -> bool {
16449        // Issue 2118 -- the frame's one value, filled in place.
16450        let mut value = nros_params::ParameterValue::NotSet;
16451        if self.argv_param_override(node, name, declared, &mut value) {
16452            self.declare_parameter_resolved(node, name, &value)
16453        } else {
16454            self.declare_parameter_resolved(node, name, declared)
16455        }
16456    }
16457
16458    /// The store write and the reserved-name hook, for a value whose argv
16459    /// override has already been applied.
16460    fn declare_parameter_resolved(
16461        &mut self,
16462        node: super::node_record::NodeId,
16463        name: &str,
16464        value: &nros_params::ParameterValue,
16465    ) -> bool {
16466        // phase-430 W2 — an application declaring `use_sim_time` itself wins
16467        // over the auto-declared default, so the placeholder leaves first.
16468        let yielded = self.yield_seeded_use_sim_time(node, name);
16469        let accepted = match &mut self.params {
16470            Some(params) => params.server.declare_ref(node.into(), name, value),
16471            None => false,
16472        };
16473        if yielded && !accepted {
16474            // The app's own declaration was refused on its own terms (a full
16475            // store, an ill-formed range). Put the rclcpp default back rather
16476            // than leaving the name undeclared — that is a state neither the
16477            // app nor upstream asked for, and it would silently un-do W2 for
16478            // this node.
16479            self.seed_use_sim_time_default(node);
16480        }
16481        // phase-425 W3b — `use_sim_time` is RESERVED, exactly as in ROS 2: its
16482        // value is not a value the app reads, it is the switch that attaches the
16483        // time source. This is the one seam every language funnels through
16484        // (`nros::main!`'s launch bakes via `apply_param_services`, nros-c's
16485        // the rclc parameter server's `declare`, nros-cpp's `params_shim`), so hooking it
16486        // here covers all of them instead of once per entry path.
16487        //
16488        // phase-430 W3 / issue 1202 — the hook runs AFTER the store's verdict
16489        // and only on acceptance. It used to run first and unconditionally, so
16490        // a re-declaration the store REFUSES (the name is already there) still
16491        // flipped the switch: the store kept `use_sim_time = true` while the
16492        // `/clock` source detached, leaving an executor with sim time recorded
16493        // as on and no source attached, which is neither of the two states the
16494        // parameter can name.
16495        if accepted {
16496            self.note_reserved_parameter(name);
16497        }
16498        accepted
16499    }
16500
16501    /// Say, at ERROR, why the store refused to declare `name` on `node`, and
16502    /// whether the reason was a FULL store.
16503    ///
16504    /// For a caller whose declaration came back refused and whose name is
16505    /// still absent afterwards (an "already declared" answer is not a refusal).
16506    /// Returns `true` when every slot of the store was taken, so the caller
16507    /// can answer its own language's "full" code.
16508    ///
16509    /// The line names the node, the parameter, the store's capacity and the
16510    /// knob that sizes it in every spelling a user writes, because the value a
16511    /// launch file or YAML gave this parameter is not applied, and a node that
16512    /// runs anyway runs on numbers its launch file does not state.
16513    #[cold]
16514    #[inline(never)]
16515    pub(crate) fn report_parameter_refused(
16516        &self,
16517        node: super::node_record::NodeId,
16518        name: &str,
16519    ) -> bool {
16520        // GitHub #4018: the C++ facade used to return the code default here
16521        // with no word, so a controller ran on compiled gains.
16522        // A launch seed lands on a node that is not built yet, so the table
16523        // may have no row for it; the index is then all there is to name.
16524        let mut fqn = heapless::String::<256>::new();
16525        match self.nodes.get(node.index()) {
16526            Some(r) => match crate::names::fully_qualified_name(&r.name, &r.namespace) {
16527                Ok(f) => {
16528                    let _ = fqn.push_str(f.as_str());
16529                }
16530                Err(()) => {
16531                    let _ = fqn.push_str(&r.name);
16532                }
16533            },
16534            None => {
16535                let _ = core::fmt::Write::write_fmt(
16536                    &mut fqn,
16537                    format_args!("node index {}", node.raw()),
16538                );
16539            }
16540        }
16541        let Some(params) = self.params.as_ref() else {
16542            nros_log::log_error!(
16543                nros_log::get_logger("nros"),
16544                "node \"{}\": parameter \"{}\" not declared: this image has no parameter \
16545                 store.",
16546                fqn.as_str(),
16547                name
16548            );
16549            return false;
16550        };
16551        let capacity = params.server.capacity();
16552        if params.server.is_full() {
16553            // Three records, each short enough for the smallest log buffer:
16554            // one long line is cut where the knob's name is.
16555            let logger = nros_log::get_logger("nros");
16556            nros_log::log_error!(
16557                logger,
16558                "node \"{}\": parameter \"{}\" not declared: the parameter store is full \
16559                 ({} slots, all nodes). Its launch/YAML value is not applied.",
16560                fqn.as_str(),
16561                name,
16562                capacity
16563            );
16564            nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_KNOB);
16565            nros_log::log_error!(logger, "{}", nros_params::STORE_SIZE_DERIVED);
16566            return true;
16567        }
16568        nros_log::log_error!(
16569            nros_log::get_logger("nros"),
16570            "node \"{}\": parameter \"{}\" not declared: the parameter store ({} slots, \
16571             not full) refused it. Is the name over NROS_PARAMS_MAX_NAME_BYTES?",
16572            fqn.as_str(),
16573            name,
16574            capacity
16575        );
16576        false
16577    }
16578
16579    /// phase-425 W3b — record a reserved parameter's effect. Today that is
16580    /// `use_sim_time` and nothing else: it is the tree's only reserved name,
16581    /// and [`time_source::USE_SIM_TIME_PARAM`](crate::time_source::USE_SIM_TIME_PARAM)
16582    /// is the only such constant.
16583    ///
16584    /// Called only after the store ACCEPTED a declaration, and it reads the
16585    /// value back OUT of the store instead of taking the caller's: what the
16586    /// switch must follow is what the store holds, and the two are the same
16587    /// thing only while every write succeeds (issue 1202). The read is
16588    /// [`refresh_use_sim_time_from_store`](Self::refresh_use_sim_time_from_store),
16589    /// the same one the runtime `ros2 param set` path uses, so the declare path
16590    /// and the wire path cannot disagree about the value.
16591    ///
16592    /// A non-bool `use_sim_time` is IGNORED rather than rejected: parameter
16593    /// declaration has no channel to report a complaint on (it returns "did the
16594    /// store take it"), and refusing the declaration outright would fail a node
16595    /// for a parameter ROS 2 lets it declare. The time source simply does not
16596    /// attach, which is the same outcome as `false`.
16597    ///
16598    /// Not covered: [`Executor::parameter`](Self::parameter)'s
16599    /// [`ParameterBuilder`](nros_params::ParameterBuilder) borrows the server
16600    /// and declares through it, so the executor never sees the write and
16601    /// `use_sim_time` named that way attaches nothing — issue 1203.
16602    /// Issue 1203 — finish a `use_sim_time` that went through
16603    /// [`parameter`](Self::parameter)'s builder.
16604    ///
16605    /// The builder held the store while it declared, so nothing told the
16606    /// executor; this is the spin after, reading the store back. A builder that
16607    /// declared the name gets the reserved-parameter hook a `declare_parameter`
16608    /// would have run. One that was dropped without declaring leaves the node
16609    /// with no `use_sim_time`, because `parameter_on` stepped the placeholder
16610    /// aside for it, so the placeholder goes back.
16611    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
16612    fn settle_builder_reserved_parameters(&mut self) {
16613        let Some(params) = self.params.as_deref_mut() else {
16614            return;
16615        };
16616        if !params.sim_time_via_builder.contains(&true) {
16617            return;
16618        }
16619        let pending = core::mem::replace(
16620            &mut params.sim_time_via_builder,
16621            [false; crate::param_sizing::MAX_SERVICE_SETS],
16622        );
16623        let mut declared = false;
16624        for (index, _) in pending.iter().enumerate().filter(|(_, p)| **p) {
16625            let node = super::node_record::NodeId(index as u8);
16626            let present = self.params.as_deref().is_some_and(|p| {
16627                p.server
16628                    .get(node.into(), crate::time_source::USE_SIM_TIME_PARAM)
16629                    .is_some()
16630            });
16631            if present {
16632                declared = true;
16633            } else {
16634                self.seed_use_sim_time_default(node);
16635            }
16636        }
16637        if declared {
16638            self.note_reserved_parameter(crate::time_source::USE_SIM_TIME_PARAM);
16639        }
16640    }
16641
16642    fn note_reserved_parameter(&mut self, name: &str) {
16643        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
16644        if name == crate::time_source::USE_SIM_TIME_PARAM {
16645            self.refresh_use_sim_time_from_store();
16646        }
16647        let _ = name;
16648    }
16649
16650    /// phase-425 W3b — a parameter service handled `n` requests this spin.
16651    ///
16652    /// The hook exists so `use_sim_time` can be re-read after a runtime
16653    /// `ros2 param set`, WITHOUT a per-spin scan of the store. It takes the
16654    /// count unconditionally and ignores it when `sim-time` is off, rather than
16655    /// the call sites carrying the feature test: `handled` was then assigned and
16656    /// never read in the `param-services`-without-`sim-time` combo, which is a
16657    /// `-D warnings` error `check-build` catches and the narrower per-crate
16658    /// clippy runs do not.
16659    #[inline]
16660    fn note_param_services_ran(&mut self, handled: usize) {
16661        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
16662        if handled > 0 {
16663            self.refresh_use_sim_time_from_store();
16664        }
16665        let _ = handled;
16666        self.report_truncated_descriptions();
16667        #[cfg(feature = "param-services")]
16668        self.flush_parameter_events();
16669    }
16670
16671    /// phase-446 F2 -- log each parameter whose description did not fit
16672    /// `NROS_PARAMS_MAX_DESCRIPTION_BYTES`, once, naming the knob.
16673    ///
16674    /// `nros-params` has no logger, so it truncates, records the truncation on
16675    /// the stored descriptor, and hands it over here. Asked on every spin
16676    /// because a declaration can arrive through builders this executor never
16677    /// sees the end of (`parameter::<T>()` returns the store's own builder);
16678    /// while nothing is pending the store answers from one flag, without
16679    /// walking its table.
16680    #[cold]
16681    fn report_truncated_descriptions(&mut self) {
16682        let Some(params) = self.params.as_deref_mut() else {
16683            return;
16684        };
16685        let nodes = &self.nodes;
16686        params
16687            .server
16688            .take_truncated_descriptions(|key, name, text| {
16689                let (ns, node) = nodes
16690                    .get(key.index())
16691                    .map_or(("", "?"), |r| (r.namespace.as_str(), r.name.as_str()));
16692                // phase-446 F2; issue 2686 -- name the field that was cut and the
16693                // knob that sizes IT: a constraints text has its own.
16694                nros_log::log_warn!(
16695                    nros_log::get_logger("nros"),
16696                    "parameter `{}` on node {}/{}: its {} is longer than \
16697                 {} ({} bytes), so `ros2 param describe` answers it truncated \
16698                 at a character boundary. Raise {} to keep it whole; 0 stores \
16699                 none. Logged once for this parameter.",
16700                    name,
16701                    ns.trim_end_matches('/'),
16702                    node,
16703                    text.field(),
16704                    text.knob(),
16705                    text.capacity(),
16706                    text.knob()
16707                );
16708            });
16709    }
16710
16711    /// Declare a parameter with a value and descriptor on the PRIMARY node.
16712    /// Returns `true` if successful.
16713    ///
16714    /// The sibling of [`Self::declare_parameter`],
16715    /// with the identical `else { false }` arm and no attribute. W6 marked the
16716    /// one method its audit named; this is the site three lines below it, which
16717    /// is the shape CLAUDE.md's "fix the CLASS, not the reported site" rule
16718    /// exists for.
16719    #[must_use]
16720    // phase-515 R10 -- the node is the parameter receiver.
16721    #[deprecated(
16722        since = "0.6.0",
16723        note = "the node is the parameter receiver: call `node.declare_parameter_with_descriptor(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
16724    )]
16725    pub fn declare_parameter_with_descriptor(
16726        &mut self,
16727        name: &str,
16728        value: nros_params::ParameterValue,
16729        descriptor: nros_params::ParameterDescriptor,
16730    ) -> bool {
16731        let node = super::node_record::NodeId::PRIMARY;
16732        self.observe_code_parameter_declare(node, name, Some(&value), value.param_type());
16733        self.declare_parameter_with_descriptor_on(node, name, value, descriptor)
16734    }
16735
16736    /// Declare a parameter with a value and descriptor on a named node.
16737    pub(crate) fn declare_parameter_with_descriptor_on(
16738        &mut self,
16739        node: super::node_record::NodeId,
16740        name: &str,
16741        value: nros_params::ParameterValue,
16742        descriptor: nros_params::ParameterDescriptor,
16743    ) -> bool {
16744        self.ensure_parameter_store();
16745        // phase-430 W2 — same rule as the sibling above: the app's own
16746        // declaration, descriptor and all, replaces the auto-declared default.
16747        let yielded = self.yield_seeded_use_sim_time(node, name);
16748        // Issue 2070 — borrowed, as on the sibling path; the override branch
16749        // has its own frame.
16750        let accepted = if self.has_argv_param_override(node, name) {
16751            self.declare_described_overridden(node, name, &value, descriptor)
16752        } else {
16753            match &mut self.params {
16754                Some(params) => params
16755                    .server
16756                    .try_declare_ref(node.into(), name, &value, Some(descriptor))
16757                    .is_ok(),
16758                None => false,
16759            }
16760        };
16761        if yielded && !accepted {
16762            self.seed_use_sim_time_default(node);
16763        }
16764        // phase-430 W3 / issue 1202 — the sibling declare path, which had NO
16765        // reserved hook at all: `declare_parameter_with_descriptor` stored
16766        // `use_sim_time` and attached nothing, so the same declaration meant
16767        // two different things depending on whether the app passed a
16768        // descriptor. Same seam, same verdict ordering, one shared hook.
16769        if accepted {
16770            self.note_reserved_parameter(name);
16771        }
16772        accepted
16773    }
16774
16775    /// Issue 2070 — the override branch of
16776    /// [`declare_parameter_with_descriptor_on`](Self::declare_parameter_with_descriptor_on),
16777    /// in its own frame.
16778    ///
16779    /// phase-482 W5 — an argv override that the DESCRIPTOR refuses (out of
16780    /// range, or read-only with a different value) must not cost the
16781    /// parameter its existence: log it, then declare the code's default.
16782    #[inline(never)]
16783    fn declare_described_overridden(
16784        &mut self,
16785        node: super::node_record::NodeId,
16786        name: &str,
16787        declared: &nros_params::ParameterValue,
16788        descriptor: nros_params::ParameterDescriptor,
16789    ) -> bool {
16790        // Issue 2118 -- the frame's one value, filled in place.
16791        let mut value = nros_params::ParameterValue::NotSet;
16792        let overridden = self.argv_param_override(node, name, declared, &mut value);
16793        let Some(params) = &mut self.params else {
16794            return false;
16795        };
16796        if params
16797            .server
16798            .try_declare_ref(
16799                node.into(),
16800                name,
16801                if overridden { &value } else { declared },
16802                Some(descriptor.clone()),
16803            )
16804            .is_ok()
16805        {
16806            return true;
16807        }
16808        if !overridden {
16809            return false;
16810        }
16811        nros_log::log_error!(
16812            nros_log::get_logger("nros"),
16813            "parameter override for `{}` was refused by its descriptor; the declared \
16814             default stands",
16815            name
16816        );
16817        params
16818            .server
16819            .try_declare_ref(node.into(), name, declared, Some(descriptor))
16820            .is_ok()
16821    }
16822
16823    /// THE writer.
16824    ///
16825    /// Set an ALREADY-DECLARED parameter on the executor's primary node, with
16826    /// the same rules a remote `ros2 param set` gets: read-only, type, range
16827    /// (min/max/step), and the refusal of a name the node never
16828    /// declared unless that node opted in through
16829    /// [`allow_undeclared_parameters_on`](Self::allow_undeclared_parameters_on).
16830    ///
16831    /// It routes through [`ParameterServer::apply`](nros_params::ParameterServerOps::apply),
16832    /// which is what makes the C and C++ facades, the by-value oracle, the
16833    /// streaming service path and the atomic pre-check agree — a facade that
16834    /// wrote the slot directly would be a second answer to "may this set
16835    /// happen", which is the class the C API's thin-wrapper discipline forbids. An in-image caller
16836    /// that genuinely wants declare-on-write names
16837    /// `params_mut()`/`set_or_declare` and has opted in by naming it.
16838    ///
16839    /// Returns `Err(ParameterError::NotFound)` when the store does not exist
16840    /// yet (no parameter has been declared and no services registered).
16841    // phase-515 R10 -- the node is the parameter receiver.
16842    #[deprecated(
16843        since = "0.6.0",
16844        note = "the node is the parameter receiver: call `node.set_parameter(name, value)` on the `Node` that `create_node` / `node_mut(id)` returns"
16845    )]
16846    pub fn set_parameter(
16847        &mut self,
16848        name: &str,
16849        value: nros_params::ParameterValue,
16850    ) -> Result<(), nros_params::ParameterError> {
16851        self.set_parameter_on(super::node_record::NodeId::PRIMARY, name, value)
16852    }
16853
16854    /// [`set_parameter`](Self::set_parameter) on a named node.
16855    pub(crate) fn set_parameter_on(
16856        &mut self,
16857        node: super::node_record::NodeId,
16858        name: &str,
16859        value: nros_params::ParameterValue,
16860    ) -> Result<(), nros_params::ParameterError> {
16861        self.set_parameter_on_ref(node, name, &value)
16862    }
16863
16864    /// [`set_parameter_on`](Self::set_parameter_on), borrowing the value --
16865    /// issue 2104, and the one the by-value spelling forwards to. The value is
16866    /// copied once, into its slot (`ParameterServer::apply_ref`).
16867    pub(crate) fn set_parameter_on_ref(
16868        &mut self,
16869        node: super::node_record::NodeId,
16870        name: &str,
16871        value: &nros_params::ParameterValue,
16872    ) -> Result<(), nros_params::ParameterError> {
16873        // Reserved parameters (`use_sim_time`) take effect on a set exactly as
16874        // they do on a declare — this is the seam every language funnels
16875        // through, so hooking it once here covers all of them.
16876        //
16877        // AFTER the store's verdict and only on `Success`, for the reason issue
16878        // 1202 gives one function up: the hook used to run first and off the
16879        // caller's value, so a write the store REFUSED still moved the switch
16880        // and left sim time recorded as on with no source attached. `apply` has
16881        // more ways to refuse than `declare` does — read-only, type, range,
16882        // undeclared-without-the-node-option — so a writer that hooked first
16883        // would reach that state from four directions instead of one.
16884        let result = match &mut self.params {
16885            Some(params) => params.server.apply_ref(node.into(), name, value),
16886            None => Err(nros_params::ParameterError::NotFound),
16887        };
16888        if result.is_ok() {
16889            self.note_reserved_parameter(name);
16890        }
16891        result
16892    }
16893
16894    /// phase-491 W2 (RFC-0105 D7) — rclc's LOCAL typed set on `node`:
16895    /// type, the on-set hooks with `(old, new)`, the write. Read-only and
16896    /// range are NOT checked, because rclc's owner of a parameter is not bound
16897    /// by them; remote writes keep [`set_parameter_on`](Self::set_parameter_on)'s
16898    /// rules. The reserved-parameter hook runs on success, as on every writer.
16899    pub(crate) fn set_parameter_local_on(
16900        &mut self,
16901        node: super::node_record::NodeId,
16902        name: &str,
16903        value: nros_params::ParameterValue,
16904    ) -> Result<(), nros_params::ParameterError> {
16905        let result = match &mut self.params {
16906            Some(params) => params.server.set_local(node.into(), name, value),
16907            None => Err(nros_params::ParameterError::NotFound),
16908        };
16909        if result.is_ok() {
16910            self.note_reserved_parameter(name);
16911        }
16912        result
16913    }
16914
16915    #[cfg(feature = "param-services")]
16916    /// Issue 2023 — the serving half of `/parameter_events`: a node whose six
16917    /// services just came up publishes its events unless it opted out. A
16918    /// failure is LOGGED and the services stay up: `ros2 param` still works,
16919    /// and a publisher slot the image did not size for is a fact to report,
16920    /// not a reason to take the services down with it.
16921    #[inline(never)]
16922    fn start_parameter_events_for_served_node(&mut self, node: super::node_record::NodeId) {
16923        if self
16924            .params
16925            .as_deref()
16926            .is_some_and(|p| p.events_opt_out.get(node.into()))
16927        {
16928            return;
16929        }
16930        if let Err(e) = self.enable_parameter_events_on(node) {
16931            report_parameter_events_refused(e);
16932        }
16933    }
16934
16935    #[cfg(feature = "param-services")]
16936    /// Issue 2023 — `node` publishes no `/parameter_events` (rclc's
16937    /// `notify_changed_over_dds = false`; rclcpp's
16938    /// `start_parameter_event_publisher(false)`). Stops logging its changes,
16939    /// keeps [`register_parameter_services`](Self::register_parameter_services)
16940    /// from switching them on, and drops the node's publisher (issue 2493),
16941    /// so the graph no longer lists it as one. Other nodes' publishers stay.
16942    pub(crate) fn disable_parameter_events_on(&mut self, node: super::node_record::NodeId) {
16943        if !self.ensure_parameter_store() {
16944            return;
16945        }
16946        if let Some(params) = self.params.as_deref_mut() {
16947            params.events_opt_out.set(node.into(), true);
16948            params.server.set_parameter_events(node.into(), false);
16949            params.event_publishers.retain(|e| e.node != node.index());
16950        }
16951    }
16952
16953    // Gated like its only callers, the `tests` module (`executor/mod.rs`).
16954    #[cfg(all(
16955        test,
16956        feature = "param-services",
16957        feature = "alloc",
16958        not(feature = "rmw-cffi")
16959    ))]
16960    /// Issue 2493 — `node`'s `/parameter_events` publisher, if it has one.
16961    pub(crate) fn parameter_event_publisher(
16962        &self,
16963        node: super::node_record::NodeId,
16964    ) -> Option<&session::RmwPublisher> {
16965        self.params.as_deref().and_then(|p| {
16966            p.event_publishers
16967                .iter()
16968                .find(|e| e.node == node.index())
16969                .map(|e| &e.publisher)
16970        })
16971    }
16972
16973    #[cfg(feature = "param-services")]
16974    /// phase-491 W3 (RFC-0105 D8) — publish `node`'s parameter changes on
16975    /// `/parameter_events` (rclc's `notify_changed_over_dds`).
16976    ///
16977    /// Creates the node's own `/parameter_events` publisher on the first
16978    /// call (see `ParamState::event_publishers`; one per node since issue
16979    /// 2493, as stock), typed
16980    /// `rcl_interfaces/msg/ParameterEvent`, RELIABLE + VOLATILE as upstream's
16981    /// `parameter_events` profile. Its depth is upstream's 1000 on a hosted
16982    /// build and `NROS_PARAMS_EVENTS_DEPTH` (default 1) otherwise, because a
16983    /// reliable DDS writer's history is memory the RMW reserves; depth is not
16984    /// a matching criterion, so an upstream subscriber still matches.
16985    /// Idempotent.
16986    pub(crate) fn enable_parameter_events_on(
16987        &mut self,
16988        node: super::node_record::NodeId,
16989    ) -> Result<(), NodeError> {
16990        type Event = nros_rcl_interfaces::msg::ParameterEvent;
16991        if !self.ensure_parameter_store() {
16992            return Err(NodeError::Transport(TransportError::BadAlloc));
16993        }
16994        let idx = node.index();
16995        if idx >= crate::param_sizing::MAX_SERVICE_SETS {
16996            return Err(NodeError::NodeTableFull);
16997        }
16998        // Issue 2023 — an explicit request overrides an earlier opt-out.
16999        if let Some(params) = self.params.as_deref_mut() {
17000            params.events_opt_out.set(node.into(), false);
17001        }
17002        if self
17003            .params
17004            .as_ref()
17005            .is_some_and(|p| p.event_publishers.iter().any(|e| e.node == idx))
17006        {
17007            if let Some(params) = self.params.as_mut() {
17008                params.server.set_parameter_events(node.into(), true);
17009            }
17010            return Ok(());
17011        }
17012        // The event is encoded into the services' reply buffer; on the heap
17013        // road that pair is allocated with the first service set, which may
17014        // not exist yet.
17015        #[cfg(feature = "alloc")]
17016        if let Some(params) = self.params.as_mut()
17017            && params.buffers.is_none()
17018        {
17019            params.buffers = Some(
17020                crate::parameter_services::ParamServiceBuffers::try_with_capacity(
17021                    crate::parameter_services::param_service_buffer_bytes(),
17022                )
17023                .ok_or(NodeError::Transport(TransportError::BadAlloc))?,
17024            );
17025        }
17026        crate::rmw_type_registry::register_type::<Event>()?;
17027        let qos = QoSProfile::parameter_events_default().depth(nros_params::PARAM_EVENTS_DEPTH);
17028        // Issue 2493 — one slot per parameter node; refused, not created,
17029        // when every slot is taken.
17030        if self
17031            .params
17032            .as_ref()
17033            .is_some_and(|p| p.event_publishers.is_full())
17034        {
17035            return Err(NodeError::NodeTableFull);
17036        }
17037        let handle = create_param_event_pub(self, node, qos)?;
17038        if let Some(params) = self.params.as_mut() {
17039            let _ = params
17040                .event_publishers
17041                .push(crate::param_store::EventPublisher {
17042                    node: idx,
17043                    publisher: handle,
17044                });
17045            params.server.set_parameter_events(node.into(), true);
17046        }
17047        Ok(())
17048    }
17049
17050    #[cfg(feature = "param-services")]
17051    /// Publish every pending parameter change, one
17052    /// `ParameterEvent` each, oldest first. Runs after each spin's parameter
17053    /// services and after every C or C++ parameter call; nothing allocates.
17054    pub fn flush_parameter_events(&mut self) {
17055        let stamp_ns = self
17056            .epoch_us_fn
17057            .or(self.clock_us_fn)
17058            .map_or(0, |clock| clock().saturating_mul(1000));
17059        let mut lost: u32 = 0;
17060        loop {
17061            let Some(params) = self.params.as_mut() else {
17062                return;
17063            };
17064            // Issue 2023 — a node's start-up event first, then the log.
17065            let Some(event) = params
17066                .server
17067                .pop_initial_parameter_event()
17068                .or_else(|| params.server.pop_parameter_event())
17069            else {
17070                break;
17071            };
17072            let idx = event.node.index();
17073            let mut fqn = heapless::String::<256>::new();
17074            match self.nodes.get(idx) {
17075                Some(r) => {
17076                    if let Ok(f) = crate::names::fully_qualified_name(&r.name, &r.namespace) {
17077                        let _ = fqn.push_str(f.as_str());
17078                    }
17079                }
17080                None => {
17081                    if let Ok(f) =
17082                        crate::names::fully_qualified_name(&self.node_name, &self.namespace)
17083                    {
17084                        let _ = fqn.push_str(f.as_str());
17085                    }
17086                }
17087            }
17088            let Some(params) = self.params.as_mut() else {
17089                return;
17090            };
17091            let crate::param_store::ParamState {
17092                server,
17093                buffers,
17094                event_publishers,
17095                ..
17096            } = &mut **params;
17097            // Issue 2493 — the event goes out on its OWN node's publisher.
17098            let (Some(publisher), Some(buffers)) = (
17099                event_publishers
17100                    .iter()
17101                    .find(|e| e.node == idx)
17102                    .map(|e| &e.publisher),
17103                buffers.as_mut(),
17104            ) else {
17105                continue;
17106            };
17107            let value = match event.kind {
17108                nros_params::ParameterEventKind::Deleted => None,
17109                _ => server.get(event.node, event.name.as_str()),
17110            };
17111            let encoded = crate::parameter_services::encode_parameter_event(
17112                buffers.reply_mut(),
17113                stamp_ns,
17114                fqn.as_str(),
17115                event.kind,
17116                event.name.as_str(),
17117                value,
17118            );
17119            match encoded {
17120                Some(n) => {
17121                    use nros_rmw::Publisher as _;
17122                    if publisher.publish_raw(&buffers.reply_mut()[..n]).is_err() {
17123                        lost = lost.saturating_add(1);
17124                    }
17125                }
17126                None => {
17127                    lost = lost.saturating_add(1);
17128                }
17129            }
17130        }
17131        let dropped = self
17132            .params
17133            .as_mut()
17134            .map_or(0, |p| p.server.take_parameter_events_dropped());
17135        let lost = lost.saturating_add(dropped);
17136        if lost > 0 {
17137            Self::report_parameter_events_lost(lost);
17138        }
17139    }
17140
17141    #[cfg(feature = "param-services")]
17142    #[cold]
17143    fn report_parameter_events_lost(lost: u32) {
17144        // Issue 2023 — an event that does not fit is REFUSED whole, never
17145        // truncated into a malformed sample; this line is how anyone hears.
17146        // phase-491 W3, issue 2023
17147        nros_log::log_error!(
17148            nros_log::get_logger("nros"),
17149            "{} /parameter_events message(s) were not published: the change log \
17150             (PARAMETER_EVENT_LOG_LEN) filled between two flushes, an event did not fit the \
17151             parameter-service reply buffer (NROS_EXECUTOR_PARAM_SERVICE_BUFFER_BYTES) and was refused \
17152             rather than truncated, or the publish failed. The parameters themselves changed.",
17153            lost
17154        );
17155    }
17156
17157    /// phase-491 W2 — a remote `NOT_SET` on `node` deletes the parameter
17158    /// (rclc) instead of being refused (rclcpp). See
17159    /// [`ParameterServer::set_delete_on_not_set`](nros_params::ParameterServerOps::set_delete_on_not_set).
17160    pub(crate) fn delete_parameters_on_not_set_on(
17161        &mut self,
17162        node: super::node_record::NodeId,
17163        on: bool,
17164    ) {
17165        self.ensure_parameter_store();
17166        if let Some(params) = &mut self.params {
17167            params.server.set_delete_on_not_set(node.into(), on);
17168        }
17169    }
17170
17171    /// May a remote set DECLARE a name this node never declared? Upstream's
17172    /// `allow_undeclared_parameters` node option (issue 1151), per node since
17173    /// phase-426 W1: switching it on for one node leaves its siblings
17174    /// refusing.
17175    pub(crate) fn allow_undeclared_parameters_on(
17176        &mut self,
17177        node: super::node_record::NodeId,
17178        allow: bool,
17179    ) {
17180        if allow {
17181            self.observe_undeclared_parameters(node);
17182        }
17183        self.ensure_parameter_store();
17184        if let Some(params) = &mut self.params {
17185            params.server.set_allow_undeclared(node.into(), allow);
17186        }
17187    }
17188
17189    /// [`allow_undeclared_parameters_on`](Self::allow_undeclared_parameters_on)
17190    /// for the primary node.
17191    // phase-515 R10 -- the node is the parameter receiver.
17192    #[deprecated(
17193        since = "0.6.0",
17194        note = "the node is the parameter receiver: call `node.allow_undeclared_parameters(allow)` on the `Node` that `create_node` / `node_mut(id)` returns"
17195    )]
17196    pub fn allow_undeclared_parameters(&mut self, allow: bool) {
17197        self.allow_undeclared_parameters_on(super::node_record::NodeId::PRIMARY, allow);
17198    }
17199
17200    /// Get a parameter value by name from the primary node.
17201    // phase-515 R10 -- the node is the parameter receiver.
17202    #[deprecated(
17203        since = "0.6.0",
17204        note = "the node is the parameter receiver: call `node.get_parameter(name)` on the `Node` that `create_node` / `node_mut(id)` returns"
17205    )]
17206    pub fn get_parameter(&self, name: &str) -> Option<&nros_params::ParameterValue> {
17207        self.get_parameter_on(super::node_record::NodeId::PRIMARY, name)
17208    }
17209
17210    /// Get a parameter value by name from a named node.
17211    pub(crate) fn get_parameter_on(
17212        &self,
17213        node: super::node_record::NodeId,
17214        name: &str,
17215    ) -> Option<&nros_params::ParameterValue> {
17216        self.params.as_deref()?.server.get(node.into(), name)
17217    }
17218
17219    /// Get an integer parameter value by name from the primary node (convenience).
17220    pub fn get_parameter_integer(&self, name: &str) -> Option<i64> {
17221        self.params
17222            .as_ref()?
17223            .server
17224            .get_integer(super::node_record::NodeId::PRIMARY.into(), name)
17225    }
17226
17227    /// Get a reference to the parameter server (if registered).
17228    pub fn params(&self) -> Option<&nros_params::ParameterServer<'s>> {
17229        self.params.as_deref().map(|p| &p.server)
17230    }
17231
17232    /// Get a mutable reference to the parameter server (if registered).
17233    pub fn params_mut(&mut self) -> Option<&mut nros_params::ParameterServer<'s>> {
17234        self.params.as_deref_mut().map(|p| &mut p.server)
17235    }
17236
17237    /// Create a typed parameter builder (rclrs-compatible API).
17238    ///
17239    /// Returns a [`ParameterBuilder`] for fluent parameter declaration with
17240    /// `.default()`, `.description()`, `.range()`, and terminal methods
17241    /// `.mandatory()`, `.optional()`, or `.read_only()`.
17242    ///
17243    /// Returns [`NodeError::NotInitialized`] if parameter services have
17244    /// not been registered yet — call [`register_parameter_services`]
17245    /// first.
17246    ///
17247    /// # Example
17248    ///
17249    /// ```ignore
17250    /// let max_speed = executor.parameter::<f64>("max_speed")?
17251    ///     .default(25.0)
17252    ///     .description("Maximum velocity (m/s)")
17253    ///     .read_only()?;
17254    /// ```
17255    ///
17256    /// [`ParameterBuilder`]: nros_params::ParameterBuilder
17257    /// [`register_parameter_services`]: Self::register_parameter_services
17258    // phase-515 R10 -- the node is the parameter receiver.
17259    #[deprecated(
17260        since = "0.6.0",
17261        note = "the node is the parameter receiver: call `node.declare_parameter::<T>(name)` on the `Node` that `create_node` / `node_mut(id)` returns"
17262    )]
17263    pub fn parameter<'a, T: nros_params::ParameterVariant>(
17264        &'a mut self,
17265        name: &'a str,
17266    ) -> Result<nros_params::ParameterBuilder<'a, 's, T>, NodeError> {
17267        self.parameter_on(super::node_record::NodeId::PRIMARY, name)
17268    }
17269
17270    /// [`parameter`](Self::parameter) on a named node.
17271    pub(crate) fn parameter_on<'a, T: nros_params::ParameterVariant>(
17272        &'a mut self,
17273        node: super::node_record::NodeId,
17274        name: &'a str,
17275    ) -> Result<nros_params::ParameterBuilder<'a, 's, T>, NodeError> {
17276        // Issue 2670 -- observed here, where the typed builder starts, because
17277        // its terminals live in nros-params and know no node name. Reached only
17278        // by `parameter` and `Node::declare_parameter`; no C, C++ or
17279        // declarative route builds a typed builder.
17280        self.observe_code_parameter_declare(node, name, None, T::parameter_type());
17281        // phase-515 R10 — the store comes into being on first use, as it
17282        // does for `declare_parameter_on`: `Node::declare_parameter` is the
17283        // user-facing declaration now, and it must not need a call the old
17284        // one did not. `NotInitialized` remains for a heap that refused it.
17285        self.ensure_parameter_store();
17286        // Issue 1203 — a reserved name the executor acts on. The builder
17287        // declares through its own borrow of the store, so the seeded
17288        // placeholder has to leave first (or the declaration is refused, the
17289        // way a second `declare_parameter` is), and the next spin reads back
17290        // what was declared.
17291        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
17292        if name == crate::time_source::USE_SIM_TIME_PARAM {
17293            self.yield_seeded_use_sim_time(node, name);
17294            if let Some(pending) = self
17295                .params
17296                .as_deref_mut()
17297                .and_then(|p| p.sim_time_via_builder.get_mut(node.index()))
17298            {
17299                *pending = true;
17300            }
17301        }
17302        let server = self
17303            .params
17304            .as_mut()
17305            .map(|p| &mut p.server)
17306            .ok_or(NodeError::NotInitialized)?;
17307        Ok(nros_params::ParameterBuilder::new(
17308            server,
17309            node.into(),
17310            name,
17311        ))
17312    }
17313
17314    // ========================================================================
17315    // phase-417 W4.a — the surface C and C++ forward to
17316    //
17317    // Every one of these is a forwarder onto `nros_params::ParameterServer`,
17318    // the ONE store. They exist on the executor because that is the object the
17319    // FFI holds: a C caller has an `rclc_executor_t*` and an `rcl_node_t*`,
17320    // and a C++ node has its `node_id`. Nothing here keeps state — a wrapper
17321    // that did would be the second store phase-426 removed.
17322    // ========================================================================
17323
17324    /// Attach a description and free-text constraints to a declared parameter
17325    /// on `node` — rclc's `rclc_add_parameter_description`.
17326    pub(crate) fn set_parameter_description_on(
17327        &mut self,
17328        node: super::node_record::NodeId,
17329        name: &str,
17330        description: &str,
17331        additional_constraints: &str,
17332    ) -> bool {
17333        match &mut self.params {
17334            Some(params) => params.server.set_parameter_description(
17335                node.into(),
17336                name,
17337                description,
17338                additional_constraints,
17339            ),
17340            None => false,
17341        }
17342    }
17343
17344    /// [`set_parameter_description_on`](Self::set_parameter_description_on) for
17345    /// the primary node.
17346    // phase-515 R10 -- the node is the parameter receiver.
17347    #[deprecated(
17348        since = "0.6.0",
17349        note = "the node is the parameter receiver: call `node.set_parameter_description(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
17350    )]
17351    pub fn set_parameter_description(
17352        &mut self,
17353        name: &str,
17354        description: &str,
17355        additional_constraints: &str,
17356    ) -> bool {
17357        self.set_parameter_description_on(
17358            super::node_record::NodeId::PRIMARY,
17359            name,
17360            description,
17361            additional_constraints,
17362        )
17363    }
17364
17365    /// Mark a declared parameter read-only — rclc's
17366    /// `rclc_set_parameter_read_only`. Every later write, local or remote, is
17367    /// refused.
17368    pub(crate) fn set_parameter_read_only_on(
17369        &mut self,
17370        node: super::node_record::NodeId,
17371        name: &str,
17372        read_only: bool,
17373    ) -> bool {
17374        match &mut self.params {
17375            Some(params) => params
17376                .server
17377                .set_parameter_read_only(node.into(), name, read_only),
17378            None => false,
17379        }
17380    }
17381
17382    /// [`set_parameter_read_only_on`](Self::set_parameter_read_only_on) for the
17383    /// primary node.
17384    // phase-515 R10 -- the node is the parameter receiver.
17385    #[deprecated(
17386        since = "0.6.0",
17387        note = "the node is the parameter receiver: call `node.set_parameter_read_only(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
17388    )]
17389    pub fn set_parameter_read_only(&mut self, name: &str, read_only: bool) -> bool {
17390        self.set_parameter_read_only_on(super::node_record::NodeId::PRIMARY, name, read_only)
17391    }
17392
17393    /// Attach an integer range — rclc's
17394    /// `rclc_add_parameter_constraint_integer`. Refuses an ill-formed range or
17395    /// one the current value does not satisfy.
17396    pub(crate) fn set_parameter_integer_range_on(
17397        &mut self,
17398        node: super::node_record::NodeId,
17399        name: &str,
17400        min: i64,
17401        max: i64,
17402        step: i64,
17403    ) -> bool {
17404        match &mut self.params {
17405            Some(params) => {
17406                params
17407                    .server
17408                    .set_parameter_integer_range(node.into(), name, min, max, step)
17409            }
17410            None => false,
17411        }
17412    }
17413
17414    /// [`set_parameter_integer_range_on`](Self::set_parameter_integer_range_on)
17415    /// for the primary node.
17416    // phase-515 R10 -- the node is the parameter receiver.
17417    #[deprecated(
17418        since = "0.6.0",
17419        note = "the node is the parameter receiver: call `node.set_parameter_integer_range(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
17420    )]
17421    pub fn set_parameter_integer_range(
17422        &mut self,
17423        name: &str,
17424        min: i64,
17425        max: i64,
17426        step: i64,
17427    ) -> bool {
17428        self.set_parameter_integer_range_on(
17429            super::node_record::NodeId::PRIMARY,
17430            name,
17431            min,
17432            max,
17433            step,
17434        )
17435    }
17436
17437    /// Attach a floating-point range — rclc's
17438    /// `rclc_add_parameter_constraint_double`.
17439    pub(crate) fn set_parameter_float_range_on(
17440        &mut self,
17441        node: super::node_record::NodeId,
17442        name: &str,
17443        min: f64,
17444        max: f64,
17445        step: f64,
17446    ) -> bool {
17447        match &mut self.params {
17448            Some(params) => {
17449                params
17450                    .server
17451                    .set_parameter_float_range(node.into(), name, min, max, step)
17452            }
17453            None => false,
17454        }
17455    }
17456
17457    /// [`set_parameter_float_range_on`](Self::set_parameter_float_range_on) for
17458    /// the primary node.
17459    // phase-515 R10 -- the node is the parameter receiver.
17460    #[deprecated(
17461        since = "0.6.0",
17462        note = "the node is the parameter receiver: call `node.set_parameter_float_range(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
17463    )]
17464    pub fn set_parameter_float_range(&mut self, name: &str, min: f64, max: f64, step: f64) -> bool {
17465        self.set_parameter_float_range_on(super::node_record::NodeId::PRIMARY, name, min, max, step)
17466    }
17467
17468    /// The descriptor of a declared parameter — rclcpp's
17469    /// `describe_parameter`, rclrs's `ParameterBuilder` readback. `None` when
17470    /// the parameter is not declared on `node`, or was declared without one.
17471    pub(crate) fn describe_parameter_on(
17472        &self,
17473        node: super::node_record::NodeId,
17474        name: &str,
17475    ) -> Option<&nros_params::ParameterDescriptor> {
17476        self.params
17477            .as_ref()?
17478            .server
17479            .get_descriptor(node.into(), name)
17480    }
17481
17482    /// [`describe_parameter_on`](Self::describe_parameter_on) for the primary
17483    /// node.
17484    // phase-515 R10 -- the node is the parameter receiver.
17485    #[deprecated(
17486        since = "0.6.0",
17487        note = "the node is the parameter receiver: call `node.describe_parameter(name)` on the `Node` that `create_node` / `node_mut(id)` returns"
17488    )]
17489    pub fn describe_parameter(&self, name: &str) -> Option<&nros_params::ParameterDescriptor> {
17490        self.describe_parameter_on(super::node_record::NodeId::PRIMARY, name)
17491    }
17492
17493    /// The declared TYPE of a parameter — rclcpp's `get_parameter_types`, and
17494    /// the local answer to the `~/get_parameter_types` service.
17495    pub(crate) fn get_parameter_type_on(
17496        &self,
17497        node: super::node_record::NodeId,
17498        name: &str,
17499    ) -> Option<nros_params::ParameterType> {
17500        self.params.as_deref()?.server.get_type(node.into(), name)
17501    }
17502
17503    /// [`get_parameter_type_on`](Self::get_parameter_type_on) for the primary
17504    /// node.
17505    // phase-515 R10 -- the node is the parameter receiver.
17506    #[deprecated(
17507        since = "0.6.0",
17508        note = "the node is the parameter receiver: call `node.get_parameter_type(name)` on the `Node` that `create_node` / `node_mut(id)` returns"
17509    )]
17510    pub fn get_parameter_type(&self, name: &str) -> Option<nros_params::ParameterType> {
17511        self.get_parameter_type_on(super::node_record::NodeId::PRIMARY, name)
17512    }
17513
17514    /// The names a node has declared, filtered by prefix — rclcpp's
17515    /// `list_parameters`, and the local answer to `~/list_parameters`. An
17516    /// empty prefix lists them all.
17517    pub(crate) fn list_parameters_on<'p>(
17518        &'p self,
17519        node: super::node_record::NodeId,
17520        prefix: &'p str,
17521    ) -> impl Iterator<Item = &'p str> {
17522        self.params
17523            .as_ref()
17524            .into_iter()
17525            .flat_map(move |p| p.server.list_with_prefix(node.into(), prefix))
17526    }
17527
17528    /// How many parameters `node` holds that someone DECLARED -- every name
17529    /// [`list_parameters_on`](Self::list_parameters_on) yields, less the
17530    /// runtime's seeded `use_sim_time` placeholder while it is still one.
17531    ///
17532    /// This is the count an rclc parameter server's `max_params` is measured
17533    /// against. rclc never declares `use_sim_time`, so an application sizes
17534    /// `max_params` for its own names; charging it for a placeholder the
17535    /// runtime seeded (and steps aside the moment the application declares
17536    /// the name itself) made a node sized exactly for its parameters refuse
17537    /// its last one once the stock interface set carried `sim_time`.
17538    pub(crate) fn declared_parameter_count_on(&self, node: super::node_record::NodeId) -> usize {
17539        let listed = self.list_parameters_on(node, "").count();
17540        listed.saturating_sub(usize::from(self.sim_time_placeholder_on(node)))
17541    }
17542
17543    /// Whether `node`'s `use_sim_time` is still the runtime's placeholder.
17544    fn sim_time_placeholder_on(&self, node: super::node_record::NodeId) -> bool {
17545        #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
17546        if let Some(params) = self.params.as_deref()
17547            && params.sim_time_seeded.get(node.index()).copied() == Some(true)
17548        {
17549            return true;
17550        }
17551        let _ = node;
17552        false
17553    }
17554
17555    /// [`list_parameters_on`](Self::list_parameters_on) for the primary node.
17556    // phase-515 R10 -- the node is the parameter receiver.
17557    #[deprecated(
17558        since = "0.6.0",
17559        note = "the node is the parameter receiver: call `node.list_parameters(prefix)` on the `Node` that `create_node` / `node_mut(id)` returns"
17560    )]
17561    pub fn list_parameters<'p>(&'p self, prefix: &'p str) -> impl Iterator<Item = &'p str> {
17562        self.list_parameters_on(super::node_record::NodeId::PRIMARY, prefix)
17563    }
17564
17565    /// All-or-nothing multi-set on `node` — rclcpp's
17566    /// `set_parameters_atomically`.
17567    ///
17568    /// We SERVED `~/set_parameters_atomically` and offered it in no language,
17569    /// so the only way to reach our own atomic set was over the wire. This is
17570    /// the same call the service handler makes.
17571    ///
17572    /// `items` yields `None` for an element that could not be turned into a
17573    /// value at all; that refuses the batch like any failing check.
17574    pub(crate) fn set_parameters_atomically_on<'x, I>(
17575        &mut self,
17576        node: super::node_record::NodeId,
17577        items: I,
17578    ) -> Result<(), nros_params::ParameterError>
17579    where
17580        I: Iterator<Item = Option<(&'x str, nros_params::ParameterValue)>> + Clone,
17581    {
17582        match &mut self.params {
17583            Some(params) => params.server.apply_atomically(node.into(), items),
17584            None => Err(nros_params::ParameterError::NotFound),
17585        }
17586    }
17587
17588    /// [`set_parameters_atomically_on`](Self::set_parameters_atomically_on),
17589    /// with element `i` FILLED into one scratch value by `fill(i, slot)`
17590    /// (`ParameterServer::apply_atomically_with`, issue 2104). For a caller
17591    /// that would otherwise build each ~8 KiB value on its own stack.
17592    pub(crate) fn set_parameters_atomically_with_on<'x>(
17593        &mut self,
17594        node: super::node_record::NodeId,
17595        count: usize,
17596        fill: impl FnMut(usize, &mut nros_params::ParameterValue) -> Option<&'x str>,
17597    ) -> Result<(), nros_params::ParameterError> {
17598        match &mut self.params {
17599            Some(params) => params
17600                .server
17601                .apply_atomically_with(node.into(), count, fill),
17602            None => Err(nros_params::ParameterError::NotFound),
17603        }
17604    }
17605
17606    /// [`set_parameters_atomically_on`](Self::set_parameters_atomically_on) for
17607    /// the primary node.
17608    // phase-515 R10 -- the node is the parameter receiver.
17609    #[deprecated(
17610        since = "0.6.0",
17611        note = "the node is the parameter receiver: call `node.set_parameters_atomically(items)` on the `Node` that `create_node` / `node_mut(id)` returns"
17612    )]
17613    pub fn set_parameters_atomically<'x, I>(
17614        &mut self,
17615        items: I,
17616    ) -> Result<(), nros_params::ParameterError>
17617    where
17618        I: Iterator<Item = Option<(&'x str, nros_params::ParameterValue)>> + Clone,
17619    {
17620        self.set_parameters_atomically_on(super::node_record::NodeId::PRIMARY, items)
17621    }
17622
17623    /// Undeclare a parameter — rclcpp's `undeclare_parameter`, rclc's
17624    /// `rclc_delete_parameter`. The slot is freed for a later declaration.
17625    pub(crate) fn undeclare_parameter_on(
17626        &mut self,
17627        node: super::node_record::NodeId,
17628        name: &str,
17629    ) -> bool {
17630        match &mut self.params {
17631            Some(params) => params.server.remove(node.into(), name),
17632            None => false,
17633        }
17634    }
17635
17636    /// [`undeclare_parameter_on`](Self::undeclare_parameter_on) for the primary
17637    /// node.
17638    // phase-515 R10 -- the node is the parameter receiver.
17639    #[deprecated(
17640        since = "0.6.0",
17641        note = "the node is the parameter receiver: call `node.undeclare_parameter(name)` on the `Node` that `create_node` / `node_mut(id)` returns"
17642    )]
17643    pub fn undeclare_parameter(&mut self, name: &str) -> bool {
17644        self.undeclare_parameter_on(super::node_record::NodeId::PRIMARY, name)
17645    }
17646
17647    /// Register an accept/reject hook for writes to `node` — rclcpp's
17648    /// `add_on_set_parameters_callback`.
17649    ///
17650    /// It runs on every write that reaches the store through
17651    /// [`set_parameter_on`](Self::set_parameter_on), which is the seam the six
17652    /// `rcl_interfaces/srv/*` servers and both wrapper languages share, so ONE
17653    /// registration covers a remote `ros2 param set` and a local one alike.
17654    ///
17655    /// `None` when all [`nros_params::MAX_ON_SET_CALLBACKS`] slots are taken.
17656    pub(crate) fn add_on_set_parameters_callback_on(
17657        &mut self,
17658        node: super::node_record::NodeId,
17659        callback: nros_params::OnSetParameterFn,
17660        ctx: nros_params::OnSetContext,
17661    ) -> Option<nros_params::OnSetParameterHandle> {
17662        self.ensure_parameter_store();
17663        self.params
17664            .as_mut()?
17665            .server
17666            .add_on_set_parameters_callback(node.into(), callback, ctx)
17667    }
17668
17669    /// [`add_on_set_parameters_callback_on`](Self::add_on_set_parameters_callback_on)
17670    /// for the primary node.
17671    // phase-515 R10 -- the node is the parameter receiver.
17672    #[deprecated(
17673        since = "0.6.0",
17674        note = "the node is the parameter receiver: call `node.add_on_set_parameters_callback(..)` on the `Node` that `create_node` / `node_mut(id)` returns"
17675    )]
17676    pub fn add_on_set_parameters_callback(
17677        &mut self,
17678        callback: nros_params::OnSetParameterFn,
17679        ctx: nros_params::OnSetContext,
17680    ) -> Option<nros_params::OnSetParameterHandle> {
17681        self.add_on_set_parameters_callback_on(super::node_record::NodeId::PRIMARY, callback, ctx)
17682    }
17683
17684    /// Unregister a hook — rclcpp's `remove_on_set_parameters_callback`.
17685    pub fn remove_on_set_parameters_callback(
17686        &mut self,
17687        handle: nros_params::OnSetParameterHandle,
17688    ) -> bool {
17689        match &mut self.params {
17690            Some(params) => params.server.remove_on_set_parameters_callback(handle),
17691            None => false,
17692        }
17693    }
17694
17695    /// rclrs's `Node::use_undeclared_parameters` — a handle that reads and
17696    /// writes parameters this node never declared.
17697    ///
17698    /// The handle writes through `set_or_declare`, not through the wire-facing
17699    /// `apply`: `allow_undeclared_parameters` governs what a REMOTE set may
17700    /// create, and a caller who reached for this type has opted in by naming
17701    /// it. That is rclrs's split too.
17702    pub(crate) fn use_undeclared_parameters_on(
17703        &mut self,
17704        node: super::node_record::NodeId,
17705    ) -> Result<nros_params::Parameters<'_, 's>, NodeError> {
17706        self.observe_undeclared_parameters(node);
17707        self.ensure_parameter_store(); // phase-515 R10, as `parameter_on`
17708        let server = self
17709            .params
17710            .as_mut()
17711            .map(|p| &mut p.server)
17712            .ok_or(NodeError::NotInitialized)?;
17713        Ok(nros_params::Parameters::new(server, node.into()))
17714    }
17715
17716    /// [`use_undeclared_parameters_on`](Self::use_undeclared_parameters_on) for
17717    /// the primary node.
17718    // phase-515 R10 -- the node is the parameter receiver.
17719    #[deprecated(
17720        since = "0.6.0",
17721        note = "the node is the parameter receiver: call `node.use_undeclared_parameters()` on the `Node` that `create_node` / `node_mut(id)` returns"
17722    )]
17723    pub fn use_undeclared_parameters(
17724        &mut self,
17725    ) -> Result<nros_params::Parameters<'_, 's>, NodeError> {
17726        self.use_undeclared_parameters_on(super::node_record::NodeId::PRIMARY)
17727    }
17728}
17729
17730// ============================================================================
17731// Executor lifecycle — cancel / is_spinning (phase-417 W4.c)
17732// ============================================================================
17733
17734// Issue 1177 -- UN-GATED. This block was `#[cfg(feature = "alloc")]` because
17735// `halt_flag` and `spinning` were `alloc` fields, and neither needed to be: the
17736// allocator is required to SHARE the halt flag (`halt_flag()` hands out a
17737// refcounted handle), never to hold it.
17738//
17739// Gating it meant a no_std executor could not be stopped, and worse, that
17740// `nros-c`'s spin loop -- which calls `cancel`, `is_halted`, `is_spinning`,
17741// `enter_spin_loop` and `exit_spin_loop` with no cfg of its own -- did not
17742// COMPILE for an embedded image. The safety island found that; no
17743// merge-gating lane builds this crate without `alloc`.
17744impl<'s> Executor<'s> {
17745    /// Request the executor to stop spinning — `rclcpp::Executor::cancel`.
17746    ///
17747    /// # ADOPT-BOUNDED
17748    ///
17749    /// `cancel` sets a flag the spin loop observes at the NEXT POLL BOUNDARY,
17750    /// so it returns BEFORE spinning has actually stopped;
17751    /// [`is_spinning()`](Self::is_spinning) is the observable that tells you
17752    /// when it has. rclcpp makes the same promise in the same shape, but the
17753    /// boundary here is one `spin_once` timeout wide (a backend's `drive_io`
17754    /// blocks up to the poll interval), so "next boundary" is a duration a
17755    /// caller can measure rather than an implementation detail. The wake flag
17756    /// below shortens it; it does not remove it.
17757    ///
17758    /// Nothing here tears down the session: an executor that has been cancelled
17759    /// is still initialised, still owns its entities, and can be spun again.
17760    /// Teardown is a different verb (`fini` / `shutdown`), and collapsing the
17761    /// two costs a full discovery round on every mode change.
17762    ///
17763    /// Safe to call from another thread or a signal handler.
17764    ///
17765    /// Also raises the wake flag so a `spin_once` already blocked
17766    /// inside a backend's `drive_io` falls through to the cancel check on its
17767    /// next loop iteration instead of waiting out its full `timeout_ms` first.
17768    pub fn cancel(&self) {
17769        self.halt_flag
17770            .store(true, core::sync::atomic::Ordering::SeqCst);
17771        // The wake flag is the `Arc` half and still needs an allocator. A
17772        // core-only image simply waits out the poll interval, which is the
17773        // bounded behaviour the envelope above already promises.
17774        #[cfg(feature = "alloc")]
17775        self.wake_flag
17776            .store(true, core::sync::atomic::Ordering::SeqCst);
17777        // phase-521 W6 (RFC-0113 D2) — and end a PARK, not only a backend
17778        // wait. An entry parks until its next deadline rather than for a
17779        // fixed slice, so a cancel that only raised the flag would wait out
17780        // that whole park. `nros_platform_wake_signal` is the port's ISR- and
17781        // signal-safe post, the one an arrival uses.
17782        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
17783        if let Some(wake) = self.node_wake.as_ref() {
17784            wake.signal();
17785        }
17786    }
17787
17788    /// Wake every worker parked over this
17789    /// executor: its own and every level's band worker, as an arrival nothing
17790    /// attributes does. A level parks until its band's next deadline or an
17791    /// arrival, not for a fixed period, so a runner that stops its levels must
17792    /// end those parks or wait them out. Lock-free; safe from any thread.
17793    /// Raises no halt: a woken worker runs one pass and parks again unless its
17794    /// runner's own stop flag says otherwise.
17795    pub fn wake_all_workers(&self) {
17796        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
17797        if let Some(ctx) = self.wake_ctx.as_ref() {
17798            ctx.signal();
17799        }
17800    }
17801
17802    /// Has a [`cancel()`](Self::cancel) been REQUESTED?
17803    ///
17804    /// Not the same question as [`is_spinning()`](Self::is_spinning), and both
17805    /// are kept because both have callers:
17806    ///
17807    /// * `is_halted()` — "someone asked this executor to stop." True the instant
17808    ///   `cancel()` returns, and it stays true until the next spin loop clears
17809    ///   it on entry. This is the flag a hand-rolled `while !exec.is_halted()`
17810    ///   loop polls, which is what a BSP that drives `spin_once` itself writes.
17811    /// * `is_spinning()` — "a spin loop is running right now." Answers the other
17812    ///   half of the envelope: whether the cancel has been ACTED on yet.
17813    ///
17814    /// The two are true together for as long as one poll takes, which is exactly
17815    /// the window the ADOPT-BOUNDED envelope on `cancel()` describes. Neither is
17816    /// derivable from the other: an executor that was never spun is neither
17817    /// halted nor spinning, and one cancelled mid-poll is both.
17818    ///
17819    /// The name is the pre-rename spelling and is deliberately NOT deprecated —
17820    /// `cancel`'s rclcpp pair is a `spinning` observable, not an
17821    /// `is_cancel_requested` one, so there is no ROS 2 name to adopt here and a
17822    /// third spelling would buy nothing.
17823    pub fn is_halted(&self) -> bool {
17824        self.halt_flag.load(core::sync::atomic::Ordering::SeqCst)
17825    }
17826
17827    /// Is a spin loop running on this executor right now?
17828    ///
17829    /// rclcpp spells this `Executor::is_spinning()`. True between the entry and
17830    /// the exit of [`spin`](Self::spin),
17831    /// [`spin_period`](Self::spin_period), the `open_threaded` worker loop, and
17832    /// the C / C++ API loops — every construct that owns its own iteration.
17833    ///
17834    /// A bare `spin_once` does NOT set it: one poll is not a spin, and a caller
17835    /// running its own `while` around `spin_once` is the one who knows it is
17836    /// looping. Such a caller can say so with
17837    /// [`enter_spin_loop`](crate::executor::ffi::ExecutorFfi::enter_spin_loop).
17838    ///
17839    /// See [`is_halted()`](Self::is_halted) for why this is a different question
17840    /// from "was cancel requested".
17841    pub fn is_spinning(&self) -> bool {
17842        self.spinning.load(core::sync::atomic::Ordering::SeqCst)
17843    }
17844
17845    /// Declare that the caller is entering a spin loop it drives itself.
17846    ///
17847    /// The seam the C and C++ APIs use so their loops answer
17848    /// [`is_spinning()`](Self::is_spinning) without keeping a flag of their own
17849    /// (RFC-0019: ergonomics may live in the wrapper, state may not). Also
17850    /// CLEARS any pending cancel, matching what `spin` does on entry:
17851    /// a cancel requested before a spin started is not a cancel of THIS spin.
17852    ///
17853    /// Pair it with [`exit_spin_loop`](Self::exit_spin_loop) on EVERY exit path,
17854    /// `break` and early `return` alike — a loop that leaves without it reports
17855    /// `is_spinning() == true` forever. It is a method pair rather than an RAII
17856    /// guard on purpose: a guard would have to borrow the executor for the whole
17857    /// loop, and every caller needs `&mut` inside the body to poll.
17858    ///
17859    /// Takes `&self` (the flags are atomics), so the borrow ends at the call.
17860    pub(crate) fn enter_spin_loop(&self) {
17861        self.halt_flag
17862            .store(false, core::sync::atomic::Ordering::SeqCst);
17863        self.spinning
17864            .store(true, core::sync::atomic::Ordering::SeqCst);
17865    }
17866
17867    /// End the scope opened by [`enter_spin_loop`](Self::enter_spin_loop).
17868    ///
17869    /// Idempotent. Leaves the cancel flag alone: "someone asked me to stop" is
17870    /// the caller's answer to keep or clear, and clearing it here would lose the
17871    /// reason the loop exited.
17872    pub(crate) fn exit_spin_loop(&self) {
17873        self.spinning
17874            .store(false, core::sync::atomic::Ordering::SeqCst);
17875    }
17876}
17877
17878// ============================================================================
17879// std-gated spin and halt methods
17880// ============================================================================
17881
17882// phase-359 W10 — this impl used to be ONE `#[cfg(feature = "std")]` block.
17883// Only the wall-clock spin loops in it need `std` (`Instant`, `thread::sleep`,
17884// `thread::spawn`); `halt` / `is_halted` / `wake` are plain atomic stores on
17885// flags the struct already owns, and `halt_flag` / `wake_handle` only need
17886// `Arc`. Gating the BLOCK rather than the items made a no_std image unable to
17887// stop its own executor — `ExecutorNodeRuntime::spin` carried a matching `std`
17888// gate for no reason but this one.
17889// phase-359 W10 — `alloc`, not `std`. The wall-clock spin loops were the
17890// reason this block was std-gated: `Instant` for the deadline and
17891// `thread::sleep` for the pacing. Both now go through the platform — the
17892// executor's own `now_us()` and `nros_platform_sleep_us` — so a no_std
17893// image can run the same blocking loops a hosted one does instead of
17894// hand-rolling them in its BSP.
17895#[cfg(feature = "alloc")]
17896impl<'s> Executor<'s> {
17897    /// Blocking spin loop with configurable exit conditions — rclrs's
17898    /// `Executor::spin(SpinOptions)`.
17899    ///
17900    /// ADOPT-BOUNDED. Same name, same argument, same meaning: run
17901    /// until an exit condition in `opts` says stop. Two bounds, both visible in
17902    /// the signature:
17903    ///
17904    /// * **The error channel is one error, not all of them.** rclrs returns
17905    ///   `Vec<RclrsError>` and the caller writes `.first_error()?`; there is no
17906    ///   allocator here, so ours returns `Result<(), NodeError>` carrying the
17907    ///   FIRST failing callback's error and drops the rest (they are still
17908    ///   counted in each pass's [`SpinOnceResult`]). Ported line for line, the
17909    ///   edit is `.first_error()?` -> `?`, which the compiler points at.
17910    /// * **The loop is a poll loop**, so `opts.poll_interval` is the quantum at
17911    ///   which every exit condition is observed — a `cancel()` from another
17912    ///   task, the `timeout` expiring, `max_callbacks` being reached. Requesting
17913    ///   a `timeout` on a build with no clock is an ERROR, not a silent
17914    ///   never-ending loop.
17915    ///
17916    /// This method was ~~`spin_blocking`~~. `spin` was taken by the
17917    /// `-> !` task body, which is now [`spin_forever`](Self::spin_forever).
17918    ///
17919    /// Runs until one of:
17920    /// - [`cancel()`](Self::cancel) is called (from
17921    ///   another thread or signal handler)
17922    /// - `opts.timeout` expires (if set)
17923    /// - `opts.max_callbacks` is reached (if set)
17924    /// - `opts.only_next` is true (single iteration)
17925    /// - a callback failed and `opts.stop_on_first_error` is set
17926    ///
17927    /// # Example
17928    ///
17929    /// ```ignore
17930    /// // Spin until cancelled
17931    /// executor.spin(SpinOptions::default())?;
17932    ///
17933    /// // Spin with 5-second timeout
17934    /// executor.spin(SpinOptions::new().timeout(core::time::Duration::from_secs(5)))?;
17935    ///
17936    /// // Single iteration
17937    /// executor.spin(SpinOptions::spin_once())?;
17938    /// ```
17939    pub fn spin(&mut self, opts: SpinOptions) -> Result<(), NodeError> {
17940        // phase-427 — was a private ~~`POLL_INTERVAL`~~ const; it is
17941        // `SpinOptions::poll_interval` now, defaulting to the same 10 ms, so
17942        // `spin` and `spin_forever` read one value instead of two literals.
17943        let poll_interval = opts.poll_interval;
17944
17945        // phase-359 W10 — the executor's own clock. `now_us()` reads the
17946        // PLATFORM's monotonic counter, and nothing else: the platform API is
17947        // the clock, so a build with a port has one and a build without has
17948        // none. There is no `std::time::Instant` third answer any more, which
17949        // is what used to make "what time is it" depend on whether some crate
17950        // in the graph happened to name `std`.
17951        //
17952        // `None` means this build has NO clock at all — and issue 0709 is what
17953        // the previous answer here cost. It read: "a timeout cannot be honoured
17954        // then, and pretending otherwise would exit immediately or never; the
17955        // honest reading is no deadline". It then picked NEVER. A caller that
17956        // asked for 50 ms got an infinite loop, silently, in the one API whose
17957        // whole contract is "returns after N ms" — ten hours of a CI lane
17958        // before anyone read it as stuck rather than slow.
17959        //
17960        // Neither of the two silent readings is honest. An unmet precondition
17961        // is an ERROR (repo rule, fail-loud): the caller supplied a time
17962        // quantity this build cannot measure, and only they can decide what to
17963        // do about it. An UNTIMED `spin` still runs until halt, which
17964        // is a promise this build can keep.
17965        let start_us = self.now_us();
17966        if opts.timeout.is_some() && start_us.is_none() {
17967            // issue 0709
17968            nros_log::log_error!(
17969                nros_log::get_logger("nros"),
17970                "spin: a timeout was requested but this build has no clock \
17971                 — install one with `ExecutorConfig::clock_us`"
17972            );
17973            return Err(NodeError::NotInitialized);
17974        }
17975        // `as_micros()` rather than a hand-rolled `ms * 1_000`: the multiply
17976        // was unchecked, and the unit conversion is `Duration`'s job.
17977        let timeout_us = opts.timeout.map(|d| d.as_micros() as u64);
17978        let mut total_callbacks = 0usize;
17979
17980        // TEMPORARY (phase-554 W3 slice C deletes it) -- a zero-node image's
17981        // waiting executor-level open, returned rather than counted.
17982        self.open_pending_on_configured_name()?;
17983
17984        // phase-417 W4.c — clears the cancel flag AND raises `is_spinning`. The
17985        // clear is the pre-existing behaviour (a cancel requested before this
17986        // spin is not a cancel of this spin); the raise is what lets a peer
17987        // thread see that its `cancel()` has not been acted on yet. Every exit
17988        // below is a `break` to the single tail, which is where the scope ends.
17989        self.enter_spin_loop();
17990
17991        loop {
17992            if self.halt_flag.load(core::sync::atomic::Ordering::SeqCst) {
17993                break;
17994            }
17995
17996            if let (Some(start), Some(limit)) = (start_us, timeout_us)
17997                && self
17998                    .now_us()
17999                    .is_some_and(|now| now.saturating_sub(start) >= limit)
18000            {
18001                break;
18002            }
18003
18004            let mut callback_error = None;
18005            let result = self.spin_once_capturing(poll_interval, &mut callback_error);
18006            total_callbacks += result.total();
18007
18008            // phase-427 — the first error, and only the first: rclrs's
18009            // `Vec<RclrsError>` needs an allocator we do not have. The scope is
18010            // closed before returning so a caller that reads `is_spinning()`
18011            // after an error sees `false`, exactly as after a clean exit.
18012            if opts.stop_on_first_error
18013                && let Some(e) = callback_error
18014            {
18015                self.exit_spin_loop();
18016                return Err(NodeError::Transport(e));
18017            }
18018
18019            if opts.max_callbacks.is_some_and(|max| total_callbacks >= max) {
18020                break;
18021            }
18022
18023            if opts.only_next {
18024                break;
18025            }
18026        }
18027
18028        self.exit_spin_loop();
18029        Ok(())
18030    }
18031
18032    /// Execute one period with wall-clock overrun detection.
18033    ///
18034    /// Calls [`spin_once()`](Self::spin_once), measures wall-clock time, sleeps
18035    /// for the remainder if under budget.
18036    ///
18037    /// # Example
18038    ///
18039    /// ```ignore
18040    /// let period = core::time::Duration::from_millis(10);
18041    /// let result = executor.spin_one_period_timed(period);
18042    /// if result.overrun {
18043    ///     log::warn!("Period overrun: {:?}", result.elapsed);
18044    /// }
18045    /// ```
18046    pub fn spin_one_period_timed(
18047        &mut self,
18048        period: core::time::Duration,
18049    ) -> super::types::SpinPeriodResult {
18050        let start_us = self.now_us();
18051        let result = self.spin_once(period);
18052        // With no clock there is nothing to measure and nothing to sleep off;
18053        // report zero elapsed and no overrun, which is what an unmeasured
18054        // period is.
18055        let elapsed = start_us
18056            .zip(self.now_us())
18057            .map(|(s, e)| core::time::Duration::from_micros(e.saturating_sub(s)))
18058            .unwrap_or_default();
18059        let overrun = elapsed > period;
18060        if !overrun && start_us.is_some() {
18061            platform_sleep(period - elapsed);
18062        }
18063        super::types::SpinPeriodResult {
18064            work: result,
18065            overrun,
18066            elapsed,
18067        }
18068    }
18069
18070    /// Spin at a fixed rate with drift compensation. Blocks until halted.
18071    ///
18072    /// Uses wall-clock time to maintain the target rate. The next invocation
18073    /// time is accumulated (not reset to `now + period`) to prevent cumulative
18074    /// drift.
18075    ///
18076    /// # Example
18077    ///
18078    /// ```ignore
18079    /// // 100Hz control loop — blocks until halt() is called
18080    /// executor.spin_period(core::time::Duration::from_millis(10))?;
18081    /// ```
18082    pub fn spin_period(&mut self, period: core::time::Duration) -> Result<(), NodeError> {
18083        let period_us = period.as_micros().min(u64::MAX as u128) as u64;
18084        // Absolute next-deadline in the executor's own clock. issue 0709 — the
18085        // sibling of `spin`'s guard above: with no clock there is no
18086        // pacing, and the loop would run as fast as `spin_once` returns while
18087        // the caller believes it is running at `period`. A requested period
18088        // this build cannot honour is a configuration error, not a silent
18089        // busy-loop.
18090        let Some(start_us) = self.now_us() else {
18091            // issue 0709
18092            nros_log::log_error!(
18093                nros_log::get_logger("nros"),
18094                "spin_period: a period was requested but this build has no clock \
18095                 — install one with `ExecutorConfig::clock_us`"
18096            );
18097            return Err(NodeError::NotInitialized);
18098        };
18099        // phase-417 W4.c — after the clock guard, not before it: a call that
18100        // returns an error never spun, and must not report that it did. (This
18101        // also moved the cancel-flag clear past the guard, which is the same
18102        // correction.)
18103        self.enter_spin_loop();
18104        let mut next_us = Some(start_us + period_us);
18105
18106        loop {
18107            if self.halt_flag.load(core::sync::atomic::Ordering::SeqCst) {
18108                break;
18109            }
18110
18111            self.spin_once(period);
18112
18113            if let Some(next) = next_us {
18114                // Jitter is recorded in `spin_once` above, which this loop
18115                // calls every iteration -- counting it here as well would
18116                // double every wake on this one driver.
18117                if let Some(now) = self.now_us()
18118                    && now < next
18119                {
18120                    platform_sleep(core::time::Duration::from_micros(next - now));
18121                }
18122                // Accumulate to prevent drift (not = now + period)
18123                next_us = Some(next + period_us);
18124            }
18125        }
18126        self.exit_spin_loop();
18127        Ok(())
18128    }
18129}
18130
18131#[cfg(feature = "alloc")]
18132impl<'s> Executor<'s> {
18133    /// Move this Executor onto a fresh OS thread,
18134    /// apply a per-thread scheduling policy via the caller-supplied
18135    /// `apply_policy` function, and run the spin loop until
18136    /// `ThreadHandle::halt` fires.
18137    ///
18138    /// The function-pointer indirection on `apply_policy` lets the
18139    /// caller pass any platform's `PlatformScheduler::set_current_thread_policy`
18140    /// without forcing `Executor` to be generic over the platform —
18141    /// keeps the existing `Executor` type stable.
18142    ///
18143    /// Multi-executor preemption (the actual hard-RT win) comes from
18144    /// the OS scheduler — call `open_threaded` once per criticality
18145    /// sched task, each with its own policy / priority. The kernel handles
18146    /// preemption across executors; within a single executor,
18147    /// dispatch remains non-preemptive (110.A–C bucketed sets).
18148    ///
18149    /// # Safety
18150    ///
18151    /// Moves `self` across thread boundaries. `Executor` contains a
18152    /// raw `*mut session::ConcreteSession` when constructed via
18153    /// `from_session_ptr`; the caller must ensure that pointer's
18154    /// referent stays valid across the lifetime of the spawned thread
18155    /// and that no other thread mutates the session concurrently.
18156    /// `from_session` (Owned) is safer — `ConcreteSession` ownership
18157    /// transfers cleanly into the thread.
18158    #[cfg(feature = "alloc")]
18159    pub unsafe fn open_threaded(
18160        self,
18161        policy: nros_platform_api::SchedPolicy,
18162        apply_policy: fn(
18163            nros_platform_api::SchedPolicy,
18164        ) -> Result<(), nros_platform_api::SchedError>,
18165        spin_period: core::time::Duration,
18166    ) -> ThreadHandle
18167    where
18168        // phase-271 — the spawned thread owns `self` for an unbounded lifetime,
18169        // so its borrowed storage must be `'static` (a leaked/`static` backing —
18170        // the `alloc` convenience constructors or a program-lifetime region).
18171        's: 'static,
18172    {
18173        let halt = self.halt_flag.clone();
18174        // phase-359 W10 — a platform task, not `std::thread`. The two other
18175        // executor-owned workers moved earlier; this is the third and last, and
18176        // it is the one the ABI fits best: `open_threaded` exists to give a
18177        // spin loop an OS SCHEDULING POLICY, which is not something a build
18178        // without an OS was ever going to get from `std`.
18179        //
18180        // The closure becomes a heap context because the entry point crosses C
18181        // as `*mut c_void`. It is reclaimed by the trampoline on exit rather
18182        // than leaked: unlike a sched task, this loop RETURNS — that is what
18183        // `halt` is for.
18184        let ctx = alloc::boxed::Box::into_raw(alloc::boxed::Box::new(ThreadedCtx {
18185            executor: self,
18186            policy,
18187            apply_policy,
18188            spin_period,
18189        }));
18190        // SAFETY: `ctx` stays live until the trampoline reclaims it, which
18191        // happens on the spawned task and only after the loop exits.
18192        let task = unsafe {
18193            nros_platform_api::task::PlatformTask::spawn(
18194                threaded_spin_trampoline,
18195                ctx as *mut core::ffi::c_void,
18196                OPEN_THREADED_STACK_BYTES,
18197                c"nros-exec".as_ptr(),
18198            )
18199        };
18200        let Some(task) = task else {
18201            // The platform refused (or cannot size) a task. Reclaim the
18202            // context and hand back a handle that owns nothing — `halt` and
18203            // `join` stay callable, which keeps the caller's shape identical to
18204            // the success path.
18205            //
18206            // SAFETY: nothing was spawned, so this pointer has no other owner.
18207            drop(unsafe { alloc::boxed::Box::from_raw(ctx) });
18208            return ThreadHandle { task: None, halt };
18209        };
18210        ThreadHandle {
18211            task: Some(task),
18212            halt,
18213        }
18214    }
18215
18216    /// Wake the executor from another thread / ISR /
18217    /// signal handler.
18218    ///
18219    /// Sets the shared `wake_flag`. The next `spin_once` swap-clears the
18220    /// flag, skips the blocking wait on the primary session, and polls
18221    /// every session non-blockingly so whatever queued the wake is
18222    /// observed in a single iteration. Idempotent — multiple `wake()`
18223    /// calls collapse into one observed wake per `spin_once`.
18224    pub fn wake(&self) {
18225        self.wake_flag
18226            .store(true, core::sync::atomic::Ordering::SeqCst);
18227    }
18228}
18229
18230#[cfg(feature = "alloc")]
18231impl<'s> Executor<'s> {
18232    /// Get a clone of the halt flag for use in signal handlers or other threads.
18233    ///
18234    /// # Example
18235    ///
18236    /// ```ignore
18237    /// let halt = executor.halt_flag();
18238    /// std::thread::spawn(move || {
18239    ///     std::thread::sleep(Duration::from_secs(5));
18240    ///     halt.store(true, Ordering::SeqCst);
18241    /// });
18242    /// executor.spin(SpinOptions::default())?;
18243    /// ```
18244    pub fn halt_flag(&self) -> portable_atomic_util::Arc<portable_atomic::AtomicBool> {
18245        self.halt_flag.clone()
18246    }
18247
18248    /// Clone of the shared wake flag for cross-thread
18249    /// use (signal handlers, foreign threads, future per-backend vtable
18250    /// wake hooks).
18251    ///
18252    /// # Example
18253    ///
18254    /// ```ignore
18255    /// let wake = executor.wake_handle();
18256    /// std::thread::spawn(move || {
18257    ///     // ... compute something ...
18258    ///     // hand off to executor by setting the flag.
18259    ///     wake.store(true, Ordering::SeqCst);
18260    /// });
18261    /// loop { executor.spin_once(Duration::from_millis(100)); }
18262    /// ```
18263    pub fn wake_handle(&self) -> portable_atomic_util::Arc<portable_atomic::AtomicBool> {
18264        self.wake_flag.clone()
18265    }
18266}
18267
18268/// Opaque per-platform timer handle. Stores the
18269/// raw platform handle (a boxed POSIX `timer_t`, FreeRTOS `TimerHandle_t`,
18270/// etc.) plus a destroy thunk so the
18271/// Executor can clean up without being generic over the platform.
18272///
18273/// Caller of `register_sporadic_timer` builds this via
18274/// `OpaqueTimerHandle::new(handle, destroy_fn)` after their
18275/// `PlatformTimer::create_periodic` call returns.
18276#[cfg(feature = "alloc")]
18277pub struct OpaqueTimerHandle {
18278    handle: *mut core::ffi::c_void,
18279    destroy_fn: extern "C" fn(*mut core::ffi::c_void),
18280}
18281
18282#[cfg(feature = "alloc")]
18283unsafe impl Send for OpaqueTimerHandle {}
18284#[cfg(feature = "alloc")]
18285unsafe impl Sync for OpaqueTimerHandle {}
18286
18287#[cfg(feature = "alloc")]
18288impl OpaqueTimerHandle {
18289    /// # Safety
18290    /// `handle` must be a live platform-specific timer handle that
18291    /// `destroy_fn` knows how to drop. Caller surrenders ownership
18292    /// of the underlying handle to the Executor.
18293    pub unsafe fn new(
18294        handle: *mut core::ffi::c_void,
18295        destroy_fn: extern "C" fn(*mut core::ffi::c_void),
18296    ) -> Self {
18297        Self { handle, destroy_fn }
18298    }
18299}
18300
18301#[cfg(feature = "alloc")]
18302impl Drop for OpaqueTimerHandle {
18303    fn drop(&mut self) {
18304        if !self.handle.is_null() {
18305            (self.destroy_fn)(self.handle);
18306            self.handle = core::ptr::null_mut();
18307        }
18308    }
18309}
18310
18311/// Handle returned from [`Executor::open_threaded`]. Holds the
18312/// spawned thread's join handle and a clone of the executor's halt
18313/// flag. Drop runs `halt() + join()` so the thread can't outlive the
18314/// handle.
18315#[cfg(feature = "alloc")]
18316pub struct ThreadHandle {
18317    task: Option<nros_platform_api::task::PlatformTask>,
18318    halt: portable_atomic_util::Arc<portable_atomic::AtomicBool>,
18319}
18320
18321/// Default stack for an `open_threaded` spin loop. `std::thread`'s default was
18322/// 2 MiB; the executor's own storage is caller-carved and lives elsewhere, so
18323/// this carries call frames only — the same reasoning (and size) as the NuttX
18324/// sched task spawn, which measured this against a real RTOS default.
18325#[cfg(feature = "alloc")]
18326const OPEN_THREADED_STACK_BYTES: usize = 65536;
18327
18328/// What [`Executor::open_threaded`] hands its task, in place of a closure's
18329/// captures. Owned by the trampoline, which reclaims it when the loop exits.
18330#[cfg(feature = "alloc")]
18331struct ThreadedCtx {
18332    executor: Executor<'static>,
18333    policy: nros_platform_api::SchedPolicy,
18334    apply_policy: fn(nros_platform_api::SchedPolicy) -> Result<(), nros_platform_api::SchedError>,
18335    spin_period: core::time::Duration,
18336}
18337
18338/// The spawned spin loop.
18339///
18340/// # Safety
18341/// `arg` must be the `Box<ThreadedCtx>` raw pointer `open_threaded` created,
18342/// passed exactly once.
18343#[cfg(feature = "alloc")]
18344unsafe extern "C" fn threaded_spin_trampoline(
18345    arg: *mut core::ffi::c_void,
18346) -> *mut core::ffi::c_void {
18347    // SAFETY: the caller's contract — this is the pointer `open_threaded`
18348    // leaked, and the task is the only consumer of it.
18349    let mut ctx = unsafe { alloc::boxed::Box::from_raw(arg as *mut ThreadedCtx) };
18350    // Apply the requested OS scheduling policy to this fresh task. Failure is
18351    // reported but not propagated — a runtime that fails to lift to SCHED_FIFO
18352    // still spins correctly at SCHED_OTHER (just without RT guarantees).
18353    let _ = (ctx.apply_policy)(ctx.policy);
18354    // phase-417 W4.c — this loop owns its own iteration, so it is a spin and
18355    // must say so. NOT `enter_spin_loop()`: that clears the cancel flag, and
18356    // `open_threaded` hands the caller a `ThreadHandle` whose `halt()` may
18357    // already have fired before this task was scheduled. Raising `is_spinning`
18358    // without touching the cancel bit is the honest report here.
18359    ctx.executor
18360        .spinning
18361        .store(true, core::sync::atomic::Ordering::SeqCst);
18362    while !ctx.executor.is_halted() {
18363        ctx.executor.spin_once(ctx.spin_period);
18364    }
18365    ctx.executor.exit_spin_loop();
18366    core::ptr::null_mut()
18367}
18368
18369#[cfg(feature = "alloc")]
18370impl ThreadHandle {
18371    /// Signal the spawned executor thread to stop. The thread exits
18372    /// on its next `spin_once` iteration.
18373    pub fn halt(&self) {
18374        self.halt.store(true, core::sync::atomic::Ordering::SeqCst);
18375    }
18376
18377    /// Wait for the spawned task to exit. After `join`, calling it again is a
18378    /// no-op.
18379    ///
18380    /// Was `std::thread::Result<()>`, which carried a panic
18381    /// payload this can no longer produce: a platform task has no unwinding
18382    /// join. Same two outcomes, an error type that does not require `std` —
18383    /// the trade `signal_fd` already made in this campaign. `NotInitialized`
18384    /// means the platform refused to host the task at spawn time — nothing was
18385    /// started, so there is nothing to wait for. (An existing variant rather
18386    /// than a new one: `NodeError` is mapped across the C and C++ FFI, so a new
18387    /// variant is a gate-checked ABI change and this needs no new meaning.)
18388    pub fn join(mut self) -> Result<(), NodeError> {
18389        self.halt();
18390        match self.task.take() {
18391            Some(t) => {
18392                t.join();
18393                Ok(())
18394            }
18395            None => Err(NodeError::NotInitialized),
18396        }
18397    }
18398}
18399
18400#[cfg(feature = "alloc")]
18401impl Drop for ThreadHandle {
18402    fn drop(&mut self) {
18403        self.halt.store(true, core::sync::atomic::Ordering::SeqCst);
18404        if let Some(t) = self.task.take() {
18405            t.join();
18406        }
18407    }
18408}
18409
18410// SAFETY: Phase 110.D.b — `Executor` contains a raw `*mut
18411// session::ConcreteSession` only on the `from_session_ptr` (Borrowed)
18412// path; the `from_session` (Owned) path is plain Send-able. The
18413// `unsafe fn open_threaded` entry point documents the safety
18414// contract for Borrowed sessions; for Owned sessions the Send claim
18415// is unconditional.
18416// phase-359 W10 — `alloc`, not `std`: this assertion exists for
18417// `open_threaded`, which now hands the executor to a PLATFORM task. The
18418// crossing is the same one; only the thing doing the crossing changed.
18419#[cfg(feature = "alloc")]
18420unsafe impl<'s> Send for Executor<'s> {}
18421
18422/// phase-509 P9b item 2 -- take the bits of `mask` out of the ready words and
18423/// leave the rest for the workers of the other bands. One swap per word for
18424/// the one-level worker's every-slot mask, as before.
18425#[cfg(any(has_rmw, test))]
18426#[allow(dead_code)] // no ready word without `alloc` + `rmw-cffi`
18427#[inline]
18428fn take_band_bits(
18429    words: &super::slot_mask::AtomicSlotMask,
18430    mask: super::slot_mask::SlotMask,
18431) -> super::slot_mask::SlotMask {
18432    if mask == super::slot_mask::SlotMask::ALL {
18433        words.take()
18434    } else {
18435        words.take_masked(mask)
18436    }
18437}
18438
18439/// phase-509 P9b item 2 (RFC-0108 "As built in P9b") -- how a pass runs.
18440#[cfg(any(has_rmw, test))]
18441pub(crate) enum PassMode<'w> {
18442    /// `spin_once(&mut self)`: the executor's own worker; the lock, if one
18443    /// is installed, is held for the whole pass.
18444    Owned,
18445    /// The executor's own worker through a raw pointer
18446    /// ([`Executor::spin_once_shared`]): the lock is released around each
18447    /// user callback when it carries a thread identity.
18448    Shared,
18449    /// A band worker's pass ([`Executor::spin_band_once`]).
18450    Band(&'w mut super::scheduler::BandWorker),
18451}
18452
18453impl<'s> Drop for Executor<'s> {
18454    fn drop(&mut self) {
18455        // Issue 0790 — a teardown that never went through `close()` still gets
18456        // its ordered shutdown hooks, and gets them in the SAME order. The C
18457        // API's `rclc_executor_fini` is exactly that path: it drops the
18458        // executor in place and leaves the session to `rclc_support_fini`, so
18459        // without this the whole facility would be silently inert for every C
18460        // entry. Entities are still live at the top of `drop` — the component
18461        // cells and the arena entries below are what tears them down — so this
18462        // is the last moment a pre-shutdown hook can do what it exists to do.
18463        //
18464        // After a normal `close()` both tables are already empty and these two
18465        // calls are a pair of `None` scans.
18466        self.run_shutdown_hooks(super::types::ShutdownPhase::Pre);
18467        // Phase 258 (Track 2, 2a) — release executor-owned component cells
18468        // first (before the arena entries), so a component's `drop`
18469        // trampoline can still touch its own (cell-owned) state. Each slot
18470        // owns a leaked `Arc<ComponentCell>`; its `drop` reconstitutes +
18471        // drops that Arc exactly once.
18472        for slot in self.component_slots.iter() {
18473            // SAFETY: `slot.state` is the leaked cell enrolled via
18474            // `enroll_component`; `slot.drop` is its matching trampoline, run
18475            // exactly once here (slots are not removed before Drop).
18476            unsafe {
18477                (slot.drop)(slot.state);
18478            }
18479        }
18480        let arena_ptr = self.arena.as_mut_ptr() as *mut u8;
18481        for meta in self.entries.iter().flatten() {
18482            // SAFETY: each entry was written by `ptr::write` in `add_*` and
18483            // has not been dropped yet. `drop_fn` matches the concrete type.
18484            unsafe {
18485                let data_ptr = arena_ptr.add(meta.offset);
18486                (meta.drop_fn)(data_ptr);
18487            }
18488        }
18489        // phase-556 W13 -- the runtime's `/rosout` writers are entities too:
18490        // dropped here, with the others, not when the node table drops after
18491        // the session field. A no-op after `close()`.
18492        #[cfg(feature = "rosout")]
18493        self.release_rosout();
18494        // Issue 0790 — the post-teardown half, after the entities are gone.
18495        // Same "already empty after `close()`" note as the pre pass above.
18496        self.run_shutdown_hooks(super::types::ShutdownPhase::Post);
18497        // Issue 1385 — LAST in the body, and that is the whole point: the
18498        // context the backend holds is `wake_ctx`, a field, so it is still
18499        // alive for every line above and is freed only after `drop` returns.
18500        // Clearing here is therefore the SHORTEST window in which a callback
18501        // can fire into live state, not the longest — entity teardown above
18502        // may still be talking to the backend.
18503        //
18504        // A no-op after `close()` (the latch), and a no-op for an executor
18505        // that never installed. For the C path this is the only clear there
18506        // is: `rclc_executor_fini` runs this `drop_in_place` and THEN
18507        // zero-fills the storage the callback pointed into.
18508        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
18509        self.clear_wake_signal();
18510        // phase-467 Row 8 — and the graph-change target, before the box it
18511        // names is freed with this executor.
18512        #[cfg(all(feature = "alloc", feature = "rmw-cffi"))]
18513        self.clear_graph_change_signal();
18514    }
18515}
18516
18517/// Phase 274.W1 — borrowed-executor session sharing + active-groups gating.
18518///
18519/// Validates three primitives introduced for RFC-0015 Model 1:
18520/// - `session_handle` / `open_with_session_handle` (Borrowed session store —
18521///   the borrowed executor does not own or close the session on drop).
18522/// - `set_active_groups` + `group_active` (callback-group filter gating).
18523///
18524/// Uses `MockSession`; gated `not(feature = "rmw-cffi")` because the mock
18525/// session exists only there.
18526#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
18527mod p274_w1_sched_task_executor_tests {
18528    use super::Executor;
18529    use crate::mock::MockSession;
18530
18531    /// Phase-573 W3 -- a borrowed executor keeps working over the session
18532    /// pointer after its owner has spun and written the session through its
18533    /// own field: the pointer `session_ptr` hands out must stay valid, not be
18534    /// a child of a temporary reborrow the owner's next write disables.
18535    #[test]
18536    fn a_session_pointer_survives_its_owner_spinning() {
18537        let mut primary = alloc::boxed::Box::new(Executor::from_session(MockSession::new()));
18538        let handle = primary.session_handle().expect("a heap session is shared");
18539        // SAFETY: `primary` outlives `borrowed` and is not moved (boxed).
18540        let mut borrowed = unsafe { Executor::open_with_session_handle(handle) };
18541        for _ in 0..2 {
18542            let _ = primary.spin_once(core::time::Duration::ZERO);
18543            let _ = borrowed.spin_once(core::time::Duration::ZERO);
18544        }
18545        drop(borrowed);
18546    }
18547
18548    /// Phase-573 W3 -- when the owned session's own allocation fails, it is
18549    /// held inline, and an inline session is never shared: the handle is
18550    /// refused rather than handed out as a pointer the owner's next write
18551    /// would disable.
18552    #[test]
18553    fn an_inline_session_is_never_shared() {
18554        let mut primary = alloc::boxed::Box::new(Executor::from_session(MockSession::new()));
18555        assert!(
18556            primary.session_handle().is_some(),
18557            "a heap session is shared"
18558        );
18559        primary.session = super::SessionStore::owned_via(MockSession::new(), Err);
18560        assert!(
18561            primary.session_handle().is_none(),
18562            "an inline session is refused"
18563        );
18564        assert!(primary.session_ptr().is_none());
18565        // The owner itself still works over its inline session.
18566        let _ = primary.spin_once(core::time::Duration::ZERO);
18567    }
18568
18569    #[test]
18570    fn session_handle_borrowed_executor_shares_session_ptr() {
18571        // Open the primary executor (session owner).
18572        let session = MockSession::new();
18573        let mut primary = Executor::from_session(session);
18574
18575        // Record the primary's session pointer for later comparison.
18576        let primary_session_ptr = primary.session_ptr().expect("shared");
18577
18578        // Get the opaque session handle (into_raw for C FFI; here we keep it raw).
18579        let handle = primary.session_handle().expect("a heap session is shared");
18580
18581        // Open a second executor over the SAME session (Borrowed — does not own it).
18582        // SAFETY: `primary` (the session owner) outlives `borrowed` in this scope.
18583        let mut borrowed = unsafe { Executor::open_with_session_handle(handle) };
18584
18585        // Both executors must expose the same session pointer.
18586        assert_eq!(
18587            primary.session_ptr().expect("shared"),
18588            borrowed.session_ptr().expect("shared"),
18589            "borrowed executor must share the primary's session pointer"
18590        );
18591        assert_eq!(
18592            borrowed.session_ptr().expect("shared"),
18593            primary_session_ptr,
18594            "session pointer must be stable across session_handle / open_with_session_handle"
18595        );
18596
18597        // Drop the borrowed executor — the primary's session must remain valid.
18598        drop(borrowed);
18599
18600        // Primary still exposes the same session pointer (session was NOT closed by drop).
18601        assert_eq!(
18602            primary.session_ptr().expect("shared"),
18603            primary_session_ptr,
18604            "primary session pointer must be unchanged after dropping the borrowed executor"
18605        );
18606    }
18607
18608    /// An oversized group name is REFUSED and fails CLOSED.
18609    ///
18610    /// issue 1172 — this used to be `if s.push_str(g).is_ok()`, which dropped
18611    /// the name and left the sched task filtering on a set that silently lacked it.
18612    /// Two things are asserted because either alone would let the bug back:
18613    /// the call must REPORT the failure, and the resulting filter must accept
18614    /// NOTHING rather than fall back to the wildcard, which would be
18615    /// fail-open.
18616    #[test]
18617    fn an_oversized_group_name_is_refused_and_fails_closed() {
18618        let session = MockSession::new();
18619        let mut primary = Executor::from_session(session);
18620        let handle = primary.session_handle().expect("a heap session is shared");
18621        // SAFETY: primary outlives borrowed.
18622        let mut borrowed = unsafe { Executor::open_with_session_handle(handle) };
18623
18624        // `GroupName` is `heapless::String<32>`.
18625        let too_long = "g".repeat(33);
18626        assert!(
18627            borrowed
18628                .set_active_groups(&[("n", "/", too_long.as_str())])
18629                .is_err(),
18630            "an oversized group name must be reported, not dropped"
18631        );
18632        assert!(
18633            !borrowed.group_active("n", "/", &too_long),
18634            "the name that did not fit must not be active"
18635        );
18636        assert!(
18637            !borrowed.group_active("n", "/", "anything-else"),
18638            "a refused filter must accept NOTHING — falling back to the \
18639             wildcard would run every callback on this sched task"
18640        );
18641    }
18642
18643    #[test]
18644    fn set_active_groups_gates_group_active() {
18645        let session = MockSession::new();
18646        let mut primary = Executor::from_session(session);
18647        let handle = primary.session_handle().expect("a heap session is shared");
18648
18649        // SAFETY: primary outlives borrowed.
18650        let mut borrowed = unsafe { Executor::open_with_session_handle(handle) };
18651
18652        // Before gating: wildcard — every group is accepted.
18653        assert!(
18654            borrowed.group_active("n", "/", "ctrl"),
18655            "default (wildcard) must accept every group"
18656        );
18657        assert!(
18658            borrowed.group_active("n", "/", "telem"),
18659            "default (wildcard) must accept every group"
18660        );
18661
18662        // Gate borrowed to only the "ctrl" group (one-sched-task filter).
18663        borrowed
18664            .set_active_groups(&[("n", "/", "ctrl")])
18665            .expect("fits");
18666
18667        assert!(
18668            borrowed.group_active("n", "/", "ctrl"),
18669            "\"ctrl\" must be active after set_active_groups([\"ctrl\"])"
18670        );
18671        assert!(
18672            !borrowed.group_active("n", "/", "telem"),
18673            "\"telem\" must NOT be active when only \"ctrl\" is gated"
18674        );
18675        assert!(
18676            !borrowed.group_active("n", "/", "planning"),
18677            "\"planning\" must NOT be active when only \"ctrl\" is gated"
18678        );
18679
18680        // Primary is unaffected (it still uses the wildcard).
18681        assert!(
18682            primary.group_active("n", "/", "telem"),
18683            "primary executor must remain unaffected (still wildcard)"
18684        );
18685
18686        // Clear the filter on borrowed — back to wildcard.
18687        borrowed
18688            .set_active_groups(&[])
18689            .expect("the wildcard always fits");
18690        assert!(
18691            borrowed.group_active("n", "/", "telem"),
18692            "after clearing, borrowed must accept all groups again"
18693        );
18694    }
18695
18696    #[test]
18697    fn session_handle_into_raw_from_raw_round_trip() {
18698        let session = MockSession::new();
18699        let mut primary = Executor::from_session(session);
18700        let session_ptr = primary.session_ptr().expect("shared");
18701
18702        let handle = primary.session_handle().expect("a heap session is shared");
18703        let raw = handle.into_raw();
18704
18705        // into_raw must return a non-null pointer matching the session address.
18706        assert!(!raw.is_null());
18707        assert_eq!(raw as *mut _, session_ptr);
18708
18709        // from_raw must reconstruct a handle that opens the same borrowed executor.
18710        // SAFETY: primary still owns the session, raw is its address.
18711        let handle2 = unsafe { crate::executor::SessionHandle::from_raw(raw) };
18712        let mut borrowed = unsafe { Executor::open_with_session_handle(handle2) };
18713        assert_eq!(
18714            borrowed.session_ptr().expect("shared"),
18715            session_ptr,
18716            "from_raw reconstructed handle must open executor on the same session"
18717        );
18718    }
18719}
18720
18721/// W3b.5 — snapshot the monitored publishers' counters before a dispatch
18722/// (only when a latency contract exists; otherwise a zeroed array that
18723/// `attribute_latency` never reads).
18724fn snapshot_pub_counts(
18725    table: &'static [super::monitor::MonitorSpec],
18726    active: bool,
18727) -> [u32; super::monitor::MAX_MONITORS] {
18728    let mut counts = [0u32; super::monitor::MAX_MONITORS];
18729    if active {
18730        for (k, spec) in table.iter().take(super::monitor::MAX_MONITORS).enumerate() {
18731            counts[k] = spec.cell.count.load(core::sync::atomic::Ordering::Relaxed);
18732        }
18733    }
18734    counts
18735}
18736
18737/// W3b.5 — attribute one dispatch's elapsed time to every monitored
18738/// publisher whose counter advanced during it (an upper bound on the
18739/// node-path take → publish latency: the callback deserialized, ran, and
18740/// published within `elapsed_us`).
18741fn attribute_latency(
18742    table: &'static [super::monitor::MonitorSpec],
18743    active: bool,
18744    counts_before: &[u32; super::monitor::MAX_MONITORS],
18745    elapsed_us: u32,
18746) {
18747    if !active {
18748        return;
18749    }
18750    for (k, spec) in table.iter().take(super::monitor::MAX_MONITORS).enumerate() {
18751        if spec.max_latency_ms == 0 {
18752            continue;
18753        }
18754        let now = spec.cell.count.load(core::sync::atomic::Ordering::Relaxed);
18755        if now != counts_before[k] {
18756            spec.cell
18757                .max_latency_us
18758                .fetch_max(elapsed_us, core::sync::atomic::Ordering::Relaxed);
18759        }
18760    }
18761}
18762
18763/// W3b.5 — enforce the bound SC's deadline after a dispatch. A miss maps
18764/// through [`DeadlineAction`](super::sched_context::DeadlineAction):
18765/// `Warn`/`Skip`/`Fault` all report; `Skip` additionally masks the SC's
18766/// remaining callbacks for this cycle; `Fault` invokes the fault hook
18767/// (panic when none is registered).
18768/// phase-503 -- hand a route deadline verdict of `table[row]` to the reaction
18769/// hook, if one is installed (and the monitors are armed: the caller passes
18770/// `None` otherwise). Shared by the overdue check after the park and the
18771/// completion verdict of a late supervised route (`route_judge`).
18772fn call_route_reaction(
18773    hook: Option<(super::monitor::ReactionHookFn, *mut core::ffi::c_void)>,
18774    table: &[super::monitor::MonitorSpec],
18775    row: usize,
18776    v: &super::monitor::Violation,
18777    fired_at_us: u64,
18778) {
18779    let Some((f, ctx)) = hook else { return };
18780    let spec = &table[row];
18781    let ev = super::monitor::ReactionEvent {
18782        reaction_id: spec.reaction_id as u32,
18783        row: row as u32,
18784        rule_code: super::monitor::rule_code(v.rule),
18785        measured_ms: v.measured,
18786        declared_ms: v.declared,
18787        mechanism: spec.mechanism,
18788        fired_at_us,
18789    };
18790    // SAFETY: `f` and `ctx` were registered together through
18791    // `set_reaction_hook`, whose caller keeps `ctx` valid for the executor's
18792    // life; the event lives across the call.
18793    unsafe { f(&ev, ctx) };
18794}
18795
18796/// phase-462 W3c -- [`call_route_reaction`] for a detected hazard: the event
18797/// names the hazard's reaction id and its index in the hazard table.
18798fn call_hazard_reaction(
18799    hook: Option<(super::monitor::ReactionHookFn, *mut core::ffi::c_void)>,
18800    spec: &super::monitor::HazardSpec,
18801    row: usize,
18802    v: &super::monitor::Violation,
18803    fired_at_us: u64,
18804) {
18805    let Some((f, ctx)) = hook else { return };
18806    let ev = super::monitor::ReactionEvent {
18807        reaction_id: spec.reaction_id as u32,
18808        row: row as u32,
18809        rule_code: super::monitor::rule_code(v.rule),
18810        measured_ms: v.measured,
18811        declared_ms: v.declared,
18812        mechanism: super::monitor::MECHANISM_EXECUTOR,
18813        fired_at_us,
18814    };
18815    // SAFETY: as `call_route_reaction` -- `f` and `ctx` were registered
18816    // together through `set_reaction_hook`.
18817    unsafe { f(&ev, ctx) };
18818}
18819
18820// The deadline, the SC slot, the miss sinks and both fault paths, plus the
18821// fire time the reaction hook reports (play_launch phase 96 W4.2).
18822#[allow(clippy::too_many_arguments)]
18823fn check_deadline_miss(
18824    sc: Option<&super::sched_context::SchedContext>,
18825    sc_idx: usize,
18826    elapsed_us: u32,
18827    misses: &mut heapless::Vec<super::monitor::Violation, { super::monitor::MAX_VIOLATIONS }>,
18828    skipped_scs: &mut u64,
18829    fault_fn: Option<fn(&super::monitor::Violation)>,
18830    reaction_hook: Option<(super::monitor::ReactionHookFn, *mut core::ffi::c_void)>,
18831    fired_at_us: u64,
18832) {
18833    use super::sched_context::DeadlineAction;
18834    let Some(sc) = sc else { return };
18835    let Some(deadline_us) = sc.deadline_us.get().map(|nz| nz.get()) else {
18836        return;
18837    };
18838    if matches!(sc.deadline_action, DeadlineAction::Ignore) || elapsed_us <= deadline_us {
18839        return;
18840    }
18841    let v = super::monitor::Violation {
18842        rule: "deadline-miss-runtime",
18843        // Entries carry no name at this altitude; the SC slot stands in.
18844        fqn: "sched-context",
18845        measured: elapsed_us,
18846        declared: deadline_us,
18847        level: "",
18848    };
18849    match sc.deadline_action {
18850        DeadlineAction::Ignore => {}
18851        DeadlineAction::Warn => {
18852            let _ = misses.push(v);
18853        }
18854        DeadlineAction::Skip => {
18855            if sc_idx < 64 {
18856                *skipped_scs |= 1u64 << sc_idx;
18857            }
18858            let _ = misses.push(v);
18859        }
18860        DeadlineAction::Fault => {
18861            if let Some(f) = fault_fn {
18862                f(&v);
18863                let _ = misses.push(v);
18864            } else if let Some((f, ctx)) = reaction_hook {
18865                // phase-503 — the reaction hook is the fault path a C or C++
18866                // image can install; reaction id 0, the SC slot as the row.
18867                let ev = super::monitor::ReactionEvent {
18868                    reaction_id: super::monitor::REACTION_NONE as u32,
18869                    row: sc_idx as u32,
18870                    rule_code: super::monitor::rule_code(v.rule),
18871                    measured_ms: elapsed_us / 1_000,
18872                    declared_ms: deadline_us / 1_000,
18873                    mechanism: super::monitor::MECHANISM_EXECUTOR,
18874                    fired_at_us,
18875                };
18876                // SAFETY: as in `check_route_deadlines`.
18877                unsafe { f(&ev, ctx) };
18878                let _ = misses.push(v);
18879            } else {
18880                panic!(
18881                    "nros: deadline fault — dispatch ran {elapsed_us} us past a {deadline_us} us deadline"
18882                );
18883            }
18884        }
18885    }
18886}
18887
18888// Timer-accounting clock default (issue: no_std sched tasks with no `clock_us`
18889// credited each spin the REQUESTED timeout — spin.rs `delta_us` fallback —
18890// so shared-session wakes made low-rate timers fire early (a 100 ms timer
18891// at ~67 ms on Zephyr native_sim) and tick rounding made fast tiers fire
18892// late. Measured on that native_sim image; mechanism documented at the
18893// fallback site.)
18894//
18895// Every platform port exports `nros_platform_clock_ns` through the same
18896// linkage contract the wake primitives rely on (`nros_platform_export_clock!`
18897// in nros-platform-cffi), so an rmw-cffi no_std build can safely default the
18898// executor clock to it; `ExecutorConfig::clock_us` stays as an override.
18899#[cfg(feature = "rmw-cffi")]
18900unsafe extern "C" {
18901    fn nros_platform_clock_ns() -> u64;
18902}
18903
18904#[cfg(feature = "rmw-cffi")]
18905fn default_platform_clock_us() -> u64 {
18906    // SAFETY: bare query of the platform's monotonic ns counter; the symbol
18907    // is guaranteed by whichever platform port linked the binary (the same
18908    // contract `nros_platform_wake_*` already depends on).
18909    //
18910    // RFC-0073 made the ABI nanoseconds; the executor's own accounting is
18911    // still microseconds (`clock_us_fn`, `delta_us`), so the division lives
18912    // here rather than being pushed into every port.
18913    unsafe { nros_platform_clock_ns() / 1_000 }
18914}
18915
18916/// Sleep, through the platform ABI.
18917///
18918/// phase-359 W10 — the spin loops used `std::thread::sleep`. Every port already
18919/// exports `nros_platform_sleep_us` (the ABI's own pacing primitive, the one an
18920/// RTOS build has always used), so a hosted loop and an embedded one now pace
18921/// the same way. The µs entry point is used rather than `_ms` because
18922/// `spin_one_period_timed` sleeps off a remainder, which rounds badly at
18923/// millisecond granularity on short periods.
18924#[cfg(feature = "alloc")]
18925pub(crate) fn platform_sleep(d: core::time::Duration) {
18926    unsafe extern "C" {
18927        fn nros_platform_sleep_us(us: usize);
18928    }
18929    let us = d.as_micros().min(usize::MAX as u128) as usize;
18930    if us == 0 {
18931        return;
18932    }
18933    // SAFETY: a bare pacing call with no pointer arguments, guaranteed by
18934    // whichever port linked the binary — the same contract the clock and wake
18935    // symbols in this file already rely on.
18936    unsafe { nros_platform_sleep_us(us) }
18937}
18938
18939/// A monotonic µs reader, or `None` when this build has no clock at all.
18940///
18941/// phase-359 W10 — one provider, chosen by what is LINKED rather than by which
18942/// flavour the crate was built in. W4 unified the executor's clock ACCESSOR and
18943/// said the provider was the last piece; this is it.
18944///
18945/// `rmw-cffi` means a platform port is linked, and every port exports
18946/// `nros_platform_clock_ns` under the same contract the wake primitives use —
18947/// so a hosted build reads the same counter an embedded one does, instead of
18948/// `Instant` on one and the platform on the other. `Instant` survives only
18949/// where there is no port to ask: `std` without `rmw-cffi`.
18950///
18951/// phase-359 W10 follow-up — this comment claimed the metadata PROBE was that
18952/// configuration, and **it is not**. The probe's generated manifest deps
18953/// `nros-platform-cffi` with `posix-c-port` (issue 0288 layer 5, so it links),
18954/// and its `nros` resolves with `rmw-cffi` ON — feature-unified from the
18955/// component's board crate. Measured on a real probe tree: `alloc default
18956/// macros rmw-cffi ros-humble std`. It takes the PORT arm.
18957///
18958/// What is real: `nros-rmw-metadata` and `nros-tests` do resolve `nros` with
18959/// `std` and no `rmw-cffi`, and have no port crate in their graphs. But nothing
18960/// in either uses this arm — deleting it and building the workspace
18961/// `--all-targets` is clean, and there is no in-tree caller of
18962/// `nros::time::now` at all. So the arm serves an OUT-OF-TREE contract only: a
18963/// consumer with `std`, no `rmw-cffi`, and its own `Session`.
18964pub(crate) fn default_clock_us_fn() -> Option<fn() -> u64> {
18965    #[cfg(feature = "rmw-cffi")]
18966    {
18967        Some(default_platform_clock_us)
18968    }
18969    #[cfg(not(feature = "rmw-cffi"))]
18970    {
18971        None
18972    }
18973}
18974
18975// =============================================================================
18976// phase-425 W3b — the `/clock` time source's executor half.
18977//
18978// Its OWN impl block, gated on `sim-time`, because the methods were first
18979// written next to `declare_parameter` — which lives in a
18980// `#[cfg(feature = "param-store")]` block, so `reconcile_ros_time_source`
18981// silently disappeared in every combo without parameter services, including the
18982// one `spin_once` calls it from.
18983// =============================================================================
18984#[cfg(all(feature = "sim-time", any(has_rmw, test)))]
18985impl<'s> Executor<'s> {
18986    /// phase-425 W3b — bring the `/clock` subscription in line with the last
18987    /// requested `use_sim_time`.
18988    ///
18989    /// Called at the head of every spin, and cheap when there is nothing to do:
18990    /// the common case is one bool comparison. It is a RECONCILE rather than an
18991    /// action at the request site because the request routinely arrives before
18992    /// there is a node to hang the subscription on — `nros::main!` emits
18993    /// `apply_param_services` before its per-node `register` calls, by design,
18994    /// so the store exists when each cell is created.
18995    ///
18996    /// Turning it off stops SAMPLES from being installed; the subscription
18997    /// itself stays, because the executor has no entity removal and inventing
18998    /// one for this would be a much larger change than the switch is worth. The
18999    /// gate is `time_source::set_active`, which the subscription callback reads.
19000    ///
19001    /// Turning it off also does NOT clear the override: a node that stops
19002    /// listening keeps the last simulated time rather than jumping back to the
19003    /// wall clock, which every ROS-time timer would otherwise absorb as a
19004    /// backwards jump.
19005    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19006    pub(crate) fn reconcile_ros_time_source(&mut self) {
19007        // An executor nobody told about `use_sim_time` has NO opinion, and the
19008        // gate is process-global, so writing its default here is not a no-op --
19009        // it is one executor overruling another. Say nothing until asked.
19010        if !self.sim_time_stated {
19011            return;
19012        }
19013        if self.sim_time_requested == crate::time_source::is_active()
19014            && (!self.sim_time_requested || self.sim_time_source.is_some())
19015        {
19016            return;
19017        }
19018        crate::time_source::set_active(self.sim_time_requested);
19019        if !self.sim_time_requested {
19020            // phase-430 W1 — the source is no longer wanted, so its silence is
19021            // no longer a symptom. Disarming here (rather than only re-arming
19022            // on attach) is what makes a later re-attach start a FRESH
19023            // interval: the watch that was counting is put down, not paused.
19024            self.sim_time_silence.disarm();
19025            return;
19026        }
19027        if self.sim_time_source.is_none() {
19028            // No node yet — stay pending and try again next spin. Not an error:
19029            // it is the ordinary order of a generated entry, which declares
19030            // parameters before it registers components.
19031            if self.nodes.is_empty() {
19032                return;
19033            }
19034            if let Ok(handle) = self.install_ros_time_source(
19035                super::node_record::NodeId::PRIMARY,
19036                crate::time_source::CLOCK_TOPIC,
19037            ) {
19038                self.sim_time_source = Some(handle);
19039                // phase-430 W1 — the interval starts HERE, at attach, and not
19040                // at construction: before the subscription exists there is
19041                // nothing to be silent about, so counting from boot would
19042                // accuse an image that spent the interval bringing a transport
19043                // up.
19044                self.sim_time_silence.arm();
19045            }
19046        } else {
19047            // Re-attached: `use_sim_time` went false and back to true while the
19048            // subscription (which the executor cannot remove) stayed. W1 asks
19049            // for the one-shot to reset in exactly this case.
19050            self.sim_time_silence.arm();
19051        }
19052    }
19053
19054    /// phase-430 W1 — credit one spin's elapsed time to the silence watch and
19055    /// emit the diagnostic if this is the spin that crosses the threshold.
19056    ///
19057    /// `delta_us` is the executor's OWN per-spin elapsed measure — the same one
19058    /// every wall timer on this executor accumulates, including its "no clock,
19059    /// credit the requested timeout" fallback. See
19060    /// [`SILENCE_WARN_US`](crate::time_source::SILENCE_WARN_US) for why that is
19061    /// the unit and not a spin count or an independent wall clock.
19062    ///
19063    /// Scope: the source the EXECUTOR installed for `use_sim_time`. An
19064    /// application that calls
19065    /// [`Node::install_ros_time_source`](super::node::Node::install_ros_time_source)
19066    /// directly is not watched, because the line this would print names
19067    /// `use_sim_time`, and that application never set it — the honest
19068    /// diagnostic for the explicit path would be a different sentence, and
19069    /// inventing one nobody asked for is how a warning becomes noise.
19070    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19071    fn note_sim_time_silence(&mut self, delta_us: u64) {
19072        if self.sim_time_silence.tick(
19073            delta_us,
19074            nros_core::clock::Clock::is_ros_time_override_active(),
19075        ) {
19076            crate::time_source::report_silence(crate::time_source::CLOCK_TOPIC);
19077        }
19078    }
19079
19080    /// How many times this executor has reported that
19081    /// `use_sim_time` is on with no `/clock` sample.
19082    ///
19083    /// The count rather than a bool, and an accessor rather than a log grep: a
19084    /// diagnostic whose contract is "exactly once" needs an assertion that can
19085    /// tell one from two, and a log sink is not present on every target that
19086    /// runs the test. It is also the question an application supervising its
19087    /// own configuration would ask.
19088    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19089    pub fn sim_time_silence_warnings(&self) -> u32 {
19090        self.sim_time_silence.reports()
19091    }
19092
19093    /// phase-425 W3b — re-read `use_sim_time` from the parameter store.
19094    ///
19095    /// Called after a parameter service actually handled something, which is
19096    /// what makes a runtime `ros2 param set <node> use_sim_time true` work
19097    /// without a per-spin scan of the store.
19098    ///
19099    /// phase-430 W3 / issue 1202 — the declaration path calls it too, through
19100    /// `note_reserved_parameter`, once the store has accepted the write. It
19101    /// used to record the value directly from the caller's argument, which is
19102    /// the same thing only while the store never refuses. One read for both
19103    /// paths; a second spelling is the drift this function exists to prevent.
19104    /// `pub(crate)` for the same reason: a test that changes the store directly
19105    /// needs the entry point a parameter service uses, not a copy of it.
19106    #[cfg(all(feature = "sim-time", feature = "param-store", any(has_rmw, test)))]
19107    pub(crate) fn refresh_use_sim_time_from_store(&mut self) {
19108        // phase-426 W1 — the store is keyed by NODE, and the simulated clock is
19109        // not. This function is where those two facts meet, so the rule is
19110        // stated here rather than left to whichever call site got there first.
19111        //
19112        // `use_sim_time` is a per-node parameter in ROS 2, and rclcpp means it:
19113        // every `Node` builds its own `TimeSource` over its own `Clock`, so two
19114        // nodes composed into one process CAN be configured differently and
19115        // stamp messages from different clocks at the same instant. This tree
19116        // deliberately does not follow that (phase-425): "the override is
19117        // process-global — one simulated clock per image, the model
19118        // `nros_core::Clock` already documents — so there is nothing to attach
19119        // to and nothing to fan out." That is the right trade for an image with
19120        // a fixed RAM budget, and it makes "whose `use_sim_time`?" a question
19121        // rclcpp never has to answer and this executor now does.
19122        //
19123        // ANY node asking arms the one source. Two reasons, and the second is
19124        // the binding one:
19125        //
19126        //   * it is the only rule the CALLERS can implement. `note_param_
19127        //     services_ran` fires after a runtime `ros2 param set` and knows
19128        //     only that N requests were handled — not which node was written.
19129        //     A last-writer-wins rule would need a writer identity that does
19130        //     not reach here, so it would silently degrade to "whatever node 0
19131        //     says", which is the default-to-primary bug phase-426 W1 exists to
19132        //     remove.
19133        //   * one node still wanting simulated time is a reason to keep the
19134        //     source attached, and detaching is the destructive direction:
19135        //     phase-425 already records that turning it off "stops SAMPLES, not
19136        //     the subscription", precisely so a mid-run change does not read as
19137        //     a clock jump.
19138        //
19139        // The scan is over the executor's own node table, which is the same
19140        // `u8` index space `NodeKey` wraps, so there is one node identity here
19141        // and not two.
19142        let Some(params) = self.params.as_deref() else {
19143            return;
19144        };
19145        let mut stated = false;
19146        let mut enable = false;
19147        // A `NodeId` IS the index into this table (`NodeId::index`), so the
19148        // enumeration is the key space — no second derivation of the number.
19149        //
19150        // `.max(1)` because `NodeId::PRIMARY` is IMPLICIT: the executor's node
19151        // table starts empty and a parameter can be declared on the primary
19152        // node before any `create_node` puts a record in it. Scanning only the
19153        // table would then find nothing and leave `sim_time_stated` false, so a
19154        // `use_sim_time` declared before the first node would never arm the
19155        // source — which `use_sim_time_attaches_and_detaches_the_clock_source`
19156        // catches, since its whole first half runs while "there is still no
19157        // node". Slot 0 is always a legitimate key; at worst the lookup misses.
19158        for idx in 0..self.nodes.len().max(1) {
19159            let key = nros_params::NodeKey::new(idx as u8);
19160            if let Some(v) = params
19161                .server
19162                .get_bool(key, crate::time_source::USE_SIM_TIME_PARAM)
19163            {
19164                stated = true;
19165                enable |= v;
19166            }
19167        }
19168        if stated {
19169            self.sim_time_requested = enable;
19170            self.sim_time_stated = true;
19171        }
19172    }
19173
19174    /// The installed `/clock` subscription, if any.
19175    ///
19176    /// The HANDLE rather than a bool, because "did we subscribe twice" is the
19177    /// question a reconciliation loop has to be able to answer: a second
19178    /// registration takes a new slot, so a stable handle across spins is the
19179    /// evidence that the loop is idempotent.
19180    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19181    pub fn ros_time_source_handle(&self) -> Option<HandleId> {
19182        self.sim_time_source
19183    }
19184
19185    /// Whether a `/clock` subscription is currently installed.
19186    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19187    pub fn ros_time_source_installed(&self) -> bool {
19188        self.sim_time_source.is_some()
19189    }
19190
19191    /// phase-425 W3 — subscribe `topic` and install every sample as this
19192    /// image's ROS time. The registration behind
19193    /// [`Node::install_ros_time_source`](super::node::Node::install_ros_time_source)
19194    /// and behind the `use_sim_time` reconciliation, so both spell the QoS and
19195    /// the conversion exactly once.
19196    #[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19197    pub(crate) fn install_ros_time_source(
19198        &mut self,
19199        node_id: super::node_record::NodeId,
19200        topic: &str,
19201    ) -> Result<HandleId, NodeError> {
19202        let handle = create_clock_sub(self, node_id, topic)?;
19203        Ok(handle)
19204    }
19205}
19206
19207/// phase-556 W11 -- create the executor's `/clock` subscription:
19208/// `rosgraph_msgs/msg/Clock` on `topic`, with [`QoSProfile::clock_default`],
19209/// installing each sample as the image's ROS time while `use_sim_time` holds.
19210///
19211/// The ONE creation site `check-infra-queryable-counts` holds
19212/// [`CLOCK_SUBSCRIPTIONS`](crate::time_source::CLOCK_SUBSCRIPTIONS) to, once
19213/// per executor: the `use_sim_time` reconciliation creates it at most once
19214/// (`sim_time_source`), and the sizing reserves that one whenever the image
19215/// carries the `sim_time` capability.
19216#[cfg(all(feature = "sim-time", any(has_rmw, test)))]
19217fn create_clock_sub(
19218    exec: &mut Executor<'_>,
19219    node_id: super::node_record::NodeId,
19220    topic: &str,
19221) -> Result<HandleId, NodeError> {
19222    exec.register_subscription_buffered_on::<
19223            nros_rosgraph_msgs::msg::Clock,
19224            _,
19225            { crate::config::DEFAULT_RX_BUF_SIZE },
19226        >(
19227            node_id,
19228            topic,
19229            QoSProfile::clock_default(),
19230            |msg: &nros_rosgraph_msgs::msg::Clock| {
19231                // The `use_sim_time` gate is read HERE rather than by removing
19232                // the subscription, because there is no entity removal. An
19233                // image that never touches `use_sim_time` and installs the
19234                // source explicitly is active by default.
19235                if !crate::time_source::is_active() {
19236                    return;
19237                }
19238                if let Some(nanos) =
19239                    crate::time_source::override_nanos(msg.clock.sec, msg.clock.nanosec)
19240                {
19241                    nros_core::clock::Clock::set_ros_time_override(nanos);
19242                }
19243            },
19244            None, // no group — node default
19245            None, // the configured default RX buffer, unchanged
19246        )
19247}
19248
19249// ============================================================================
19250// phase-417 W4.c — cancel / is_spinning
19251// ============================================================================
19252//
19253// Same gate as `executor::tests`, exactly: `ConcreteSession` is `MockSession`
19254// only while no rmw-* feature is unified in (see `executor/mod.rs`), and
19255// `from_session_with` / `halt_flag` are `alloc`. No `std` gate — `cfg(test)`
19256// already means a hosted harness, which is why `lib.rs` brings `std` in under
19257// `test` as well. (It said "exactly" while missing `alloc`, and `std` was not in
19258// scope: 20 errors, hidden by feature unification under `--workspace`.)
19259#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
19260mod cancel_tests {
19261    use super::Executor;
19262    use crate::{executor::types::ExecutorConfig, mock::MockSession};
19263
19264    /// The core has no default clock and says so (issue 0709), so a test that
19265    /// measures elapsed time brings its own — the same seam a board uses.
19266    fn test_clock_us() -> u64 {
19267        use std::{sync::OnceLock, time::Instant};
19268        static EPOCH: OnceLock<Instant> = OnceLock::new();
19269        EPOCH.get_or_init(Instant::now).elapsed().as_micros() as u64
19270    }
19271
19272    fn executor() -> Executor<'static> {
19273        let cfg = ExecutorConfig::default().clock_us(test_clock_us);
19274        Executor::from_session_with(MockSession::new(), &cfg)
19275    }
19276
19277    /// A fresh executor is neither cancelled nor spinning — the two questions
19278    /// are independent, and this is the state where both answers are `false`.
19279    #[test]
19280    fn a_fresh_executor_is_neither_cancelled_nor_spinning() {
19281        let exec = executor();
19282        assert!(!exec.is_halted(), "nothing has asked it to stop");
19283        assert!(!exec.is_spinning(), "no spin loop is running");
19284    }
19285
19286    /// `cancel()` raises the request bit without starting or stopping anything.
19287    #[test]
19288    fn cancel_requests_without_spinning() {
19289        let exec = executor();
19290        exec.cancel();
19291        assert!(exec.is_halted(), "cancel() must be observable immediately");
19292        assert!(
19293            !exec.is_spinning(),
19294            "cancel() must not make a non-spinning executor claim to spin"
19295        );
19296    }
19297
19298    /// The load-bearing one: `cancel()` from a peer thread TERMINATES a running
19299    /// `spin`, `is_spinning()` is true while the loop runs, and false
19300    /// once it has returned.
19301    ///
19302    /// The peer asserts `is_spinning()` from OUTSIDE the spinning thread, which
19303    /// is the whole point of the observable — it is what a signal handler or a
19304    /// supervisor sees.
19305    #[test]
19306    fn cancel_terminates_a_spin_and_is_spinning_tracks_it() {
19307        use std::{
19308            sync::{
19309                Arc,
19310                atomic::{AtomicBool, Ordering},
19311            },
19312            thread,
19313            time::{Duration, Instant},
19314        };
19315
19316        let mut exec = executor();
19317        assert!(!exec.is_spinning());
19318
19319        // `Executor` is not `Sync`, so the peer thread cannot hold a reference
19320        // to it. It observes and drives through the two flag handles instead —
19321        // which is the supported cross-thread surface (`halt_flag()`), and
19322        // keeps this test on the same seam a signal handler uses.
19323        let cancel_bit = exec.halt_flag();
19324        let saw_spinning = Arc::new(AtomicBool::new(false));
19325        let saw_spinning_peer = Arc::clone(&saw_spinning);
19326
19327        let started = Instant::now();
19328        let peer = thread::spawn(move || {
19329            // Give the loop time to enter. Bounded, and the assertion below is
19330            // on what was OBSERVED, so a slow host cannot turn this green by
19331            // accident — it fails instead.
19332            thread::sleep(Duration::from_millis(50));
19333            saw_spinning_peer.store(true, Ordering::SeqCst);
19334            cancel_bit.store(true, Ordering::SeqCst);
19335        });
19336
19337        exec.spin(crate::executor::types::SpinOptions::default())
19338            .expect("an untimed spin runs until cancelled");
19339        let elapsed = started.elapsed();
19340
19341        peer.join().expect("peer thread must not panic");
19342
19343        assert!(
19344            saw_spinning.load(Ordering::SeqCst),
19345            "the peer must have run before spin returned"
19346        );
19347        assert!(
19348            !exec.is_spinning(),
19349            "is_spinning() must be false once the loop has returned"
19350        );
19351        assert!(
19352            exec.is_halted(),
19353            "the cancel request survives the loop it ended"
19354        );
19355        // LOWER bound too: a spin that never waited would prove nothing about
19356        // termination. The peer sleeps 50 ms before cancelling.
19357        assert!(
19358            elapsed >= Duration::from_millis(40),
19359            "spin returned in {elapsed:?} — it cannot have spun"
19360        );
19361        // ...and an UPPER bound, because "terminated" is the claim: without the
19362        // cancel check this loop never returns and the test would hang rather
19363        // than fail. 10 s is far past any scheduling noise.
19364        assert!(
19365            elapsed < Duration::from_secs(10),
19366            "spin took {elapsed:?} to observe the cancel"
19367        );
19368    }
19369
19370    /// `is_spinning()` is true from INSIDE the loop. Read from a timer callback,
19371    /// which is the only place the executor is genuinely mid-spin, and asserted
19372    /// after the loop so a callback that never fired cannot pass silently.
19373    #[test]
19374    fn is_spinning_is_true_inside_the_loop() {
19375        use std::time::Duration;
19376
19377        let mut exec = executor();
19378        // `only_next` runs exactly one iteration, so this is a single poll
19379        // inside a spin scope — bounded, no thread, no clock dependency beyond
19380        // the one the fixture installs.
19381        assert!(!exec.is_spinning());
19382        exec.spin(crate::executor::types::SpinOptions::spin_once())
19383            .expect("a single-iteration spin must succeed");
19384        assert!(
19385            !exec.is_spinning(),
19386            "the scope must close when the loop returns"
19387        );
19388
19389        // The inside-the-loop reading needs a second thread to do it, because
19390        // the spinning thread is blocked in the loop and `Executor` is `!Sync`
19391        // so no `&Executor` may cross. What crosses is a pointer to the one
19392        // atomic, which is the same thing the C and C++ APIs hold: they observe
19393        // `is_spinning` through a raw executor handle, and that is the case this
19394        // flag exists to serve.
19395        struct FlagPtr(*const portable_atomic::AtomicBool);
19396        // SAFETY: the pointee is an `AtomicBool`, which is `Sync`; the only
19397        // operation performed through it is a relaxed-or-stronger load. The
19398        // executor outlives the thread — `peer.join()` below happens before
19399        // `exec` is dropped at the end of the test.
19400        unsafe impl Send for FlagPtr {}
19401
19402        let cancel_bit = exec.halt_flag();
19403        let observed = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
19404        let spinning_bit_seen = std::sync::Arc::clone(&observed);
19405        let flag = FlagPtr(&exec.spinning as *const portable_atomic::AtomicBool);
19406        let peer = std::thread::spawn(move || {
19407            let flag = flag;
19408            for _ in 0..500 {
19409                // SAFETY: see the `unsafe impl Send` above.
19410                if unsafe { &*flag.0 }.load(core::sync::atomic::Ordering::SeqCst) {
19411                    spinning_bit_seen.store(true, std::sync::atomic::Ordering::SeqCst);
19412                    break;
19413                }
19414                std::thread::sleep(Duration::from_millis(2));
19415            }
19416            cancel_bit.store(true, std::sync::atomic::Ordering::SeqCst);
19417        });
19418
19419        exec.spin(crate::executor::types::SpinOptions::default())
19420            .expect("an untimed spin runs until cancelled");
19421        peer.join().expect("peer thread must not panic");
19422
19423        assert!(
19424            observed.load(std::sync::atomic::Ordering::SeqCst),
19425            "is_spinning() must read true while spin is running"
19426        );
19427    }
19428
19429    /// `spin_period` maintains the same scope, and a period this build cannot
19430    /// pace is an error that must NOT leave the executor claiming to spin.
19431    #[test]
19432    fn spin_period_with_no_clock_leaves_is_spinning_false() {
19433        let mut exec = executor();
19434        exec.clock_us_fn = None;
19435        let err = exec
19436            .spin_period(core::time::Duration::from_millis(10))
19437            .expect_err("a period with no clock must fail (issue 0709)");
19438        assert_eq!(err, crate::NodeError::NotInitialized);
19439        assert!(
19440            !exec.is_spinning(),
19441            "a spin that never started must not report that it did"
19442        );
19443    }
19444
19445    /// Entering a spin CLEARS a stale cancel: a cancel requested before this
19446    /// spin is not a cancel of this spin. Documents the ADOPT-BOUNDED envelope's
19447    /// one sharp edge.
19448    #[test]
19449    fn entering_a_spin_clears_a_stale_cancel() {
19450        let exec = executor();
19451        exec.cancel();
19452        assert!(exec.is_halted());
19453        exec.enter_spin_loop();
19454        assert!(
19455            !exec.is_halted(),
19456            "a cancel raised before the loop started must not end it instantly"
19457        );
19458        assert!(exec.is_spinning());
19459        exec.exit_spin_loop();
19460        assert!(!exec.is_spinning());
19461    }
19462}
19463
19464/// phase-509 P9b item 3 (RFC-0108 D7) -- the arrival path wakes only the
19465/// worker whose band holds the slot.
19466// Issue 2727 -- a guard condition handle keeps the executor's wake state
19467// alive. The handle held a raw pointer to the `WakeCtx` whose last `Arc` the
19468// executor drops, so `trigger` after `drop(executor)` called the wake callback
19469// on freed memory, from safe code. `executor::tests` does not build with
19470// `rmw-cffi` (it needs `MockSession`), so these hold the handle to what
19471// `register_guard_condition_on` gives it: the executor's `Arc`, cloned.
19472#[cfg(all(test, feature = "alloc", feature = "rmw-cffi"))]
19473mod guard_wake_ctx_tests {
19474    use super::*;
19475    use portable_atomic_util::Arc;
19476
19477    /// The executor's side: the one `Arc` it owns, as `wake_ctx_ptr` builds it.
19478    fn executor_wake_ctx() -> Arc<WakeCtx> {
19479        Arc::new(WakeCtx::new(
19480            Arc::new(portable_atomic::AtomicBool::new(false)),
19481            None,
19482        ))
19483    }
19484
19485    /// A handle wired the way `register_guard_condition_on` wires it.
19486    fn handle_on<'a>(
19487        flag: &'a portable_atomic::AtomicBool,
19488        ctx: &Arc<WakeCtx>,
19489    ) -> GuardCondition<'a> {
19490        // SAFETY: `flag` outlives the handle (`'a`).
19491        let mut g = unsafe { GuardCondition::new(flag) };
19492        g.set_wake_cb(
19493            nros_rmw_runtime_wake_cb,
19494            nros_rmw_runtime_wake_cb_from_isr,
19495            ctx.clone(),
19496        );
19497        g
19498    }
19499
19500    #[test]
19501    fn a_guard_condition_keeps_the_wake_state_alive_past_its_executor() {
19502        let arena_flag = portable_atomic::AtomicBool::new(false);
19503        let owned = executor_wake_ctx();
19504        let wake_flag = owned.flag.clone();
19505        let handle = handle_on(&arena_flag, &owned);
19506        let weak = Arc::downgrade(&owned);
19507
19508        // The executor drops its `Arc` (`Executor::drop`).
19509        drop(owned);
19510        assert!(
19511            weak.upgrade().is_some(),
19512            "the handle holds the wake state past its executor"
19513        );
19514
19515        handle.trigger();
19516        assert!(arena_flag.load(portable_atomic::Ordering::SeqCst));
19517        assert!(
19518            wake_flag.load(portable_atomic::Ordering::SeqCst),
19519            "the trigger after the executor is gone reaches the state the handle holds"
19520        );
19521
19522        let second = handle.clone();
19523        drop(handle);
19524        assert!(weak.upgrade().is_some(), "a clone holds it too");
19525        drop(second);
19526        assert!(
19527            weak.upgrade().is_none(),
19528            "the last handle releases it: nothing else kept it"
19529        );
19530    }
19531
19532    #[test]
19533    fn a_guard_condition_is_one_pointer_of_wake_state() {
19534        // The C and C++ opaque storage is sized from this type; the `Arc`
19535        // took the raw pointer's place, not a second word.
19536        assert_eq!(
19537            core::mem::size_of::<Option<Arc<WakeCtx>>>(),
19538            core::mem::size_of::<*mut core::ffi::c_void>()
19539        );
19540    }
19541}
19542
19543#[cfg(all(test, feature = "alloc", feature = "rmw-cffi"))]
19544mod band_wake_routing_tests {
19545    use super::{
19546        super::{scheduler::BandWaiter, slot_mask::SlotMask},
19547        WakeCtx,
19548    };
19549    use core::ffi::c_void;
19550    use portable_atomic::{AtomicUsize, Ordering};
19551
19552    static WOKEN: [AtomicUsize; 3] = [const { AtomicUsize::new(0) }; 3];
19553
19554    unsafe extern "C" fn wake(ctx: *mut c_void) {
19555        WOKEN[ctx as usize].fetch_add(1, Ordering::SeqCst);
19556    }
19557
19558    unsafe extern "C" fn wait(_ctx: *mut c_void, _us: u64) -> i32 {
19559        0
19560    }
19561
19562    static THREAD_WAKES: AtomicUsize = AtomicUsize::new(0);
19563    static ISR_WAKES: AtomicUsize = AtomicUsize::new(0);
19564
19565    unsafe extern "C" fn thread_wake(_ctx: *mut c_void) {
19566        THREAD_WAKES.fetch_add(1, Ordering::SeqCst);
19567    }
19568
19569    unsafe extern "C" fn isr_wake(_ctx: *mut c_void) {
19570        ISR_WAKES.fetch_add(1, Ordering::SeqCst);
19571    }
19572
19573    // Issue 2696.
19574    /// An interrupt-path wake reaches every band worker through its
19575    /// `wake_from_isr` and never through its thread `wake`, which on
19576    /// FreeRTOS is `xSemaphoreGive` and must not run in an interrupt
19577    /// handler. The thread path is the negative control: it uses `wake`.
19578    #[test]
19579    fn an_isr_wake_uses_only_the_waiters_interrupt_safe_signal() {
19580        // SAFETY: the functions ignore the context.
19581        static W: BandWaiter =
19582            unsafe { BandWaiter::new(thread_wake, isr_wake, wait, core::ptr::null_mut()) };
19583        let flag = portable_atomic_util::Arc::new(portable_atomic::AtomicBool::new(false));
19584        let ctx = WakeCtx::new(flag.clone(), None);
19585        ctx.band_waiters
19586            .store(&W as *const _ as *mut _, Ordering::SeqCst);
19587
19588        // SAFETY: `ctx` is a live `WakeCtx`, as the executor installs it.
19589        let woke = unsafe {
19590            super::nros_rmw_runtime_wake_cb_from_isr(&ctx as *const WakeCtx as *mut c_void)
19591        };
19592        assert!(flag.load(Ordering::SeqCst), "the executor's flag is set");
19593        assert!(
19594            !woke,
19595            "no wake object here, so the ISR wake reports it reached none"
19596        );
19597        assert_eq!(ISR_WAKES.load(Ordering::SeqCst), 1);
19598        assert_eq!(
19599            THREAD_WAKES.load(Ordering::SeqCst),
19600            0,
19601            "no thread signal from an ISR"
19602        );
19603
19604        // SAFETY: as above.
19605        unsafe { super::nros_rmw_runtime_wake_cb(&ctx as *const WakeCtx as *mut c_void) };
19606        assert_eq!(
19607            THREAD_WAKES.load(Ordering::SeqCst),
19608            1,
19609            "the thread path uses `wake`"
19610        );
19611        assert_eq!(ISR_WAKES.load(Ordering::SeqCst), 1);
19612    }
19613
19614    #[test]
19615    fn an_attributed_arrival_wakes_its_band_and_an_unattributed_one_wakes_all() {
19616        // SAFETY: the contexts are plain indices `wake` decodes.
19617        static A: BandWaiter = unsafe { BandWaiter::new(wake, wake, wait, core::ptr::null_mut()) };
19618        static B: BandWaiter =
19619            unsafe { BandWaiter::new(wake, wake, wait, core::ptr::without_provenance_mut(1)) };
19620        A.slots.store(SlotMask::from_word0(0b0011));
19621        B.slots.store(SlotMask::from_word0(0b0100));
19622        let flag = portable_atomic_util::Arc::new(portable_atomic::AtomicBool::new(false));
19623        let ctx = WakeCtx::new(flag.clone(), None);
19624        B.next.store(&A as *const _ as *mut _, Ordering::SeqCst);
19625        ctx.band_waiters
19626            .store(&B as *const _ as *mut _, Ordering::SeqCst);
19627
19628        ctx.mark_ready(2);
19629        assert_eq!(WOKEN[1].load(Ordering::SeqCst), 1, "slot 2 is B's");
19630        assert_eq!(WOKEN[0].load(Ordering::SeqCst), 0);
19631        assert!(
19632            !flag.load(Ordering::SeqCst),
19633            "the executor's own worker sleeps on"
19634        );
19635
19636        ctx.mark_ready(1);
19637        assert_eq!(WOKEN[0].load(Ordering::SeqCst), 1, "slot 1 is A's");
19638
19639        ctx.mark_ready(5);
19640        assert!(
19641            flag.load(Ordering::SeqCst),
19642            "no band holds slot 5: own worker"
19643        );
19644        assert_eq!(
19645            WOKEN[0].load(Ordering::SeqCst) + WOKEN[1].load(Ordering::SeqCst),
19646            2
19647        );
19648
19649        ctx.signal();
19650        assert_eq!(
19651            WOKEN[0].load(Ordering::SeqCst),
19652            2,
19653            "unattributed: every band"
19654        );
19655        assert_eq!(WOKEN[1].load(Ordering::SeqCst), 2);
19656        assert_eq!(ctx.ready.load(), SlotMask::from_word0(0b100110));
19657    }
19658
19659    // Issue 2541.
19660    /// An entity on a slot past 64 gets an attributed waker: its arrival
19661    /// marks its own bit (not slot `i % 64`'s or `i % 32`'s) and wakes only
19662    /// the band worker that holds it. Before, the ready word was one `usize`,
19663    /// so such a slot got no waker and kept the session-wide wake.
19664    #[test]
19665    fn an_arrival_on_a_slot_past_64_marks_its_own_bit_and_wakes_its_band() {
19666        use super::super::entity_wake;
19667        const HIGH: usize = 100;
19668        const {
19669            assert!(
19670                HIGH < entity_wake::SLOTS,
19671                "cfg(test) holds at least 128 slots"
19672            )
19673        };
19674        // SAFETY: the context is a plain index `wake` decodes.
19675        static H: BandWaiter =
19676            unsafe { BandWaiter::new(wake, wake, wait, core::ptr::without_provenance_mut(2)) };
19677        H.slots.store(SlotMask::bit(HIGH));
19678        let flag = portable_atomic_util::Arc::new(portable_atomic::AtomicBool::new(false));
19679        let ctx = portable_atomic_util::Arc::new(WakeCtx::new(flag.clone(), None));
19680        assert_eq!(
19681            portable_atomic_util::Arc::as_ptr(&ctx) as usize % entity_wake::WAKE_CTX_ALIGN,
19682            0,
19683            "the slot rides in the pointer's low bits"
19684        );
19685        ctx.band_waiters
19686            .store(&H as *const _ as *mut _, Ordering::SeqCst);
19687
19688        assert!(
19689            entity_wake::waker(&ctx, entity_wake::SLOTS).is_none(),
19690            "past the capacity there is no attributed waker"
19691        );
19692        let waker = entity_wake::waker(&ctx, HIGH).expect("slot 100 is attributed");
19693        waker.wake_by_ref();
19694        assert_eq!(ctx.ready.load(), SlotMask::bit(HIGH), "its own bit only");
19695        assert_eq!(WOKEN[2].load(Ordering::SeqCst), 1, "its band's worker");
19696        assert!(
19697            !flag.load(Ordering::SeqCst),
19698            "the executor's own worker sleeps on"
19699        );
19700        assert_eq!(ctx.ready.take(), SlotMask::bit(HIGH));
19701        drop(waker);
19702    }
19703}