Skip to main content

nros_node/executor/
arena.rs

1//! Callback arena infrastructure (all pub(crate)).
2
3use core::marker::PhantomData;
4
5use nros_core::{
6    CdrReader, DeserializeView, MessageInfo, RawMessageInfo, RosAction, RosMessage, RosService,
7    ViewableMessage,
8};
9use nros_rmw::{ServiceTrait, Subscription, TransportError};
10
11use super::{
12    action_core::{ActionClientCore, ActionServerCore},
13    handles::{ActionServer, ActiveGoal},
14    spsc_ring::SpscRing,
15    triple_buffer::TripleBuffer,
16    types::{
17        InvocationMode, NodeError, RawAcceptedCallback, RawCancelCallback,
18        RawCancelResponseCallback, RawFeedbackCallback, RawGoalCallback, RawGoalResponseCallback,
19        RawMessageDeserializeFn, RawRequestId, RawResponseCallback, RawResponseRequestIdCallback,
20        RawResultCallback, RawServiceCallback, RawServiceRequestIdCallback,
21        RawSubscriptionCallback, RawSubscriptionInfoCallback, TypedSubscriptionCallback,
22    },
23};
24use crate::session;
25// phase-430 W4 — the clock-source enum moved to the ungated `timer` module so
26// the declarative metadata layer can name it; `executor` re-exports it.
27pub(crate) use crate::timer::{TimerCallInfo, TimerClockSource};
28
29// ============================================================================
30// Callback metadata
31// ============================================================================
32
33// ============================================================================
34// Phase 8 — callback dispatch hooks (paired stubs)
35// ============================================================================
36//
37// `docs/design/callback_tracing.rst`. The hooks bracket the LEAF callback
38// invocation rather than the `try_process` boundary, because that boundary
39// gets both granularity and truth wrong: one `try_process` for an action
40// server fires up to three distinct user callbacks, a ring-buffered
41// subscription fires the user callback once per queued message, and
42// `Ok(false)` — "ran, fired nothing", the common outcome for a timer that is
43// not yet due — would be recorded as an invocation that never happened.
44//
45// Paired stubs (the `entry_sched_tasks.rs` idiom) so the call sites read IDENTICALLY
46// whether or not the feature is on; the `#[cfg]` lives here, once, instead of
47// wrapping every hook site.
48
49/// Emit callback_start(handle) immediately before invoking a user callback.
50#[cfg(feature = "trace-callbacks")]
51#[inline]
52fn trace_cb_start(desc_idx: u8) {
53    super::callback_trace::start(desc_idx);
54}
55
56#[cfg(not(feature = "trace-callbacks"))]
57#[inline]
58fn trace_cb_start(_desc_idx: u8) {}
59
60/// phase-474 I3 -- a sample TAKEN for the subscription in `desc_idx`, emitted
61/// before its callback's start: the take event, and the sample's source stamp
62/// when `type_stamp` (the type's `STAMP_OFFSET`) or the slot's setting names
63/// one. Opt-in per slot or image-wide (`NROS_TRACE_TAKES`).
64#[cfg(feature = "trace-callbacks")]
65#[inline]
66fn trace_take(desc_idx: u8, raw: &[u8], type_stamp: Option<usize>) {
67    super::callback_trace::take(desc_idx, raw, type_stamp);
68}
69
70#[cfg(not(feature = "trace-callbacks"))]
71#[inline]
72fn trace_take(_desc_idx: u8, _raw: &[u8], _type_stamp: Option<usize>) {}
73
74/// phase-474 I3 -- whether this tick of the timer in `desc_idx` gets its
75/// start/end pair (one in N, per slot or `NROS_TRACE_TIMER_EVERY`).
76#[cfg(feature = "trace-callbacks")]
77#[inline]
78fn timer_tick_traced(desc_idx: u8) -> bool {
79    super::callback_trace::timer_tick_traced(desc_idx)
80}
81
82#[cfg(not(feature = "trace-callbacks"))]
83#[inline]
84fn timer_tick_traced(_desc_idx: u8) -> bool {
85    false
86}
87
88/// Emit callback_end(handle) immediately after a user callback returns.
89#[cfg(feature = "trace-callbacks")]
90#[inline]
91fn trace_cb_end(desc_idx: u8) {
92    super::callback_trace::end(desc_idx);
93}
94
95#[cfg(not(feature = "trace-callbacks"))]
96#[inline]
97fn trace_cb_end(_desc_idx: u8) {}
98
99/// Kind of registered callback entry.
100#[derive(Clone, Copy, PartialEq, Eq)]
101pub(crate) enum EntryKind {
102    Subscription,
103    Service,
104    ServiceClient,
105    Timer,
106    ActionServer,
107    ActionClient,
108    GuardCondition,
109}
110
111/// What a registration site calls the callback it is registering.
112///
113/// Phase 8 (`docs/design/callback_tracing.rst`) — the payload of the
114/// nros_callback_register event, resolved to a string only inside the
115/// feature-gated emitter so a build without `trace-callbacks` pays nothing
116/// for the two synthesised forms.
117///
118/// The three variants exist because the executor does NOT have a name for
119/// every entry kind:
120///
121/// * subscriptions / services / actions carry a topic or service name;
122/// * a timer carries only a period — so the period IS its identity;
123/// * a guard condition, and an arena subscription attached to an already-open
124///   `RmwSubscriber`, carry nothing at all — the slot index is the only
125///   thing that distinguishes one from another.
126///
127/// Naming them here rather than at the 25 emplace sites keeps the synthesis
128/// rules in one place; a new registration site that gets the name wrong is
129/// then a wrong ARGUMENT, not a second convention.
130// Only the feature-gated emitter READS these, so a build with the feature off
131// constructs them and never matches on them. That is the intended shape (the
132// call sites must read identically either way), not dead code to delete.
133#[cfg_attr(not(feature = "trace-callbacks"), allow(dead_code))]
134#[derive(Clone, Copy)]
135pub(crate) enum TraceName<'a> {
136    /// A real name the caller already has: topic, service, or action name.
137    Text(&'a str),
138    /// A timer, rendered `timer@<period_us>us`.
139    TimerPeriod(u64),
140    /// An entry with no name anywhere in the executor, rendered
141    /// `<label>#<slot>` — `guard#3`, `sub#7`. The slot index is exactly what
142    /// the runtime callback_start / callback_end events key on, so this
143    /// label is not a placeholder: it is the identity, spelled out.
144    Slot(&'static str, usize),
145}
146
147/// Metadata for a type-erased callback stored in the arena.
148///
149/// Each entry records where the concrete entry struct lives in the arena
150/// and carries monomorphized function pointers for dispatch and cleanup.
151#[derive(Clone, Copy)]
152pub(crate) struct CallbackMeta {
153    /// Byte offset into the arena where the concrete entry starts.
154    pub(crate) offset: usize,
155    /// What kind of entry this is (for `SpinOnceResult` counters).
156    pub(crate) kind: EntryKind,
157    /// Monomorphized dispatch: tries to receive and process one message/request.
158    /// Returns `Ok(true)` if work was done, `Ok(false)` if nothing available.
159    /// The `u64` parameter is `delta_us` (used by timer entries, ignored by others).
160    ///
161    /// The trailing `u8` is the entry's SLOT INDEX (phase 8,
162    /// `docs/design/callback_tracing.rst`). Inside a leaf the only identity
163    /// otherwise in scope is the address `arena_base + offset` — unique and
164    /// stable, but an address, and `arena_base` is not reachable from the
165    /// leaf. Threading the index in is the design's preferred fix over
166    /// publishing an `offset -> index` map: it needs no side table, it cannot
167    /// go stale if the arena moves, and attribution is exact at the point of
168    /// use. Both producers already have the index (the drain loop, the
169    /// trigger-fail timer sweep).
170    ///
171    /// Passed unconditionally rather than behind `feature = "trace-callbacks"`:
172    /// a cfg-dependent function-pointer signature would have to be threaded
173    /// through 21 leaf definitions as a macro. The cost when tracing is off is
174    /// one constant register argument per dispatch that the leaf ignores.
175    pub(crate) try_process: unsafe fn(*mut u8, u64, u8) -> Result<bool, TransportError>,
176    /// Monomorphized readiness check: returns true if the entry has data.
177    pub(crate) has_data: unsafe fn(*const u8) -> bool,
178    /// Monomorphized LET pre-sample: reads data from transport into the entry's
179    /// buffer without invoking the callback. No-op for non-subscription entries.
180    pub(crate) pre_sample: unsafe fn(*mut u8),
181    /// Per-callback invocation mode.
182    pub(crate) invocation: InvocationMode,
183    /// Issue 1631 — the arena bytes this entry's registration claimed,
184    /// starting at `offset` (the entry plus any trailing receive region).
185    ///
186    /// Registration sites write [`ArenaLen::UNRECORDED`]; the ONE choke point
187    /// `Executor::emplace_entry` overwrites it with the region the allocator
188    /// actually handed out, so no site can state a length that disagrees with
189    /// the allocation. `release_entry` gives exactly this back. Before 1631
190    /// the releasing CALLER had to restate the size from the concrete type,
191    /// which only works for an entry with no trailing region and a type the
192    /// caller can name — neither holds for a buffered subscription or for a
193    /// timer whose closure type lives in another crate.
194    pub(crate) arena_len: ArenaLen,
195    /// Monomorphized drop: runs destructors on the concrete entry.
196    pub(crate) drop_fn: unsafe fn(*mut u8),
197}
198
199// Issue 1631 — the no-growth claim, on EVERY target this crate compiles for
200// (the host test `callback_meta_len_rides_in_padding` only sees the host).
201const _: () = assert!(
202    core::mem::size_of::<Option<CallbackMeta>>() == 6 * core::mem::size_of::<usize>(),
203    "CallbackMeta grew: `arena_len` must ride in the tail padding"
204);
205
206/// Issue 1631 — the recorded length of one entry's arena region.
207///
208/// Sized to ride in `CallbackMeta`'s existing tail padding, so the entry
209/// table (and every stated executor backing size) does not grow: the two
210/// one-byte enums leave six spare bytes on a 64-bit target and two on a
211/// 32-bit one. A 32-bit region of 64 KiB or more does not fit and is stored
212/// as [`UNRECORDED`](Self::UNRECORDED): its release still drops the entry and
213/// frees the slot, and keeps the bytes — a leak of one region, never a reuse
214/// of bytes that are still in use. `callback_meta_len_rides_in_padding` pins
215/// the no-growth claim.
216#[derive(Clone, Copy, PartialEq, Eq, Debug)]
217pub(crate) struct ArenaLen(ArenaLenRepr);
218
219#[cfg(target_pointer_width = "64")]
220type ArenaLenRepr = u32;
221#[cfg(not(target_pointer_width = "64"))]
222type ArenaLenRepr = u16;
223
224impl ArenaLen {
225    /// No length known: a release frees the slot and keeps the bytes.
226    pub(crate) const UNRECORDED: Self = Self(ArenaLenRepr::MAX);
227
228    /// The length, or [`UNRECORDED`](Self::UNRECORDED) when it does not fit.
229    pub(crate) fn new(len: usize) -> Self {
230        match ArenaLenRepr::try_from(len) {
231            Ok(v) if v != ArenaLenRepr::MAX => Self(v),
232            _ => Self::UNRECORDED,
233        }
234    }
235
236    /// `None` when unrecorded.
237    pub(crate) fn get(self) -> Option<usize> {
238        (self != Self::UNRECORDED).then_some(self.0 as usize)
239    }
240}
241
242/// phase-476 W2 — the hook that destroys a capture the arena holds.
243///
244/// A capture's bytes are copied into its entry's trailing region, which MOVES
245/// ownership of whatever the capture owns (a C++ `std::shared_ptr`, a
246/// `std::string`): the C++ side relinquishes its own copy without destroying
247/// it. So the arena copy has to be destroyed exactly once, when its entry is,
248/// and this `Drop` is that once — every entry that holds a capture carries one
249/// of these, so it runs inside `release_entry`'s `drop_fn` (or the executor's
250/// teardown), before the region is handed back.
251///
252/// `drop: None` is a capture with nothing to destroy, or no capture at all.
253pub(crate) struct CaptureGuard {
254    pub(crate) ctx: *mut core::ffi::c_void,
255    pub(crate) drop: Option<unsafe extern "C" fn(*mut core::ffi::c_void)>,
256}
257
258impl Drop for CaptureGuard {
259    fn drop(&mut self) {
260        if let Some(drop) = self.drop {
261            // SAFETY: `ctx` is the arena's copy of the capture the registration
262            // supplied `drop` for, still inside the entry's region; this runs
263            // once because the entry is dropped once.
264            unsafe { drop(self.ctx) }
265        }
266    }
267}
268
269/// phase-476 W2 — a C timer callback over a capture the arena holds.
270pub(crate) struct CapturedCallback {
271    pub(crate) callback: unsafe extern "C" fn(*mut core::ffi::c_void),
272    pub(crate) guard: CaptureGuard,
273}
274
275impl CapturedCallback {
276    pub(crate) fn call(&self) {
277        // SAFETY: `ctx` is the arena's copy of the caller's capture (or null
278        // when there is none), alive as long as this entry; the registration's
279        // contract is that `callback` reads its capture through it.
280        unsafe { (self.callback)(self.guard.ctx) }
281    }
282}
283
284// ============================================================================
285// Concrete entry types
286// ============================================================================
287
288/// Concrete subscription entry stored in the arena (with MessageInfo).
289#[repr(C)]
290pub(crate) struct SubInfoEntry<M, F> {
291    pub(crate) handle: session::RmwSubscriber,
292    /// Issue 1860 / phase-498 W1 -- the receive slot, in the arena's trailing
293    /// region and sized at registration (from the type's bound when the
294    /// caller names none), as `SubBufferedRawInfoCEntry` has been since
295    /// phase-408 W5b. It was an inline `[u8; RX_BUF]`, so every entry of this
296    /// shape reserved the image's closure maximum whatever its own type was.
297    pub(crate) buffer: TrailingBuf,
298    /// Length of pre-sampled LET data (0 = not sampled).
299    pub(crate) sampled_len: usize,
300    pub(crate) callback: F,
301    pub(crate) _phantom: PhantomData<M>,
302}
303
304/// Concrete subscription entry stored in the arena (with safety validation).
305#[cfg(feature = "safety-e2e")]
306#[repr(C)]
307pub(crate) struct SubSafetyEntry<M, F> {
308    pub(crate) handle: session::RmwSubscriber,
309    /// Issue 1860 / phase-498 W1 -- the receive slot, in the arena's trailing
310    /// region and sized at registration (from the type's bound when the
311    /// caller names none), as `SubBufferedRawInfoCEntry` has been since
312    /// phase-408 W5b. It was an inline `[u8; RX_BUF]`, so every entry of this
313    /// shape reserved the image's closure maximum whatever its own type was.
314    pub(crate) buffer: TrailingBuf,
315    /// Length of pre-sampled LET data (0 = not sampled).
316    pub(crate) sampled_len: usize,
317    pub(crate) callback: F,
318    pub(crate) _phantom: PhantomData<M>,
319}
320
321/// Concrete service entry stored in the arena.
322#[repr(C)]
323pub(crate) struct SrvEntry<Svc: RosService, F, const REQ_BUF: usize, const REPLY_BUF: usize> {
324    pub(crate) handle: session::RmwServiceServer,
325    pub(crate) req_buffer: [u8; REQ_BUF],
326    pub(crate) reply_buffer: [u8; REPLY_BUF],
327    pub(crate) callback: F,
328    pub(crate) _phantom: PhantomData<Svc>,
329}
330
331/// What a periodic timer does with periods it missed while its executor
332/// was blocked.
333///
334/// A sched task that loses the CPU for several periods — a long-running
335/// callback, or preemption by a higher-priority band — resumes with
336/// accumulated elapsed time worth more than one period.
337#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
338pub enum TimerOverrunPolicy {
339    /// Coalesce the backlog: fire ONCE and drop the missed periods,
340    /// counting them in `overruns`. Phase is preserved (the sub-period
341    /// remainder carries over), so activations stay aligned to the
342    /// original cadence grid instead of drifting by each stall.
343    ///
344    /// The default, matching rclcpp (which advances the next call time
345    /// past "now") and Zephyr's `k_timer` (which coalesces expiries and
346    /// reports a count).
347    #[default]
348    Skip,
349    /// Replay every missed period, one activation per `try_process`
350    /// pass, until the backlog drains. Correct for timers that count or
351    /// accumulate, where each activation is a unit of work that must
352    /// not be lost. A replay burst runs back-to-back at dispatch speed,
353    /// NOT at the declared cadence — control loops usually want `Skip`.
354    CatchUp,
355}
356
357/// Concrete timer entry stored in the arena.
358///
359/// The first fields (up to `callback`) share layout with [`TimerHeader`],
360/// enabling type-erased access to timer state (cancel, reset, period query).
361#[repr(C)]
362pub(crate) struct TimerEntry<F> {
363    pub(crate) period_us: u64,
364    pub(crate) elapsed_us: u64,
365    /// Periods dropped by [`TimerOverrunPolicy::Skip`] (issue #505).
366    /// Saturating; never cleared by the dispatcher.
367    pub(crate) overruns: u32,
368    /// `overruns` as of the last `timer-overrun-runtime` monitor check,
369    /// so the rule reports newly dropped activations rather than the
370    /// running total. Lives here rather than in a table parallel to
371    /// `entries`, whose capacity is a runtime slice length.
372    pub(crate) overruns_reported: u32,
373    pub(crate) oneshot: bool,
374    pub(crate) fired: bool,
375    pub(crate) cancelled: bool,
376    pub(crate) overrun_policy: TimerOverrunPolicy,
377    /// Which clock advances `elapsed_us` (phase-425 W4). `Steady` consumes the
378    /// executor's spin delta; the others read their clock in `try_process`.
379    pub(crate) clock_source: TimerClockSource,
380    /// Last reading of `clock_source`, in nanoseconds. Meaningless — and never
381    /// read — while `clock_source` is `Steady`.
382    pub(crate) last_clock_ns: i64,
383    pub(crate) callback: F,
384}
385
386/// Type-erased header for timer entries.
387///
388/// Shares layout with the initial fields of `TimerEntry<F>` (both `#[repr(C)]`),
389/// so a `*mut TimerHeader` can safely read/write the timer state fields
390/// regardless of the concrete closure type `F`.
391#[repr(C)]
392pub(crate) struct TimerHeader {
393    pub(crate) period_us: u64,
394    pub(crate) elapsed_us: u64,
395    pub(crate) overruns: u32,
396    pub(crate) overruns_reported: u32,
397    pub(crate) oneshot: bool,
398    pub(crate) fired: bool,
399    pub(crate) cancelled: bool,
400    pub(crate) overrun_policy: TimerOverrunPolicy,
401    pub(crate) clock_source: TimerClockSource,
402    pub(crate) last_clock_ns: i64,
403}
404
405/// Concrete action server entry stored in the arena.
406#[repr(C)]
407pub(crate) struct ActionServerArenaEntry<
408    A: RosAction,
409    GoalF,
410    CancelF,
411    const GOAL_BUF: usize,
412    const RESULT_BUF: usize,
413    const FEEDBACK_BUF: usize,
414    const MAX_GOALS: usize,
415> {
416    pub(crate) server: ActionServer<A, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
417    pub(crate) goal_callback: GoalF,
418    pub(crate) cancel_callback: CancelF,
419}
420
421/// Concrete action server entry for raw (untyped) callbacks.
422///
423/// Uses [`ActionServerCore`] directly (no typed `ActionServer<A>` wrapper).
424#[repr(C)]
425pub(crate) struct ActionServerRawArenaEntry<
426    const GOAL_BUF: usize,
427    const RESULT_BUF: usize,
428    const FEEDBACK_BUF: usize,
429    const MAX_GOALS: usize,
430> {
431    pub(crate) core: ActionServerCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>,
432    pub(crate) goal_callback: RawGoalCallback,
433    pub(crate) cancel_callback: RawCancelCallback,
434    /// Optional hook fired after the accept reply has been sent. Used by the
435    /// C API so user-supplied long-running `accepted_callback`s run *after*
436    /// the client has observed the accept instead of blocking the reply.
437    pub(crate) accepted_callback: Option<RawAcceptedCallback>,
438    pub(crate) context: *mut core::ffi::c_void,
439}
440
441/// Concrete action client entry for raw (untyped) async callbacks.
442///
443/// Contains the `ActionClientCore` plus callback function pointers for
444/// goal response, feedback, and result. The executor polls the core's
445/// non-blocking methods during `spin_once` and invokes the callbacks.
446#[repr(C)]
447pub(crate) struct ActionClientRawArenaEntry<
448    const GOAL_BUF: usize,
449    const RESULT_BUF: usize,
450    const FEEDBACK_BUF: usize,
451> {
452    pub(crate) core: ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
453    pub(crate) goal_response_callback: Option<RawGoalResponseCallback>,
454    pub(crate) feedback_callback: Option<RawFeedbackCallback>,
455    pub(crate) result_callback: Option<RawResultCallback>,
456    /// Issue 2030 — `Some` makes the dispatcher take cancel replies (freeing
457    /// their request slots) and hand each to this callback; see
458    /// [`RawCancelResponseCallback`].
459    pub(crate) cancel_response_callback: Option<RawCancelResponseCallback>,
460    pub(crate) context: *mut core::ffi::c_void,
461}
462
463/// Concrete service-client entry for raw (untyped) async polling.
464///
465/// Holds the `RmwServiceClient` plus a single-shot reply buffer and a
466/// callback fn pointer. The executor dispatches via
467/// `service_client_raw_try_process` which checks `reply_ready` (set by
468/// the transport waker) before calling `take_response_raw`. This
469/// avoids busy-polling `get_check` on every spin tick.
470///
471/// Single in-flight request per entry: a second `send_request` while
472/// `pending` is still `true` is the user's responsibility to avoid (the
473/// C wrapper checks at the call site).
474///
475/// `sequences` holds the ids that logical call went out under
476/// (one per re-send), and a reply is dispatched only if it names one of them.
477/// Every sender records its id through [`ServiceClientRawArenaEntry::record_send`].
478#[repr(C)]
479pub struct ServiceClientRawArenaEntry<const REPLY_BUF: usize> {
480    pub handle: session::RmwServiceClient,
481    pub reply_buffer: [u8; REPLY_BUF],
482    pub pending: bool,
483    /// Set by the transport waker when a reply arrives for this slot.
484    /// Checked by `try_process` to avoid blind polling.
485    pub reply_ready: core::sync::atomic::AtomicBool,
486    pub callback: Option<RawResponseCallback>,
487    /// When set, dispatched IN PLACE of `callback`, with the id
488    /// of the request the reply answers (rclc's
489    /// `rclc_executor_add_client_with_request_id`). Same `context`.
490    pub request_id_callback: Option<RawResponseRequestIdCallback>,
491    pub context: *mut core::ffi::c_void,
492    /// The ids of the call in flight; see the type docs.
493    pub sequences: ClientSequences,
494}
495
496/// The request ids of an executor-owned client's one logical
497/// call: every re-send generation of it (see
498/// [`MAX_CLIENT_RESEND_GENERATIONS`](crate::limits::MAX_CLIENT_RESEND_GENERATIONS)).
499pub type ClientSequences =
500    nros_rmw::RequestCorrelator<(), { crate::limits::MAX_CLIENT_RESEND_GENERATIONS }>;
501
502impl<const REPLY_BUF: usize> ServiceClientRawArenaEntry<REPLY_BUF> {
503    /// Record a request this entry just sent. A FRESH call (`resend` false)
504    /// first forgets the ids of any earlier call, so that call's late reply is
505    /// dropped instead of being dispatched as this one's; a re-send of the
506    /// same call adds its generation beside the others.
507    pub fn record_send(&mut self, seq: i64, resend: bool) {
508        record_client_send(&mut self.sequences, seq, resend);
509    }
510
511    /// Take the reply to the call in flight, dropping any reply that names
512    /// another request. On a match every generation of the call is retired,
513    /// so the replies the other generations still draw are dropped too.
514    pub fn take_reply(&mut self, buf: &mut [u8]) -> Result<Option<usize>, TransportError> {
515        Ok(take_client_reply(&mut self.handle, buf, &mut self.sequences)?.map(|(len, _)| len))
516    }
517}
518
519/// Issue 2009 — [`ServiceClientRawArenaEntry::record_send`]'s rule, shared with
520/// the typed callback entry's header.
521pub(crate) fn record_client_send(seqs: &mut ClientSequences, seq: i64, resend: bool) {
522    if !resend {
523        seqs.clear();
524    } else if seq == nros_rmw::SEQUENCE_ID_UNKNOWN && seqs.contains(seq) {
525        // An id-less backend's re-sends are one request: nothing to add.
526        return;
527    }
528    seqs.insert_evicting(seq, ());
529}
530
531/// Issue 2009 — [`ServiceClientRawArenaEntry::take_reply`]'s rule.
532/// Returns the reply's length and the id it was matched on.
533pub(crate) fn take_client_reply(
534    handle: &mut session::RmwServiceClient,
535    buf: &mut [u8],
536    seqs: &mut ClientSequences,
537) -> Result<Option<(usize, i64)>, TransportError> {
538    match nros_rmw::take_correlated(handle, buf, seqs)? {
539        Some((len, seq, ())) => {
540            // The remaining generations answer a call that is now complete.
541            seqs.clear();
542            Ok(Some((len, seq)))
543        }
544        None => Ok(None),
545    }
546}
547
548/// Concrete service entry for raw (untyped) callbacks.
549///
550/// Issue 2081 — `C` is the callback's shape: [`RawServiceCallback`] (the
551/// request bytes alone) or [`RawServiceRequestIdCallback`] (plus the request's
552/// id). Both are one function pointer, so the entry's size does not depend on
553/// which.
554#[repr(C)]
555pub(crate) struct SrvRawEntry<
556    const REQ_BUF: usize,
557    const REPLY_BUF: usize,
558    C: RawServiceDispatch = RawServiceCallback,
559> {
560    pub(crate) handle: session::RmwServiceServer,
561    pub(crate) req_buffer: [u8; REQ_BUF],
562    pub(crate) reply_buffer: [u8; REPLY_BUF],
563    pub(crate) callback: C,
564    pub(crate) context: *mut core::ffi::c_void,
565    /// phase-488 — the arena's copy of a C++ handler's capture (a `std::bind`
566    /// over `this`, a capturing lambda), destroyed with the entry. `drop: None`
567    /// when the context is not a capture, which is every C caller.
568    pub(crate) capture: CaptureGuard,
569}
570
571/// Concrete guard condition entry stored in the arena.
572#[repr(C)]
573pub(crate) struct GuardConditionEntry<F> {
574    pub(crate) flag: portable_atomic::AtomicBool,
575    pub(crate) callback: F,
576}
577
578// ============================================================================
579// QoS-driven buffered subscription entries (Phase 73)
580// ============================================================================
581
582/// Buffer strategy selected by QoS depth at subscription registration time.
583///
584/// The buffer data lives in a trailing region immediately after the
585/// `SubBufferedEntry` struct in the arena.
586pub(crate) enum BufferStrategy {
587    /// `KEEP_LAST(1)`: 3 slots, latest-value semantics, writer never blocks.
588    Triple(TripleBuffer),
589    /// `KEEP_LAST(N)` where N > 1: N+1 slots, FIFO ordering, bounded drops.
590    Ring(SpscRing),
591}
592
593impl BufferStrategy {
594    /// Check if new data is available.
595    pub(crate) fn has_data(&self) -> bool {
596        match self {
597            BufferStrategy::Triple(tb) => tb.has_data(),
598            BufferStrategy::Ring(ring) => ring.has_data(),
599        }
600    }
601}
602
603/// The QoS depth an action client's FEEDBACK stream registers with.
604///
605/// Was an `8u16` literal at
606/// `NodeHandle::create_action_client_with_callbacks_sized`'s one call site.
607/// Named because `nros-node/build.rs` restates it to price the action-client
608/// arena slot, and a literal is a restatement nothing can be held to; see
609/// [`arena_model_tests`].
610pub const DEFAULT_ACTION_FEEDBACK_DEPTH: u16 = 8;
611
612/// Compute the number of buffer slots and trailing region size for a given
613/// QoS depth and per-slot buffer size.
614///
615/// Returns `(slot_count, trailing_bytes)`.
616pub(crate) fn buffered_region_size(depth: u32, slot_size: usize) -> (usize, usize) {
617    if depth <= 1 {
618        // Triple buffer: 3 fixed slots
619        (
620            TripleBuffer::SLOT_COUNT,
621            TripleBuffer::SLOT_COUNT * slot_size,
622        )
623    } else {
624        let d = depth as usize;
625        (SpscRing::slot_count(d), SpscRing::region_size(d, slot_size))
626    }
627}
628
629/// phase-408 W5b — a SINGLE flat payload slot living in the arena's trailing
630/// region, sized at REGISTRATION from the caller's `rx_buffer_hint` instead of
631/// baked into the entry as `[u8; RX_BUF]`.
632///
633/// Why this and not [`BufferStrategy`], which the plain C raw path uses: a
634/// triple buffer / ring DECOUPLES the producer's slot from the consumer's, and
635/// the two entries that hold a `TrailingBuf` carry PER-SAMPLE side data beside
636/// the payload — the wire attachment for
637/// [`SubBufferedRawInfoCEntry`], the integrity status for
638/// `SubBufferedRawSafetyCEntry`. Decoupled slots cannot carry that, which is
639/// the reason both were flat in the first place (see
640/// [`SubBufferedRawInfoEntry`]'s note) and it has not changed. What made them
641/// EXPENSIVE was the const, not the flatness: `RX_BUF` is
642/// `DEFAULT_RX_BUF_SIZE` at every call site, so a subscription that knows its
643/// type's bound was still charged the image-wide default. Moving the bytes out
644/// to the trailing region spends the hint on the allocation while keeping one
645/// sample per dispatch.
646///
647/// The buffer does not own its memory — the arena does, and it outlives every
648/// entry in it.
649#[repr(C)]
650pub(crate) struct TrailingBuf {
651    ptr: *mut u8,
652    len: usize,
653}
654
655impl TrailingBuf {
656    /// Adopt `len` bytes of arena trailing region at `ptr`, zeroing them.
657    ///
658    /// The zeroing is what makes [`as_mut_slice`](Self::as_mut_slice) a safe
659    /// method: the executor arena is `&mut [MaybeUninit<u8>]`, so the region is
660    /// UNINITIALISED until someone writes it, and handing out a `&mut [u8]`
661    /// over uninit bytes is UB even if every reader stays inside the length a
662    /// receive reported. The entries this replaced held an inline
663    /// `[0u8; RX_BUF]` and were therefore initialised; one memset per
664    /// REGISTRATION (not per sample) keeps that property rather than trading it
665    /// for the allocation saving.
666    ///
667    /// # Safety
668    /// `ptr` must point to at least `len` writable bytes that stay valid for
669    /// the lifetime of this `TrailingBuf` — i.e. a region handed back by
670    /// `arena_alloc_with_trailing`, which is never reused while the entry
671    /// lives.
672    pub(crate) unsafe fn init(ptr: *mut u8, len: usize) -> Self {
673        // Safety: the caller's contract — `len` writable bytes at `ptr`.
674        unsafe { core::ptr::write_bytes(ptr, 0, len) };
675        Self { ptr, len }
676    }
677
678    /// The whole slot, read-only, for a callback to borrow a received prefix.
679    pub(crate) fn as_slice(&self) -> &[u8] {
680        // Safety: as `as_mut_slice` -- `len` initialised bytes at `ptr`.
681        unsafe { core::slice::from_raw_parts(self.ptr, self.len) }
682    }
683
684    /// The whole slot, for a receive to fill.
685    pub(crate) fn as_mut_slice(&mut self) -> &mut [u8] {
686        // Safety: the `init` contract — `len` writable bytes at `ptr`, valid
687        // for as long as `self`, and zeroed there so they are initialised `u8`.
688        unsafe { core::slice::from_raw_parts_mut(self.ptr, self.len) }
689    }
690
691    /// The slot's base address, for handing to a C callback.
692    pub(crate) fn as_ptr(&self) -> *const u8 {
693        self.ptr
694    }
695}
696
697/// Subscription entry with QoS-driven buffer strategy (Phase 73).
698///
699/// Unlike the legacy single-buffer pattern, this entry
700/// stores a [`BufferStrategy`] that manages a trailing buffer region
701/// allocated from the arena at registration time.
702///
703/// # Arena layout
704///
705/// ```text
706/// [SubBufferedEntry<M, F> struct][trailing: slot_count × slot_size bytes]
707///  ↑ offset                      ↑ buffer managed by BufferStrategy
708/// ```
709/// W3b.5 — a contracted subscriber's age hook: the endpoint's cell plus
710/// the epoch clock, captured at registration. `None` = uncontracted (or
711/// no epoch source / no stamp in the type) — the take path costs one
712/// `Option` branch.
713pub(crate) type AgeMon = (
714    &'static crate::executor::monitor::SubMonitorCell,
715    Option<fn() -> u64>,
716);
717
718/// Record one stamped take on an age cell: its age when an epoch source is
719/// installed, else the take alone (issue 2215, `observe_unaged`).
720#[inline]
721fn observe_stamp(
722    cell: &crate::executor::monitor::SubMonitorCell,
723    epoch: Option<fn() -> u64>,
724    raw: &[u8],
725    off: usize,
726) {
727    if let Some(stamp_us) = crate::executor::monitor::peek_stamp_us(raw, off) {
728        match epoch {
729            Some(epoch) => cell.observe(stamp_us, epoch()),
730            None => cell.observe_unaged(),
731        }
732    }
733}
734
735/// W3b.5 — peek the message stamp from the raw CDR buffer and record its
736/// take-age. Compiled away per-type when `M::STAMP_OFFSET` is `None`.
737#[inline]
738pub(crate) fn observe_age<M: RosMessage>(raw: &[u8], mon: &Option<AgeMon>) {
739    if let (Some((cell, epoch)), Some(off)) = (mon, M::STAMP_OFFSET) {
740        observe_stamp(cell, *epoch, raw, off);
741    }
742}
743
744/// Issue 2215 — the C/C++ callback path's age hook. That path carries no Rust
745/// type, so the stamp's CDR offset comes from the registration (the C++
746/// template reads it off the message type, `M::STAMP_OFFSET`, and passes it in
747/// `nros_cpp_subscription_options_t::stamp_offset`). Bound after registration
748/// by `Executor::bind_raw_subscription_stamp`; `None` = no age row on this
749/// topic, or the type carries no stamp.
750#[derive(Clone, Copy)]
751pub(crate) struct RawAgeMon {
752    pub(crate) cell: &'static crate::executor::monitor::SubMonitorCell,
753    pub(crate) epoch: Option<fn() -> u64>,
754    pub(crate) stamp_offset: u16,
755}
756
757/// Issue 2215 — record a C/C++ subscription's take on its age row.
758#[inline]
759pub(crate) fn observe_age_raw(raw: &[u8], mon: &Option<RawAgeMon>) {
760    if let Some(m) = mon {
761        observe_stamp(m.cell, m.epoch, raw, m.stamp_offset as usize);
762    }
763}
764
765#[repr(C)]
766pub(crate) struct SubBufferedEntry<M, F> {
767    pub(crate) handle: session::RmwSubscriber,
768    pub(crate) buffer: BufferStrategy,
769    pub(crate) callback: F,
770    /// W3b.5 — age hook for contracted endpoints.
771    pub(crate) age_mon: Option<AgeMon>,
772    pub(crate) _phantom: PhantomData<M>,
773}
774
775/// Drain the RMW subscriber handle into the buffer strategy.
776///
777/// Calls `take_serialized()` on the subscriber handle and writes received data
778/// into the triple buffer's write slot or the SPSC ring's next push slot.
779///
780/// # Safety
781/// `entry` must be a valid mutable reference to a `SubBufferedEntry`.
782/// Issue 0757 — how many takes this process has dropped, for throttling.
783///
784/// A COUNTER, not a per-entry field, and deliberately: the arena's entry
785/// structs are sized by knob at build time (`EXECUTOR_OPAQUE_U64S`), so adding
786/// a field here would move every image's executor footprint to buy a log line.
787/// The cost is that the report cannot name the topic — see `report_dropped_take`.
788static DROPPED_TAKES: portable_atomic::AtomicU32 = portable_atomic::AtomicU32::new(0);
789
790/// issue 0900 — has the arena-headroom advisory been emitted?
791///
792/// A STATIC, for the reason [`DROPPED_TAKES`] is one: an `Executor` field would
793/// move `EXECUTOR_OPAQUE_U64S` and therefore every image's executor footprint,
794/// to buy a diagnostic. Process-scoped rather than per-executor is also the
795/// RIGHT scope here, not merely the cheap one — the number this names
796/// (`NROS_EXECUTOR_ARENA_BYTES`) is a BUILD-TIME constant, identical for every
797/// executor in the image, so saying it twice adds nothing.
798static ARENA_ADVISORY_DONE: portable_atomic::AtomicBool = portable_atomic::AtomicBool::new(false);
799
800/// Report an arena that is far larger than the entities registered in it.
801///
802/// `ARENA_SIZE` is derived by budgeting EVERY slot at the ActionClient worst
803/// case (`nros-node/build.rs`) unless the image declares its entities, so an
804/// image with no action client carries several times what it can use — 74,240
805/// bytes against ~51 KiB for four default-QoS subscriptions. (That comparison
806/// read "~16 KiB" until issue 1190: the pub/sub figure it named came from a
807/// model that priced a subscription's history at three slots when the ROS
808/// default is eleven.) The arena is a BUMP allocator, so
809/// `arena_used` is the exact claimed total rather than a reservation, and the
810/// allocator has therefore always known the right answer and never said it.
811///
812/// The override exists (`NROS_EXECUTOR_ARENA_BYTES`, or
813/// `CONFIG_NROS_EXECUTOR_ARENA_BYTES` on Zephyr) and is already load-bearing:
814/// the FreeRTOS action examples pin it to 8192 and still need a 64 KB app task
815/// stack, a number someone found by hitting "Invalid mbox" and working
816/// backwards. That is the shape of issues 0271/0739 — a knob nobody can
817/// enumerate is a knob nobody sets — and this turns it from folklore into a
818/// measurement.
819///
820/// **Where the arena lives is the CALLER's choice**, and THREE answers are real
821/// -- phase-392 W6 surveyed every entry path and found a third this comment had
822/// missed. `Executor` holds `arena: &'s mut [MaybeUninit<u8>]` -- a borrowed
823/// slice, since phase-271 (issue 0110) moved the sized tables off build-time
824/// consts. What is inline is `ExecutorInlineStorage::backing`, which the C FFI
825/// sizes its `_opaque` from.
826///
827/// * **`.bss`** -- all 34 in-tree C `rclc_executor_t` objects are file-scope
828///   statics; the C++ entry reaches `Node::GlobalStorageHolder`, also a static;
829///   and the `alloc` convenience constructors serve from
830///   `super::backing::EXECUTOR_BACKING`. Visible to `nm` and `mem-report`.
831///   Measured on mr-canhubk344: DTCM tracked ARENA_SIZE one-for-one across
832///   MAX_CBS 24 -> 36. Measured on the native zenoh talker: 21,560 B.
833/// * **the heap** -- the `alloc` constructors' fallback (a second executor, or
834///   an entry sized past the reservation, or `NROS_EXECUTOR_BACKING_BYTES=0`).
835///   This was the ONLY Rust answer before W6, and it has no symbol, which is
836///   why the campaign's own instrument could not see its largest consumer.
837/// * **a task stack** -- a stack-declared `rclc_executor_t`. Legal, and nothing
838///   in the tree does it.
839///
840/// Do not size against one placement and assume another.
841///
842/// `nros_log`, never stdio: this is reached on `no_std` targets and inside
843/// Zephyr `native_sim`, where a Rust `std` stdio call is FATAL (issue 0589).
844#[cold]
845fn report_arena_headroom(used: usize, capacity: usize) {
846    // Round the suggestion up so a small later registration still fits, and
847    // keep it a multiple of 1024 because that is the unit the knob is written
848    // in everywhere else in the tree.
849    let suggest = used.next_multiple_of(1024).max(1024);
850    // BUDGET: `nros_log`'s call-site format buffer is 256 bytes by default
851    // (`NROS_LOG_BUFFER_BYTES`), and overflow truncates with a `…` rather than
852    // dropping the record. The first draft of this line ran ~450 bytes and was
853    // cut mid-number, so the sink received "executor arena is 74240 bytes and
854    // 32…" — every word of the explanation and NONE of the value to set. A
855    // diagnostic that explains itself past the budget delivers exactly the
856    // folklore it was written to replace. So: the actionable value FIRST, the
857    // reasoning in this comment and issue 0900, and a test that fails on `…`.
858    nros_log::log_info!(
859        nros_log::get_logger("nros"),
860        // phase-392 W6 — the clause "and the arena is INLINE ON THE TASK STACK"
861        // stood here and was FALSE on every path (see the doc comment above);
862        // dropping it is also what buys the budget back. Placement is the
863        // caller's, so this line names the NUMBER, which is the same whichever
864        // memory the backing came from.
865        // Issue 2465 — worded as OPTIONAL tuning: on a first-node run "set
866        // X=1024" read as a step the user had skipped, and nothing is wrong.
867        "arena larger than needed: {used}/{capacity} bytes claimed at first \
868         spin. Optional, to save RAM: NROS_EXECUTOR_ARENA_BYTES={suggest} \
869         (Zephyr: CONFIG_ prefix), plus room for anything registered later."
870    );
871}
872
873/// One-shot arena-headroom check, called on the first `spin_once`.
874///
875/// First spin, not registration end, because there is no "registration end" —
876/// an app may register lazily, and this is why the message says
877/// "at first spin" and names what it measured rather than asserting a total.
878///
879/// Hot-path cost is one relaxed load on a branch that is taken exactly once.
880pub(crate) fn maybe_report_arena_headroom(used: usize, capacity: usize) {
881    if ARENA_ADVISORY_DONE.load(portable_atomic::Ordering::Relaxed) {
882        return;
883    }
884    // Only ever set, never cleared, so a racing second spin at worst emits the
885    // line twice — cheaper than an AcqRel on every spin to prevent a duplicate
886    // advisory.
887    ARENA_ADVISORY_DONE.store(true, portable_atomic::Ordering::Relaxed);
888    if arena_is_over_provisioned(used, capacity) {
889        report_arena_headroom(used, capacity);
890    }
891}
892
893/// Say WHY a registration ran out of arena, once.
894///
895/// `NodeError::BufferTooSmall` is the same code a dozen other paths return, so
896/// on a target where a return code is all you get, exhaustion here is
897/// indistinguishable from a message that did not fit a receive buffer. This
898/// names the entity that failed, the numbers involved, and the knobs that
899/// actually govern it.
900///
901/// `NROS_PUBSUB_QOS_DEPTH` comes FIRST, with the depth this image was budgeted
902/// for. Since phase-412 W3b the derived arena prices every subscription at that
903/// depth, so a subscription created deeper than it is the ordinary way a
904/// derived arena runs out — and raising the depth re-derives the arena, where a
905/// hand-set `NROS_EXECUTOR_ARENA_BYTES` goes stale the next time any other term
906/// moves (the rationale #775 gave for the depth knob). The line named only the
907/// size and the action-client count until then, i.e. not the knob the likeliest
908/// failure needs.
909///
910/// The counterpart to [`report_arena_headroom`], and the reason lowering
911/// `NROS_EXECUTOR_ACTION_CLIENTS` is safe to suggest: too small fails at
912/// REGISTRATION rather than at link, so the failure has to say so itself.
913///
914/// One-shot for the same reason the advisory is — the numbers do not change
915/// between registrations, and a per-registration line on an RTOS target is a
916/// flood (issue 0371's shape). `nros_log`, never stdio (issue 0589), and inside
917/// the 256-byte format budget that truncated the first advisory — at the widest
918/// realistic values too (10-digit counts, a 32-byte entity, a 5-digit depth),
919/// which
920/// `executor::tests::an_exhausted_arena_decodes_to_the_knob_an_operator_must_set`
921/// derives from the real line and holds under the buffer.
922#[cold]
923pub(crate) fn report_arena_exhausted(
924    entity: &'static str,
925    want: usize,
926    used: usize,
927    capacity: usize,
928    released: usize,
929    request: usize,
930) {
931    if ARENA_EXHAUSTED_REPORTED.swap(true, portable_atomic::Ordering::Relaxed) {
932        return;
933    }
934    let entity = entity_label(entity);
935    let depth = crate::config::arena_model::BUDGETED_QOS_DEPTH;
936    nros_log::log_error!(
937        nros_log::get_logger("nros"),
938        "arena exhausted at {entity}: {want} B short, {used}/{capacity} used. \
939         Raise NROS_PUBSUB_QOS_DEPTH (budgeted {depth}) if a sub is deeper, \
940         else NROS_EXECUTOR_ARENA_BYTES or NROS_EXECUTOR_ACTION_CLIENTS \
941         (Zephyr: CONFIG_*)."
942    );
943    // Issue 1496 / 1370's question asked of THIS arena: since entries can be
944    // released, the bytes may be there in holes none of which fits. A second
945    // line, only then, so the common case keeps its one line and its budget.
946    if arena_refusal_is_fragmented(request, released) {
947        // issue 1496
948        nros_log::log_error!(
949            nros_log::get_logger("nros"),
950            "arena FRAGMENTED: {released} B released, no hole holds {request} B"
951        );
952    }
953}
954
955/// Issue 1496 — the arena's own exhaustion classification, the same rule
956/// `zpico_alloc::Exhaustion::classify` states for the platform heap (issue
957/// 1370): the released bytes would hold the request, so it was the SHAPE that
958/// refused it, not the size. (Released regions are reused first-fit before the
959/// bump pointer moves, so reaching exhaustion with enough released bytes means
960/// no single region fitted.)
961pub(crate) const fn arena_refusal_is_fragmented(request: usize, released: usize) -> bool {
962    released >= request && request > 0
963}
964
965/// Issue 1036 — arena exhaustion reaches the platform's FATAL HOOK where the
966/// image asked for it (`NROS_ARENA_EXHAUSTION_IS_FATAL`, Zephyr
967/// `CONFIG_NROS_ARENA_EXHAUSTION_IS_FATAL`, default ON with the boot report),
968/// the arena's twin of `CONFIG_NROS_HEAP_EXHAUSTION_IS_FATAL` (issue 1425).
969///
970/// The log line goes nowhere on a board with no console, and a returned
971/// `BufferTooSmall` is handled only by code written to handle it — so without
972/// this, the observable outcome of an exhausted arena on the island is an image
973/// that keeps running with an entity missing. The record is written BEFORE
974/// this (`arena_exhausted`), so it survives the halt.
975///
976/// In a unit-test build the hook is a latch the test reads instead of a call
977/// into a platform the test does not link.
978#[cold]
979pub(crate) fn arena_exhaustion_is_fatal() {
980    #[cfg(all(nros_arena_exhaustion_fatal, not(test)))]
981    {
982        unsafe extern "C" {
983            fn nros_platform_panic(msg: *const u8, len: usize) -> !;
984        }
985        const MSG: &[u8] = b"executor arena exhausted (see the boot report's failed_alloc_size)";
986        // SAFETY: a static byte string and its length; the platform contract
987        // takes any bytes and never returns.
988        unsafe { nros_platform_panic(MSG.as_ptr(), MSG.len()) }
989    }
990    #[cfg(all(nros_arena_exhaustion_fatal, test))]
991    ARENA_FATAL_HOOK_REACHED.store(true, portable_atomic::Ordering::Relaxed);
992}
993
994/// Test-build stand-in for the fatal hook — see [`arena_exhaustion_is_fatal`].
995#[cfg(all(nros_arena_exhaustion_fatal, test))]
996pub(crate) static ARENA_FATAL_HOOK_REACHED: portable_atomic::AtomicBool =
997    portable_atomic::AtomicBool::new(false);
998
999/// The registering entity, short enough for the log budget.
1000///
1001/// From `core::any::type_name`, whose full spelling carries every generic
1002/// argument and runs past 150 bytes. The generics go, and so does all but the
1003/// last TWO path segments: most arena entries are a module's `Entry`, so the
1004/// last segment alone would name nothing (`sub_buffered::Entry`, not `Entry`).
1005/// Capped at 32 bytes; type names are ASCII, so the cut is on a char boundary.
1006pub(crate) fn entity_label(full: &'static str) -> &'static str {
1007    let path = full.split('<').next().unwrap_or(full);
1008    let label = match path.rmatch_indices("::").nth(1) {
1009        Some((i, _)) => &path[i + 2..],
1010        None => path,
1011    };
1012    let cut = label.len().min(32);
1013    label.get(..cut).unwrap_or(label)
1014}
1015
1016#[cfg(test)]
1017mod entity_label_tests {
1018    use super::entity_label;
1019
1020    mod sub_buffered {
1021        pub struct Entry<T>(pub T);
1022    }
1023
1024    /// The shape nearly every arena entry has: a module's `Entry`, generic.
1025    /// The last segment alone is `Entry` for all of them, which names nothing.
1026    #[test]
1027    fn a_module_entry_keeps_its_module_and_drops_its_generics() {
1028        let full = core::any::type_name::<sub_buffered::Entry<[u8; 1024]>>();
1029        assert!(full.contains('<'), "precondition: a generic name: {full}");
1030        assert_eq!(entity_label(full), "sub_buffered::Entry");
1031    }
1032
1033    #[test]
1034    fn a_primitive_is_itself() {
1035        assert_eq!(entity_label(core::any::type_name::<u8>()), "u8");
1036    }
1037
1038    #[test]
1039    fn a_long_label_is_capped_for_the_log_budget() {
1040        let label = entity_label("a::a_module_name_well_past_the_cap::AnEntryTypeName<X>");
1041        assert_eq!(label.len(), 32, "{label}");
1042        assert!(label.starts_with("a_module_name_well_past_the_cap"));
1043    }
1044}
1045
1046/// One-shot latch for [`report_arena_exhausted`]. A static for the reason
1047/// [`DROPPED_TAKES`] is one.
1048static ARENA_EXHAUSTED_REPORTED: portable_atomic::AtomicBool =
1049    portable_atomic::AtomicBool::new(false);
1050
1051/// Is this arena grossly larger than what registered in it?
1052///
1053/// Half is the threshold because the derivation's own over-provision at the
1054/// defaults is larger than that (74,240 bytes budgeted against ~51 KiB for four
1055/// default-QoS subscriptions, and against a few hundred bytes for a timer-only
1056/// image), so "under half" is unambiguous rather than a rounding artifact, and
1057/// an image that genuinely uses most of its arena stays quiet. Issue 1190 moved
1058/// the pub/sub half of that comparison from ~16 KiB to ~51 KiB, which
1059/// deliberately takes a four-subscription image OUT of the advisory: it is not
1060/// over-provisioned, it was mis-priced.
1061///
1062/// A zero capacity is NOT over-provisioned: that is the sentinel bug issue 0460
1063/// produced on Zephyr (a literal `0` forwarded instead of the derivation), and
1064/// it fails loudly on the first registration. Calling it over-provisioned would
1065/// bury a fatal misconfiguration under an advisory about wasted space.
1066///
1067/// Separated from [`maybe_report_arena_headroom`] so it is testable: the
1068/// reporter is one-shot on a process-scoped flag, so a test that called it
1069/// twice would silently check nothing the second time.
1070pub(crate) const fn arena_is_over_provisioned(used: usize, capacity: usize) -> bool {
1071    capacity != 0 && used.saturating_mul(2) <= capacity
1072}
1073
1074// ============================================================================
1075// Issue 1190 — the arena model is an UPPER BOUND, asserted where the sizes are
1076// ============================================================================
1077//
1078// `nros-node/build.rs` sums a per-kind cost model into `ARENA_SIZE` and says of
1079// itself that subscription and service entries are "strictly smaller" than the
1080// action-client slot it budgets at. That sentence was false for four phases:
1081// the pub/sub term charged `3 * rx_buf + 512`, which is a `TripleBuffer` (the
1082// `depth <= 1` case) plus an entry allowance smaller than any entry this crate
1083// defines, while an ordinary `KEEP_LAST(10)` subscription claims
1084// `size_of(entry) + (depth + 1) * (slot + 8)`. Measured live: 12,144 bytes into
1085// an 8,192-byte arena, dying at `Node::register` with `BufferTooSmall`.
1086//
1087// A build script cannot check this. It has no `size_of`, and the dominant term
1088// is the BACKEND's handle — 584 bytes of `CffiSubscription`, most of it two
1089// 256-byte name buffers — which is a fact of the linked backend, not of the
1090// build script's environment. So the model is emitted (`config::arena_model`)
1091// and bounded HERE, per image, per backend, at compile time.
1092//
1093// Gated on `rmw-cffi` because that is the configuration a real image is built
1094// in. The unit-test configuration substitutes `MockSubscriber`, whose 8-deep
1095// queue of 256-byte canned takes makes it ~2.1 KiB — a test fixture, not a
1096// handle any image links, and sizing the model to cover it would spend 1.4 KiB
1097// of every slot on a mock. The depth half of the model is backend-independent
1098// and is checked in the unit tests below, which do run in that configuration.
1099#[cfg(feature = "rmw-cffi")]
1100const _: () = {
1101    use crate::config::arena_model as model;
1102
1103    // The buffered subscription entries. `<(), ()>` and the C entries carry no
1104    // user closure, so this bounds the STRUCT the crate owns plus the backend
1105    // handle; a caller's own callback is captured by value on top of it and is
1106    // the one part no static bound can reach (`PUBSUB_STRUCT` is sized to leave
1107    // room for the declarative runtime's, which is the largest in this tree).
1108    // issue 1190
1109    assert!(
1110        core::mem::size_of::<SubBufferedEntry<(), ()>>() <= model::PUBSUB_STRUCT,
1111        "arena model: PUBSUB_STRUCT is below size_of::<SubBufferedEntry>() for \
1112         this backend — the derived arena would under-size every subscription. \
1113         Raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs."
1114    );
1115    // issue 1190
1116    assert!(
1117        core::mem::size_of::<SubBufferedRawEntry<()>>() <= model::PUBSUB_STRUCT,
1118        "arena model: PUBSUB_STRUCT is below size_of::<SubBufferedRawEntry>() \
1119         for this backend: raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs."
1120    );
1121    // issue 1190
1122    assert!(
1123        core::mem::size_of::<SubBufferedRawCEntry>() <= model::PUBSUB_STRUCT,
1124        "arena model: PUBSUB_STRUCT is below size_of::<SubBufferedRawCEntry>() \
1125         for this backend: raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs."
1126    );
1127    // issue 1190
1128    assert!(
1129        core::mem::size_of::<SubBufferedTypedCEntry>() <= model::PUBSUB_STRUCT,
1130        "arena model: PUBSUB_STRUCT is below \
1131         size_of::<SubBufferedTypedCEntry>() for this backend: raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs."
1132    );
1133    // issue 1190
1134    assert!(
1135        core::mem::size_of::<SubBufferedRawInfoCEntry>() <= model::PUBSUB_STRUCT,
1136        "arena model: PUBSUB_STRUCT is below \
1137         size_of::<SubBufferedRawInfoCEntry>() for this backend: raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs."
1138    );
1139
1140    // A service server has NO trailing region: both buffers are inline and it
1141    // reaches the arena through `arena_alloc`. So the whole entry is bounded.
1142    // issue 1190
1143    assert!(
1144        core::mem::size_of::<
1145            SrvRawEntry<
1146                { crate::config::DEFAULT_RX_BUF_SIZE },
1147                { crate::config::DEFAULT_RX_BUF_SIZE },
1148            >,
1149        >() <= model::SERVICE_ENTRY,
1150        "arena model: SERVICE_ENTRY is below size_of::<SrvRawEntry>() for this \
1151         backend: raise SERVICE_ENTRY_STRUCT in nros-node/build.rs."
1152    );
1153
1154    // A timer has no buffer at all.
1155    // issue 1190
1156    assert!(
1157        core::mem::size_of::<TimerEntry<()>>() <= model::TIMER_ENTRY,
1158        "arena model: TIMER_ENTRY is below size_of::<TimerEntry>(): raise TIMER_ENTRY in \
1159         nros-node/build.rs."
1160    );
1161};
1162
1163#[cfg(test)]
1164mod arena_model_tests {
1165    use crate::config::{DEFAULT_RX_BUF_SIZE, arena_model as model};
1166    use nros_rmw::QoSProfile;
1167
1168    /// Issue 1190, the failure itself. The derivation's pub/sub term must cover
1169    /// the buffered region an ORDINARY subscription claims — the one created
1170    /// with no QoS argument, which is `QoSProfile::default()`, which is
1171    /// `rmw_qos_profile_default`, which is `KEEP_LAST(10)`.
1172    ///
1173    /// This is the assertion the old model fails: it charged
1174    /// `3 * DEFAULT_RX_BUF_SIZE` = 3,072 bytes, a `TripleBuffer`, where the
1175    /// allocator claims `11 * (1024 + 8)` = 11,352 — short by 8,280 per
1176    /// subscription, on top of a 280-byte shortfall in the entry allowance. An
1177    /// image with one declared subscription therefore derived an 8,192-byte
1178    /// arena for a 12,144-byte registration.
1179    ///
1180    /// phase-454 W5 / issue 1319 — measured at the slot size the derivation
1181    /// PRICED, not at `DEFAULT_RX_BUF_SIZE`.
1182    ///
1183    /// Those were the same number until issue 1255 narrowed the term to the
1184    /// image-wide subscribed class, and this assertion went on reading `RX_BUF`
1185    /// — which made it right about the two registration paths that take the
1186    /// closure buffer and wrong about the three that do not.
1187    /// A Cyclone image priced at its bound would have failed here for sizing
1188    /// CORRECTLY. `PUBSUB_SLOT_BYTES` is what the build actually charged, and
1189    /// `the_modelled_slot_never_exceeds_the_closure_buffer` below is the other
1190    /// half — the one that says the price is an upper bound on every path.
1191    ///
1192    /// Deliberately measured through `buffered_region_size`, the function the
1193    /// allocator itself calls, and not through a second copy of its arithmetic.
1194    #[test]
1195    fn the_modelled_pubsub_region_covers_a_default_qos_subscription() {
1196        // phase-412 W3b — against the depth this image BUDGETED, not against
1197        // ROS 2's default. They are the same number until something states
1198        // otherwise, and once something does, "does the model cover a DEFAULT
1199        // subscription" stops being the question the image is asking: an image
1200        // that budgets KEEP_LAST(1) is claiming its subscriptions are
1201        // KEEP_LAST(1), and this assertion holding at depth 10 would only mean
1202        // it had over-provisioned.
1203        //
1204        // What it still catches is the thing that matters — a budget that does
1205        // not cover its own claim.
1206        let (slots, region) =
1207            super::buffered_region_size(model::BUDGETED_QOS_DEPTH, model::PUBSUB_SLOT_BYTES);
1208        assert!(
1209            model::PUBSUB_REGION >= region,
1210            "the arena derivation budgets {} bytes for a subscription's \
1211             buffered region and the allocator claims {region} for it \
1212             ({slots} slots of {} at the budgeted \
1213             KEEP_LAST({}) ) — every image that derives its arena from a \
1214             declared subscription count is short by {} bytes per \
1215             subscription (issue 1190)",
1216            model::PUBSUB_REGION,
1217            model::PUBSUB_SLOT_BYTES,
1218            model::BUDGETED_QOS_DEPTH,
1219            region.saturating_sub(model::PUBSUB_REGION),
1220        );
1221    }
1222
1223    /// **Issue 1319** — the slot the model prices may never exceed `RX_BUF`,
1224    /// because `RX_BUF` is what the widest registration path claims and the
1225    /// model is an upper bound or it is nothing.
1226    ///
1227    /// The direction that shipped the bug is the other one, and it has no
1228    /// TOTAL assertion available here: a slot priced BELOW `RX_BUF` is correct
1229    /// for a `TypedBound` registration (once ~~`c_typed_hint`~~ /
1230    /// ~~`rust_typed_descriptors`~~) and 1,848 bytes per subscription short for
1231    /// an `Unbounded` one, and which one this image
1232    /// takes is composed from the entry's language and the linked backend —
1233    /// neither of which the runtime can read out of a `cfg`. That is why the
1234    /// fact travels in the sizing descriptor and the check is on the DERIVATION
1235    /// (`nros-sizing-descriptor`'s slot table, `nros-node/build.rs`'s
1236    /// `row_slot_bytes`) rather than here. What stands here is the cheap half
1237    /// and the reproduction in `executor::tests`.
1238    ///
1239    /// Both sides go through `black_box`, for the reason `config.rs`'s
1240    /// `opaque` exists: they are build-emitted CONSTANTS, and clippy
1241    /// const-propagates the comparison and refuses the `assert!` as
1242    /// `assertions_on_constants` under `-D warnings`. A `const { assert!(…) }`
1243    /// would satisfy it and cost the message its two numbers, which are the
1244    /// whole diagnostic.
1245    #[test]
1246    fn the_modelled_slot_never_exceeds_the_closure_buffer() {
1247        fn opaque(v: usize) -> usize {
1248            core::hint::black_box(v)
1249        }
1250        assert!(
1251            opaque(model::PUBSUB_SLOT_BYTES) <= opaque(DEFAULT_RX_BUF_SIZE),
1252            "the arena model prices a subscription slot at {} bytes while the \
1253             widest registration path claims DEFAULT_RX_BUF_SIZE = \
1254             {DEFAULT_RX_BUF_SIZE} — a model term above every path it stands \
1255             for is not an upper bound, it is a second number (issue 1319)",
1256            model::PUBSUB_SLOT_BYTES,
1257        );
1258    }
1259
1260    /// The depth the derivation restates must be the depth the runtime uses. A
1261    /// build script cannot read `QOS_PROFILE_DEFAULT`, so the number is
1262    /// retyped there; this is what stops the two drifting, which is exactly how
1263    /// the term came to model a depth nothing creates.
1264    #[test]
1265    fn the_modelled_qos_depth_is_the_runtime_default() {
1266        assert_eq!(
1267            model::QOS_DEPTH,
1268            QoSProfile::default().depth,
1269            "nros-node/build.rs budgets a subscription at KEEP_LAST({}) while \
1270             `QoSProfile::default()` is KEEP_LAST({}) (issue 1190)",
1271            model::QOS_DEPTH,
1272            QoSProfile::default().depth,
1273        );
1274    }
1275
1276    /// Same, for the action client's feedback stream.
1277    #[test]
1278    fn the_modelled_action_feedback_depth_is_what_an_action_client_registers() {
1279        assert_eq!(
1280            model::ACTION_FEEDBACK_DEPTH,
1281            super::DEFAULT_ACTION_FEEDBACK_DEPTH,
1282            "nros-node/build.rs prices the action-client slot at feedback \
1283             depth {} while the registration uses {} (issue 1190)",
1284            model::ACTION_FEEDBACK_DEPTH,
1285            super::DEFAULT_ACTION_FEEDBACK_DEPTH,
1286        );
1287    }
1288
1289    /// The action-client term is left depth-blind on purpose (see
1290    /// `build.rs`), and that is only defensible while it stays an upper bound.
1291    /// Its feedback region is real and depth-scaled even though the model does
1292    /// not spell it that way, so the region alone must fit inside the term with
1293    /// the entry struct still to pay for.
1294    #[test]
1295    fn the_modelled_action_client_entry_covers_its_feedback_region() {
1296        let (_slots, region) = super::buffered_region_size(
1297            super::DEFAULT_ACTION_FEEDBACK_DEPTH as u32,
1298            DEFAULT_RX_BUF_SIZE,
1299        );
1300        assert!(
1301            model::ACTION_CLIENT_ENTRY > region,
1302            "the action-client slot is budgeted at {} bytes and its feedback \
1303             region alone claims {region} — the margin that hid issue 1190 has \
1304             closed and the term now needs the same treatment the pub/sub one \
1305             got",
1306            model::ACTION_CLIENT_ENTRY,
1307        );
1308    }
1309}
1310
1311/// Issue 0810 — every per-kind term the DECLARED model sums is held to the type
1312/// the raw C/C++ registration actually allocates, at compile time, with the
1313/// backend this image LINKS. A build script cannot see `size_of` of a backend
1314/// handle; this compilation can, so a backend whose handle grows past
1315/// `RMW_HANDLE_BOUND` — or an entry that outgrows its term — is a build error
1316/// naming the term rather than a `BufferTooSmall` at the first registration.
1317///
1318/// `rmw-cffi` is the only real `ConcreteSession`; the unit-test mock's handles
1319/// carry `Vec`s and `RefCell`s and say nothing about a target. `+ 8` is the
1320/// worst alignment pad a bump allocation pays in front of an entry.
1321#[cfg(feature = "rmw-cffi")]
1322const _: () = {
1323    use crate::config::{DEFAULT_RX_BUF_SIZE as B, arena_model as m};
1324    use core::mem::size_of;
1325    const G: usize = crate::limits::MAX_CONCURRENT_GOALS;
1326    const fn fits(actual: usize, term: usize) -> bool {
1327        actual + 8 <= term
1328    }
1329    // issue 0810
1330    assert!(
1331        size_of::<session::RmwPublisher>() <= m::RMW_HANDLE_BOUND
1332            && size_of::<session::RmwSubscriber>() <= m::RMW_HANDLE_BOUND
1333            && size_of::<session::RmwServiceServer>() <= m::RMW_HANDLE_BOUND
1334            && size_of::<session::RmwServiceClient>() <= m::RMW_HANDLE_BOUND,
1335        "an RMW handle of the linked backend exceeds RMW_HANDLE_BOUND in \
1336         nros-node/build.rs, so every declared action / service term under-prices it: raise it"
1337    );
1338    // issue 0810
1339    assert!(
1340        fits(
1341            size_of::<ActionServerRawArenaEntry<B, B, B, G>>(),
1342            m::ACTION_SERVER_ENTRY
1343        ),
1344        "ActionServerRawArenaEntry outgrew ACTION_SERVER_ENTRY: raise its term in nros-node/build.rs"
1345    );
1346    // issue 0810
1347    assert!(
1348        fits(
1349            size_of::<ActionClientRawArenaEntry<B, B, B>>(),
1350            m::ACTION_CLIENT_ENTRY
1351        ),
1352        "ActionClientRawArenaEntry outgrew ACTION_CLIENT_ENTRY: raise its term in nros-node/build.rs"
1353    );
1354    // issue 0810
1355    assert!(
1356        fits(size_of::<SrvRawEntry<B, B>>(), m::SERVICE_ENTRY),
1357        "SrvRawEntry outgrew SERVICE_ENTRY: raise its term in nros-node/build.rs"
1358    );
1359    // issue 0810
1360    assert!(
1361        fits(
1362            size_of::<ServiceClientRawArenaEntry<B>>(),
1363            m::SERVICE_CLIENT_ENTRY
1364        ),
1365        "ServiceClientRawArenaEntry outgrew SERVICE_CLIENT_ENTRY: raise its term in nros-node/build.rs"
1366    );
1367    // issue 0810
1368    assert!(
1369        fits(
1370            size_of::<GuardConditionEntry<(unsafe extern "C" fn(*mut core::ffi::c_void), usize)>>(),
1371            m::GUARD_CONDITION_ENTRY
1372        ),
1373        "GuardConditionEntry outgrew GUARD_CONDITION_ENTRY: raise its term in nros-node/build.rs"
1374    );
1375    // issue 0810
1376    assert!(
1377        fits(size_of::<SubBufferedRawCEntry>(), m::PUBSUB_STRUCT)
1378            && fits(size_of::<SubBufferedTypedCEntry>(), m::PUBSUB_STRUCT),
1379        "a C subscription entry outgrew PUBSUB_STRUCT: raise PUBSUB_ENTRY_STRUCT in nros-node/build.rs"
1380    );
1381};
1382
1383#[cfg(test)]
1384mod per_kind_term_tests {
1385    use crate::config::arena_model as model;
1386
1387    fn opaque(v: usize) -> usize {
1388        core::hint::black_box(v)
1389    }
1390
1391    /// Issue 0810 — the fallback budgets an undeclared slot at
1392    /// `WORST_SLOT_ENTRY`, which is a worst case only while it covers every
1393    /// kind a slot could turn out to be.
1394    #[test]
1395    fn the_undeclared_slot_budget_covers_every_declared_kind() {
1396        for (kind, term) in [
1397            ("subscription", model::PUBSUB_ENTRY),
1398            ("service server", model::SERVICE_ENTRY),
1399            ("service client", model::SERVICE_CLIENT_ENTRY),
1400            ("timer", model::TIMER_ENTRY),
1401            ("guard condition", model::GUARD_CONDITION_ENTRY),
1402            ("action client", model::ACTION_CLIENT_ENTRY),
1403            ("action server", model::ACTION_SERVER_ENTRY),
1404        ] {
1405            assert!(
1406                opaque(model::WORST_SLOT_ENTRY) >= opaque(term),
1407                "WORST_SLOT_ENTRY {} is below the {kind} term {term}: an undeclared \
1408                 image's per-slot budget no longer bounds what a slot can hold",
1409                model::WORST_SLOT_ENTRY
1410            );
1411        }
1412    }
1413
1414    /// Issue 0810 — the measured shape the issue was filed on, held as a
1415    /// direction rather than a literal: a declared action server costs LESS
1416    /// than the undeclared worst case (it was billed exactly that), and a
1417    /// declared service client costs something (it was billed nothing).
1418    #[test]
1419    fn declared_actions_and_service_clients_are_priced_on_their_own_terms() {
1420        assert!(opaque(model::ACTION_SERVER_ENTRY) < opaque(model::WORST_SLOT_ENTRY));
1421        assert!(opaque(model::ACTION_CLIENT_ENTRY) < opaque(model::WORST_SLOT_ENTRY));
1422        assert!(opaque(model::SERVICE_CLIENT_ENTRY) > opaque(crate::config::DEFAULT_RX_BUF_SIZE));
1423        assert!(opaque(model::GUARD_CONDITION_ENTRY) > 0);
1424    }
1425}
1426
1427#[cfg(test)]
1428mod arena_headroom_tests {
1429    use super::arena_is_over_provisioned;
1430    use crate::config::{
1431        ARENA_ACTION_CLIENTS, ARENA_SIZE, DEFAULT_RX_BUF_SIZE, MAX_CBS, arena_model as model,
1432    };
1433
1434    /// issue 0900 — the per-kind derivation must reproduce the OLD
1435    /// `max_cbs * action_client_entry + base` arithmetic byte for byte when
1436    /// every slot is still budgeted at ActionClient size, which is the default.
1437    ///
1438    /// This is the compatibility gate: the knob exists so an image CAN shrink
1439    /// its arena, not so every image silently does. A change here that moves
1440    /// the default is a change to every image's stack frame.
1441    #[test]
1442    fn the_default_derivation_is_unchanged() {
1443        if ARENA_ACTION_CLIENTS != MAX_CBS {
1444            // The test build set the knob; the identity below is not the claim
1445            // being made then. Fail rather than pass vacuously.
1446            panic!(
1447                "this test asserts the DEFAULT derivation, but \
1448                 NROS_EXECUTOR_ACTION_CLIENTS was set to {ARENA_ACTION_CLIENTS} \
1449                 against MAX_CBS {MAX_CBS}"
1450            );
1451        }
1452        // Issue 1190 — these six constants used to be RETYPED here, which is a
1453        // second copy of the model that agrees with the first until one of them
1454        // moves. They come from `config::arena_model` now, which is what
1455        // `build.rs` actually summed.
1456        // Issue 0810 — the fallback's per-slot budget is `WORST_SLOT_ENTRY`
1457        // now; `ACTION_CLIENT_ENTRY` prices a DECLARED action client.
1458        let want = (MAX_CBS * model::WORST_SLOT_ENTRY + model::BASE_OVERHEAD).max(model::FLOOR);
1459        assert_eq!(
1460            ARENA_SIZE, want,
1461            "the per-kind derivation moved the default arena; every image's \
1462             executor backing moves with it (issue 0900)"
1463        );
1464        // And the shipped number itself, because reading it out of the model
1465        // proves the SHAPE and not the size: with both sides emitted from one
1466        // build script, a term could move and the identity above would still
1467        // hold. 74,240 is what 1,524 of the 1,547 built configs in this tree
1468        // carry; issue 1190's fix is required to leave it exactly there,
1469        // because the pub/sub term it corrects multiplies
1470        // `MAX_CBS - ARENA_ACTION_CLIENTS`, which is zero at the defaults.
1471        //
1472        // Only when the INPUTS are the shipped ones. A test build that raised
1473        // `NROS_EXECUTOR_MAX_CBS` or the buffer size derives a different number
1474        // legitimately, and asserting a literal at it would be this file's own
1475        // "second copy" mistake wearing a different hat.
1476        if MAX_CBS == 4 && DEFAULT_RX_BUF_SIZE == 1024 {
1477            assert_eq!(
1478                ARENA_SIZE, 74_240,
1479                "the shipped default arena moved. That is not forbidden, but \
1480                 it is a change to every image built without an entity \
1481                 declaration and it has to be a decision, not a side effect \
1482                 (issues 0900, 1190)"
1483            );
1484        }
1485    }
1486
1487    /// The advisory must actually fire for the shipped defaults — otherwise W1
1488    /// installed a diagnostic that is dead on the very configuration that
1489    /// needs it. A timer-only executor claims 32 bytes against ARENA_SIZE.
1490    #[test]
1491    fn the_shipped_default_arena_trips_the_advisory() {
1492        assert!(
1493            arena_is_over_provisioned(32, ARENA_SIZE),
1494            "a timer-only executor must trip the advisory at the shipped \
1495             defaults; ARENA_SIZE is {ARENA_SIZE}"
1496        );
1497    }
1498
1499    #[test]
1500    fn gross_over_provision_is_reported() {
1501        // The measured shape: a talker's handful of entries against the
1502        // worst-case-derived 74,240.
1503        assert!(arena_is_over_provisioned(4_096, 74_240));
1504        assert!(arena_is_over_provisioned(0, 74_240));
1505    }
1506
1507    #[test]
1508    fn a_well_sized_arena_stays_quiet() {
1509        assert!(!arena_is_over_provisioned(60_000, 74_240));
1510        // Exactly half is the boundary and IS reported; one byte more is not.
1511        assert!(arena_is_over_provisioned(37_120, 74_240));
1512        assert!(!arena_is_over_provisioned(37_121, 74_240));
1513    }
1514
1515    #[test]
1516    fn a_zero_capacity_arena_is_a_fault_not_headroom() {
1517        // Issue 0460's sentinel bug. It fails on the first registration; an
1518        // advisory about wasted space would bury that.
1519        assert!(!arena_is_over_provisioned(0, 0));
1520    }
1521
1522    #[test]
1523    fn overflow_cannot_panic_the_check() {
1524        // `used` is bounded by `capacity` in practice, but the doubling must
1525        // not be the thing that decides that.
1526        assert!(!arena_is_over_provisioned(usize::MAX, 74_240));
1527    }
1528}
1529
1530/// Say that a take was thrown away, on the first one and every 64th after.
1531///
1532/// Issue 0757, RFC-0052 fail-loud. `take_serialized` returns `BufferTooSmall` when
1533/// a reassembled sample exceeds the subscription buffer, and this path used to
1534/// discard EVERY non-OK take. At transport level cyclone has already completed
1535/// and ACKed the sample by then, so the subscription looks matched and healthy
1536/// from every outside probe (`ros2 topic info -v`, tshark ACKNACK analysis)
1537/// while the application waits forever. That is how 13.4 KiB Autoware
1538/// trajectories were silently dropped by every Zephyr image for the whole life
1539/// of the lane: small degenerate samples fit the 1 KiB default, so every green
1540/// marker stayed green, and attribution needed a consumer-side tshark session.
1541///
1542/// **What this can and cannot say.** The buffer capacity is known here and is
1543/// the actionable half — it names the knob to raise
1544/// (`NROS_EXECUTOR_SUBSCRIPTION_BUFFER_BYTES`, or `NROS_SUBSCRIBER_BUFFER_BYTES` /
1545/// `ZPICO_SUBSCRIBER_LARGE_SIZE` on zenoh). The SAMPLE size is known when the
1546/// backend knows it: issue 1612 made a too-small `take` carry the size the
1547/// sample needed (`rmw_entity.h`), which reaches here as
1548/// `Subscription::refused_sample_len`, and issue 1632 made this line print it
1549/// beside the buffer (`?` when unknown — `nros_rmw::RefusedLen`'s rule, which
1550/// the C++ drop log shares). The topic is still not known: `SubBufferedEntry`
1551/// carries no name and adding one changes arena sizing.
1552///
1553/// `nros_log`, never stdio: this site is reached on `no_std` targets and inside
1554/// Zephyr `native_sim`, where a Rust `std` stdio call is FATAL (issue 0589).
1555/// `take_serialized`, with a refusal reported through [`report_dropped_take`]
1556/// together with the size the backend says the sample needed — the one
1557/// spelling of the five buffered drain sites.
1558fn take_reporting_drop(
1559    handle: &mut session::RmwSubscriber,
1560    slot: &mut [u8],
1561) -> Result<Option<usize>, TransportError> {
1562    let cap = slot.len();
1563    handle.take_serialized(slot).inspect_err(|e| {
1564        report_dropped_take(e, cap, handle.refused_sample_len());
1565    })
1566}
1567
1568#[cold]
1569fn report_dropped_take(err: &TransportError, buf_len: usize, recorded: Option<usize>) {
1570    let n = DROPPED_TAKES.fetch_add(1, portable_atomic::Ordering::Relaxed);
1571    if drop_is_reported(n) {
1572        log_dropped_take(err, buf_len, recorded, n);
1573    }
1574}
1575
1576/// First, then every 64th. A 40-participant graph must not turn one
1577/// misconfigured subscription into a log flood (issue 0371's shape).
1578///
1579/// Apart from [`report_dropped_take`] so a test asks it with a count of its
1580/// own, never through [`DROPPED_TAKES`], which every cell in the binary that
1581/// drops a take advances (issue 2082).
1582fn drop_is_reported(n: u32) -> bool {
1583    n == 0 || n.is_multiple_of(64)
1584}
1585
1586/// The line for drop number `n + 1`, unconditionally.
1587#[cold]
1588fn log_dropped_take(err: &TransportError, buf_len: usize, recorded: Option<usize>, n: u32) {
1589    let needed = nros_rmw::RefusedLen::for_error(err, recorded);
1590    // issue 0757
1591    nros_log::log_error!(
1592        nros_log::get_logger("nros"),
1593        "subscription take DROPPED ({err:?}): {needed}-byte sample, {buf_len}-byte \
1594         buffer. Received and ACKed, then discarded — raise the subscription \
1595         buffer knob if this is BufferTooSmall. Dropped {} so far",
1596        n + 1
1597    );
1598}
1599
1600unsafe fn drain_into_buffer<M, F>(
1601    entry: &mut SubBufferedEntry<M, F>,
1602) -> Result<(), TransportError> {
1603    match &entry.buffer {
1604        BufferStrategy::Triple(tb) => {
1605            let slot = tb.write_slot();
1606            if let Some(len) = take_reporting_drop(&mut entry.handle, slot)? {
1607                tb.writer_publish(len);
1608            }
1609        }
1610        BufferStrategy::Ring(ring) => {
1611            while let Some(slot) = ring.try_push() {
1612                match take_reporting_drop(&mut entry.handle, slot)? {
1613                    Some(len) => ring.commit_push(len),
1614                    None => break,
1615                }
1616            }
1617        }
1618    }
1619    Ok(())
1620}
1621
1622/// Monomorphized dispatch for buffered subscriptions.
1623///
1624/// First drains the RMW subscriber into the buffer strategy (triple buffer
1625/// or SPSC ring), then dispatches from the buffer to the user callback.
1626///
1627/// # Safety
1628/// `ptr` must point to a valid, aligned `SubBufferedEntry<M, F>`.
1629pub(crate) unsafe fn sub_buffered_try_process<M, F>(
1630    ptr: *mut u8,
1631    _delta_us: u64,
1632    desc_idx: u8,
1633) -> Result<bool, TransportError>
1634where
1635    M: RosMessage,
1636    F: FnMut(&M),
1637{
1638    let entry = unsafe { &mut *(ptr as *mut SubBufferedEntry<M, F>) };
1639
1640    // Phase 1: drain RMW subscriber → buffer strategy
1641    // Issue 0757 — let a transport error OUT, exactly as issue 0737 does for
1642    // the C copy below. Anything already buffered from an earlier spin is still
1643    // dispatched on the next call.
1644    unsafe { drain_into_buffer(entry)? };
1645
1646    // Phase 2: dispatch from buffer → user callback
1647    match &entry.buffer {
1648        // Phase 8 — hooked. Triple-buffered: at most one invocation per
1649        // `try_process`, and none at all when `reader_acquire` is empty.
1650        // The two deserialization `?`s sit BEFORE the start hook, so a
1651        // malformed sample returns early without opening a span.
1652        BufferStrategy::Triple(tb) => match tb.reader_acquire() {
1653            Some((data, len)) => {
1654                observe_age::<M>(&data[..len], &entry.age_mon);
1655                let mut reader = CdrReader::new_with_header(&data[..len])
1656                    .map_err(|_| TransportError::DeserializationError)?;
1657                let msg = M::deserialize(&mut reader)
1658                    .map_err(|_| TransportError::DeserializationError)?;
1659                trace_take(desc_idx, &data[..len], <M as RosMessage>::STAMP_OFFSET);
1660                trace_cb_start(desc_idx);
1661                (entry.callback)(&msg);
1662                trace_cb_end(desc_idx);
1663                Ok(true)
1664            }
1665            None => Ok(false),
1666        },
1667        // Phase 8 — hooked INSIDE the loop: a ring drains N queued messages
1668        // per `try_process` and fires the callback once per message, so N
1669        // messages must produce N spans, not one.
1670        BufferStrategy::Ring(ring) => {
1671            let mut did_work = false;
1672            while let Some((data, len)) = ring.try_pop() {
1673                observe_age::<M>(&data[..len], &entry.age_mon);
1674                let mut reader = CdrReader::new_with_header(&data[..len])
1675                    .map_err(|_| TransportError::DeserializationError)?;
1676                let msg = M::deserialize(&mut reader)
1677                    .map_err(|_| TransportError::DeserializationError)?;
1678                trace_take(desc_idx, &data[..len], <M as RosMessage>::STAMP_OFFSET);
1679                trace_cb_start(desc_idx);
1680                (entry.callback)(&msg);
1681                trace_cb_end(desc_idx);
1682                ring.commit_pop();
1683                did_work = true;
1684            }
1685            Ok(did_work)
1686        }
1687    }
1688}
1689
1690/// Readiness check for buffered subscriptions.
1691///
1692/// Checks the RMW subscriber handle first (new data available from transport),
1693/// then the buffer strategy (data already drained into triple buffer/ring).
1694///
1695/// # Safety
1696/// `ptr` must point to a valid `SubBufferedEntry<M, F>`.
1697pub(crate) unsafe fn sub_buffered_has_data<M, F>(ptr: *const u8) -> bool {
1698    let entry = unsafe { &*(ptr as *const SubBufferedEntry<M, F>) };
1699    // Check RMW handle first (data may be in static buffer, not yet drained)
1700    entry.handle.has_data() || entry.buffer.has_data()
1701}
1702
1703// ============================================================================
1704// In-place typed subscription (Phase 231 Wave 0.2 — RFC-0038)
1705// ============================================================================
1706
1707/// The most samples ONE in-place dispatch takes before it returns (issue 1956).
1708///
1709/// An in-place entry reads the backend's receive ring directly, and that ring
1710/// is refilled by a transport task that may run at a HIGHER priority than the
1711/// executor. "Drain until empty" was then unbounded: under a flood the check
1712/// for "empty" never came true, one `try_process` never returned, and no other
1713/// entry on the executor (or any lower sched task on the core) ran again. The
1714/// buffered shapes never had this — they drain what was copied in.
1715///
1716/// Why 64 and not 1: every sample that was in the ring when the dispatch began
1717/// should be taken in it, because one left behind waits for the NEXT spin, and
1718/// a spin parks until something wakes it. A sample that ARRIVES during the
1719/// dispatch raises that wake itself, so leaving it costs nothing. 64 covers
1720/// every shipped ring depth (zenoh's default is 4) with room; a ring
1721/// configured deeper still makes progress, a spin at a time.
1722pub(crate) const IN_PLACE_DRAIN_LIMIT: usize = 64;
1723
1724/// Run one in-place `step` (one `process_raw_in_place`) until it reports no
1725/// sample or [`IN_PLACE_DRAIN_LIMIT`] samples have been taken. The one
1726/// spelling of the in-place drain, so no shape can fall back to "until
1727/// empty". Returns whether any sample was dispatched.
1728#[inline]
1729pub(crate) fn drain_in_place(
1730    mut step: impl FnMut() -> Result<bool, TransportError>,
1731) -> Result<bool, TransportError> {
1732    let mut did_work = false;
1733    for _ in 0..IN_PLACE_DRAIN_LIMIT {
1734        if !step()? {
1735            break;
1736        }
1737        did_work = true;
1738    }
1739    Ok(did_work)
1740}
1741
1742/// In-place typed subscription entry — **no arena buffer**.
1743///
1744/// Unlike [`SubBufferedEntry`], this carries no trailing `BufferStrategy`: the
1745/// callback deserializes directly from the backend's borrowed receive slot via
1746/// [`Subscriber::process_raw_in_place`], so copy #1 (ring → arena) and the arena
1747/// buffer are both gone. Selected at registration when the backend advertises
1748/// `supports_process_in_place()`.
1749#[repr(C)]
1750pub(crate) struct SubInplaceEntry<M, F> {
1751    pub(crate) handle: session::RmwSubscriber,
1752    pub(crate) callback: F,
1753    /// W3b.5 — age hook for contracted endpoints.
1754    pub(crate) age_mon: Option<AgeMon>,
1755    pub(crate) _phantom: PhantomData<M>,
1756}
1757
1758/// Monomorphized in-place dispatch for typed subscriptions.
1759///
1760/// Drains pending messages from the backend, up to [`IN_PLACE_DRAIN_LIMIT`],
1761/// deserializing + invoking the callback directly from each borrowed slot. Returns `Ok(true)` if any message
1762/// was dispatched.
1763///
1764/// # Safety
1765/// `ptr` must point to a valid, aligned `SubInplaceEntry<M, F>`.
1766pub(crate) unsafe fn sub_inplace_try_process<M, F>(
1767    ptr: *mut u8,
1768    _delta_us: u64,
1769    desc_idx: u8,
1770) -> Result<bool, TransportError>
1771where
1772    M: RosMessage,
1773    F: FnMut(&M),
1774{
1775    let entry = unsafe { &mut *(ptr as *mut SubInplaceEntry<M, F>) };
1776    // Split-borrow the handle and callback (disjoint fields).
1777    let SubInplaceEntry {
1778        handle,
1779        callback,
1780        age_mon,
1781        ..
1782    } = entry;
1783    drain_in_place(|| {
1784        let mut deser_err = false;
1785        // Phase 8 — hooked inside the `Ok(msg)` arm of the borrow closure,
1786        // which the drain loop re-enters once per pending message: N
1787        // messages therefore produce N spans. The pair is fully contained
1788        // in the closure, so the `?` on `process_raw_in_place` below can
1789        // never fire between a start and its end. Deserialization failures
1790        // take the `deser_err` arms and emit nothing.
1791        let processed = handle.process_raw_in_place(|raw| {
1792            observe_age::<M>(raw, age_mon);
1793            match CdrReader::new_with_header(raw) {
1794                Ok(mut reader) => match M::deserialize(&mut reader) {
1795                    Ok(msg) => {
1796                        trace_take(desc_idx, raw, <M as RosMessage>::STAMP_OFFSET);
1797                        trace_cb_start(desc_idx);
1798                        (callback)(&msg);
1799                        trace_cb_end(desc_idx);
1800                    }
1801                    Err(_) => deser_err = true,
1802                },
1803                Err(_) => deser_err = true,
1804            }
1805        })?;
1806        if deser_err {
1807            return Err(TransportError::DeserializationError);
1808        }
1809        Ok(processed)
1810    })
1811}
1812
1813#[cfg(test)]
1814mod in_place_drain_tests {
1815    use super::*;
1816
1817    /// Issue 1956 — a ring a higher-priority task keeps refilling is never
1818    /// empty at the check. The drain has to come back anyway.
1819    #[test]
1820    fn a_ring_that_never_empties_still_returns() {
1821        let mut taken = 0usize;
1822        let r = drain_in_place(|| {
1823            taken += 1;
1824            Ok(true)
1825        });
1826        assert_eq!(r, Ok(true));
1827        assert_eq!(taken, IN_PLACE_DRAIN_LIMIT);
1828    }
1829
1830    #[test]
1831    fn an_emptied_ring_stops_the_drain_early() {
1832        let mut left = 3usize;
1833        let mut calls = 0usize;
1834        let r = drain_in_place(|| {
1835            calls += 1;
1836            Ok(if left == 0 {
1837                false
1838            } else {
1839                left -= 1;
1840                true
1841            })
1842        });
1843        assert_eq!(r, Ok(true));
1844        assert_eq!(calls, 4, "three samples, then the empty check");
1845        assert_eq!(drain_in_place(|| Ok(false)), Ok(false));
1846    }
1847
1848    #[test]
1849    fn a_failed_take_ends_the_drain_with_its_error() {
1850        let mut calls = 0usize;
1851        let r = drain_in_place(|| {
1852            calls += 1;
1853            if calls == 2 {
1854                Err(TransportError::DeserializationError)
1855            } else {
1856                Ok(true)
1857            }
1858        });
1859        assert_eq!(r, Err(TransportError::DeserializationError));
1860        assert_eq!(calls, 2);
1861    }
1862}
1863
1864/// Readiness check for in-place typed subscriptions.
1865///
1866/// # Safety
1867/// `ptr` must point to a valid `SubInplaceEntry<M, F>`.
1868pub(crate) unsafe fn sub_inplace_has_data<M, F>(ptr: *const u8) -> bool {
1869    let entry = unsafe { &*(ptr as *const SubInplaceEntry<M, F>) };
1870    entry.handle.has_data()
1871}
1872
1873// ============================================================================
1874// Zero-copy raw buffered subscription (Phase 73.10)
1875// ============================================================================
1876
1877/// Buffered subscription entry for zero-copy raw callbacks.
1878///
1879/// The callback receives `&[u8]` (CDR data) borrowing directly from the
1880/// triple buffer's read slot or SPSC ring's pop slot. For borrowed message
1881/// types (e.g., `Image<'a>`), the callback calls `deserialize_view()`
1882/// on the data, giving the message a lifetime tied to the callback scope.
1883#[repr(C)]
1884pub(crate) struct SubBufferedRawEntry<F> {
1885    pub(crate) handle: session::RmwSubscriber,
1886    pub(crate) buffer: BufferStrategy,
1887    pub(crate) callback: F,
1888}
1889
1890/// Drain helper for raw buffered entries.
1891///
1892/// Issue 0757 — the THIRD copy of this drain, and it had the same swallow as
1893/// the typed one above. Fixed the way issue 0737 fixed the C copy
1894/// (`drain_into_buffer_raw_c`): let the error OUT so `spin_once` counts it,
1895/// rather than inventing a second remedy for one defect.
1896unsafe fn drain_into_buffer_raw<F>(
1897    entry: &mut SubBufferedRawEntry<F>,
1898) -> Result<(), TransportError> {
1899    match &entry.buffer {
1900        BufferStrategy::Triple(tb) => {
1901            let slot = tb.write_slot();
1902            if let Some(len) = take_reporting_drop(&mut entry.handle, slot)? {
1903                tb.writer_publish(len);
1904            }
1905        }
1906        BufferStrategy::Ring(ring) => {
1907            while let Some(slot) = ring.try_push() {
1908                match take_reporting_drop(&mut entry.handle, slot)? {
1909                    Some(len) => ring.commit_push(len),
1910                    None => break,
1911                }
1912            }
1913        }
1914    }
1915    Ok(())
1916}
1917
1918/// Dispatch for zero-copy raw buffered subscriptions.
1919///
1920/// Drains the RMW handle into the buffer, then passes the raw CDR slice
1921/// to the callback. The callback borrows from the buffer slot — no copy.
1922///
1923/// # Safety
1924/// `ptr` must point to a valid, aligned `SubBufferedRawEntry<F>`.
1925pub(crate) unsafe fn sub_buffered_raw_try_process<F>(
1926    ptr: *mut u8,
1927    _delta_us: u64,
1928    desc_idx: u8,
1929) -> Result<bool, TransportError>
1930where
1931    F: FnMut(&[u8]),
1932{
1933    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawEntry<F>) };
1934
1935    // Issue 0757 — see `drain_into_buffer`; the error reaches `spin_once`'s
1936    // `subscription_errors` instead of vanishing.
1937    unsafe { drain_into_buffer_raw(entry)? };
1938
1939    match &entry.buffer {
1940        // Phase 8 — hooked. Triple-buffered: one invocation per
1941        // `try_process` at most, none when `reader_acquire` is empty.
1942        BufferStrategy::Triple(tb) => match tb.reader_acquire() {
1943            Some((data, len)) => {
1944                trace_take(desc_idx, &data[..len], None);
1945                trace_cb_start(desc_idx);
1946                (entry.callback)(&data[..len]);
1947                trace_cb_end(desc_idx);
1948                Ok(true)
1949            }
1950            None => Ok(false),
1951        },
1952        // Phase 8 — hooked INSIDE the loop: one span per drained message,
1953        // not one per `try_process`.
1954        BufferStrategy::Ring(ring) => {
1955            let mut did_work = false;
1956            while let Some((data, len)) = ring.try_pop() {
1957                trace_take(desc_idx, &data[..len], None);
1958                trace_cb_start(desc_idx);
1959                (entry.callback)(&data[..len]);
1960                trace_cb_end(desc_idx);
1961                ring.commit_pop();
1962                did_work = true;
1963            }
1964            Ok(did_work)
1965        }
1966    }
1967}
1968
1969/// Readiness check for raw buffered subscriptions.
1970///
1971/// # Safety
1972/// `ptr` must point to a valid `SubBufferedRawEntry<F>`.
1973pub(crate) unsafe fn sub_buffered_raw_has_data<F>(ptr: *const u8) -> bool {
1974    let entry = unsafe { &*(ptr as *const SubBufferedRawEntry<F>) };
1975    entry.handle.has_data() || entry.buffer.has_data()
1976}
1977
1978// ============================================================================
1979// Borrowed (zero-copy) buffered subscription (Phase 229.6, issue 0007)
1980// ============================================================================
1981
1982/// Buffered subscription entry for borrowed (zero-copy) message callbacks.
1983///
1984/// The callback receives `&B::View<'a>` — a lifetime-carrying message whose
1985/// unbounded sequence/string fields borrow directly from the triple buffer's
1986/// read slot (no arena copy, no `heapless::Vec` copy). The view is materialised
1987/// per dispatch via [`DeserializeView`] and dropped before the slot is
1988/// released, so the borrow never outlives the buffer.
1989///
1990/// **Triple-buffer only.** A borrowed view must reference exactly one
1991/// well-defined slot for the duration of the callback; an SPSC ring (depth > 1)
1992/// holds several samples in flight with no single such slot. Registration
1993/// rejects `qos.depth > 1` for borrowed subscriptions, so `buffer` is always
1994/// [`BufferStrategy::Triple`] here.
1995#[repr(C)]
1996pub(crate) struct SubBufferedViewEntry<B, F> {
1997    pub(crate) handle: session::RmwSubscriber,
1998    pub(crate) buffer: BufferStrategy,
1999    pub(crate) callback: F,
2000    pub(crate) _phantom: PhantomData<B>,
2001}
2002
2003/// Dispatch for borrowed (zero-copy) buffered subscriptions.
2004///
2005/// Drains the RMW handle into the triple buffer, then materialises a borrowed
2006/// `B::View<'_>` over the read slot and hands it to the callback. The view
2007/// borrows the slot; it is dropped at the end of the callback, before the next
2008/// dispatch can publish over the slot.
2009///
2010/// # Safety
2011/// `ptr` must point to a valid, aligned `SubBufferedViewEntry<B, F>`.
2012pub(crate) unsafe fn sub_buffered_view_try_process<B, F>(
2013    ptr: *mut u8,
2014    _delta_us: u64,
2015    desc_idx: u8,
2016) -> Result<bool, TransportError>
2017where
2018    B: ViewableMessage,
2019    F: for<'a> FnMut(&B::View<'a>),
2020{
2021    let entry = unsafe { &mut *(ptr as *mut SubBufferedViewEntry<B, F>) };
2022
2023    // Borrowed subscriptions are triple-buffer only (enforced at registration).
2024    let tb = match &entry.buffer {
2025        BufferStrategy::Triple(tb) => tb,
2026        // Unreachable: registration rejects depth > 1. Treat as no work.
2027        BufferStrategy::Ring(_) => return Ok(false),
2028    };
2029
2030    // Phase 1: drain RMW subscriber → triple buffer write slot.
2031    //
2032    // Issue 0757 — the FOURTH copy of this drain (the borrowed/zero-copy path)
2033    // and it swallowed non-OK takes like the others. Same remedy as issue 0737's
2034    // C copy: report the actionable size, then let the error out.
2035    {
2036        let slot = tb.write_slot();
2037        if let Some(len) = take_reporting_drop(&mut entry.handle, slot)? {
2038            tb.writer_publish(len);
2039        }
2040    }
2041
2042    // Phase 2: borrow the read slot and deserialize a view over it (no copy).
2043    //
2044    // Phase 8 — hooked. Exactly ONE site: the `BufferStrategy::Ring(_)` arm
2045    // above returns `Ok(false)` without ever reaching a callback (borrowed
2046    // subscriptions are triple-buffer only, enforced at registration), so it
2047    // gets no pair. Both `?`s land before the start hook.
2048    match tb.reader_acquire() {
2049        Some((data, len)) => {
2050            let mut reader = CdrReader::new_with_header(&data[..len])
2051                .map_err(|_| TransportError::DeserializationError)?;
2052            let msg = <B::View<'_> as DeserializeView>::deserialize_view(&mut reader)
2053                .map_err(|_| TransportError::DeserializationError)?;
2054            trace_take(desc_idx, &data[..len], None);
2055            trace_cb_start(desc_idx);
2056            (entry.callback)(&msg);
2057            trace_cb_end(desc_idx);
2058            Ok(true)
2059        }
2060        None => Ok(false),
2061    }
2062}
2063
2064/// Readiness check for borrowed buffered subscriptions.
2065///
2066/// # Safety
2067/// `ptr` must point to a valid `SubBufferedViewEntry<B, F>`.
2068pub(crate) unsafe fn sub_buffered_view_has_data<B, F>(ptr: *const u8) -> bool {
2069    let entry = unsafe { &*(ptr as *const SubBufferedViewEntry<B, F>) };
2070    entry.handle.has_data() || entry.buffer.has_data()
2071}
2072
2073// ============================================================================
2074// Raw buffered subscription with attachment / MessageInfo (Phase 189.M1)
2075// ============================================================================
2076
2077/// Staging cap for a raw subscription's wire attachment (bridge_origin
2078/// tags and similar are small). Attachment bytes longer than this are
2079/// truncated by the backend's `take_serialized_with_attachment`.
2080pub(crate) const RAW_INFO_ATT_CAP: usize = 256;
2081
2082/// Raw buffered subscription entry that surfaces the sample's wire
2083/// attachment as a [`RawMessageInfo`] to the callback
2084/// (`FnMut(&[u8], &RawMessageInfo)`).
2085///
2086/// Unlike [`SubBufferedRawEntry`] (Triple/Ring `BufferStrategy`), this
2087/// uses a flat inline payload buffer + a flat attachment buffer so the
2088/// attachment travels with its message — the decoupled producer/consumer
2089/// slots of a triple/ring buffer cannot carry per-message side data.
2090/// One sample per dispatch (mirrors [`SubInfoEntry`]).
2091#[repr(C)]
2092pub(crate) struct SubBufferedRawInfoEntry<F> {
2093    pub(crate) handle: session::RmwSubscriber,
2094    /// Issue 1860 / phase-498 W1 -- the receive slot, in the arena's trailing
2095    /// region and sized at registration (from the type's bound when the
2096    /// caller names none), as `SubBufferedRawInfoCEntry` has been since
2097    /// phase-408 W5b. It was an inline `[u8; RX_BUF]`, so every entry of this
2098    /// shape reserved the image's closure maximum whatever its own type was.
2099    pub(crate) buffer: TrailingBuf,
2100    pub(crate) att: [u8; RAW_INFO_ATT_CAP],
2101    pub(crate) callback: F,
2102}
2103
2104/// Dispatch for raw buffered subscriptions with attachment.
2105///
2106/// # Safety
2107/// `ptr` must point to a valid, aligned `SubBufferedRawInfoEntry<F>`.
2108pub(crate) unsafe fn sub_buffered_raw_info_try_process<F>(
2109    ptr: *mut u8,
2110    _delta_us: u64,
2111    desc_idx: u8,
2112) -> Result<bool, TransportError>
2113where
2114    F: FnMut(&[u8], &RawMessageInfo),
2115{
2116    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawInfoEntry<F>) };
2117    // Issue 2712 -- one take for the metadata AND the attachment. The
2118    // attachment-only take left `RawMessageInfo`'s metadata at its default,
2119    // so every field read zero.
2120    match entry
2121        .handle
2122        .take_serialized_with_info_and_attachment(entry.buffer.as_mut_slice(), &mut entry.att)
2123    {
2124        // Phase 8 — hooked. One sample per dispatch (flat inline buffer, no
2125        // ring), so exactly one pair. `Ok(None)` and `Err(_)` never reach a
2126        // callback and stay bare.
2127        Ok(Some((len, meta, att_len))) => {
2128            let info = RawMessageInfo::with_info(meta.unwrap_or_default(), &entry.att[..att_len]);
2129            trace_take(desc_idx, &entry.buffer.as_slice()[..len], None);
2130            trace_cb_start(desc_idx);
2131            (entry.callback)(&entry.buffer.as_slice()[..len], &info);
2132            trace_cb_end(desc_idx);
2133            Ok(true)
2134        }
2135        Ok(None) => Ok(false),
2136        Err(_) => Err(TransportError::DeserializationError),
2137    }
2138}
2139
2140/// Readiness check for raw buffered subscriptions with attachment.
2141///
2142/// # Safety
2143/// `ptr` must point to a valid `SubBufferedRawInfoEntry<F>`.
2144pub(crate) unsafe fn sub_buffered_raw_info_has_data<F>(ptr: *const u8) -> bool {
2145    let entry = unsafe { &*(ptr as *const SubBufferedRawInfoEntry<F>) };
2146    entry.handle.has_data()
2147}
2148
2149/// Issue 2036 — raw buffered subscription whose closure receives the sample's
2150/// [`MessageInfo`] (`take_serialized_with_info`): the timestamps, sequence
2151/// numbers and publisher gid a backend reports, or `None` from one that
2152/// reports none. The raw twin of [`SubInfoEntry`], for a caller that
2153/// deserializes itself — the C++ `(const M&, const rclcpp::MessageInfo&)`
2154/// subscription callback. [`SubBufferedRawInfoEntry`] carries the
2155/// ATTACHMENT bytes as well, beside the same metadata.
2156#[repr(C)]
2157pub(crate) struct SubBufferedRawMsgInfoEntry<F> {
2158    pub(crate) handle: session::RmwSubscriber,
2159    /// The receive slot, in the arena's trailing region, sized at registration.
2160    pub(crate) buffer: TrailingBuf,
2161    pub(crate) callback: F,
2162}
2163
2164/// Dispatch for [`SubBufferedRawMsgInfoEntry`]: one sample per call.
2165///
2166/// # Safety
2167/// `ptr` must point to a valid, aligned `SubBufferedRawMsgInfoEntry<F>`.
2168pub(crate) unsafe fn sub_buffered_raw_msg_info_try_process<F>(
2169    ptr: *mut u8,
2170    _delta_us: u64,
2171    desc_idx: u8,
2172) -> Result<bool, TransportError>
2173where
2174    F: FnMut(&[u8], Option<&MessageInfo>),
2175{
2176    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawMsgInfoEntry<F>) };
2177    match entry
2178        .handle
2179        .take_serialized_with_info(entry.buffer.as_mut_slice())
2180    {
2181        // Phase 8 — hooked, one pair per sample, as the other raw entries.
2182        Ok(Some((len, info))) => {
2183            trace_take(desc_idx, &entry.buffer.as_slice()[..len], None);
2184            trace_cb_start(desc_idx);
2185            (entry.callback)(&entry.buffer.as_slice()[..len], info.as_ref());
2186            trace_cb_end(desc_idx);
2187            Ok(true)
2188        }
2189        Ok(None) => Ok(false),
2190        Err(_) => Err(TransportError::DeserializationError),
2191    }
2192}
2193
2194/// Readiness check for [`SubBufferedRawMsgInfoEntry`].
2195///
2196/// # Safety
2197/// `ptr` must point to a valid `SubBufferedRawMsgInfoEntry<F>`.
2198pub(crate) unsafe fn sub_buffered_raw_msg_info_has_data<F>(ptr: *const u8) -> bool {
2199    let entry = unsafe { &*(ptr as *const SubBufferedRawMsgInfoEntry<F>) };
2200    entry.handle.has_data()
2201}
2202
2203/// C-style (fn-ptr + context) raw buffered subscription with attachment
2204/// (Phase 189.M3.4 — the C analog of [`SubBufferedRawInfoEntry`]). Flat
2205/// payload + attachment buffers, one sample per dispatch.
2206///
2207/// phase-408 W5b — the payload slot is a [`TrailingBuf`] in the arena's
2208/// trailing region rather than an inline `[u8; RX_BUF]`, so the registering
2209/// caller's `rx_buffer_hint` sizes the ALLOCATION and not just the backend's
2210/// payload size class. The attachment stays inline and fixed
2211/// ([`RAW_INFO_ATT_CAP`]): it is small, and it is the thing that has to travel
2212/// with its message.
2213#[repr(C)]
2214pub(crate) struct SubBufferedRawInfoCEntry {
2215    pub(crate) handle: session::RmwSubscriber,
2216    pub(crate) buffer: TrailingBuf,
2217    pub(crate) att: [u8; RAW_INFO_ATT_CAP],
2218    pub(crate) callback: RawSubscriptionInfoCallback,
2219    pub(crate) context: *mut core::ffi::c_void,
2220}
2221
2222/// Dispatch for the C-style raw buffered subscription with attachment.
2223///
2224/// # Safety
2225/// `ptr` must point to a valid, aligned `SubBufferedRawInfoCEntry`.
2226pub(crate) unsafe fn sub_buffered_raw_info_c_try_process(
2227    ptr: *mut u8,
2228    _delta_us: u64,
2229    desc_idx: u8,
2230) -> Result<bool, TransportError> {
2231    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawInfoCEntry) };
2232    let payload = entry.buffer.as_mut_slice();
2233    match entry
2234        .handle
2235        .take_serialized_with_attachment(payload, &mut entry.att)
2236    {
2237        // Phase 8 — hooked. One sample per dispatch; the pair brackets the
2238        // whole `unsafe` FFI call, which is the user callback itself.
2239        Ok(Some((len, att_len))) => {
2240            trace_take(
2241                desc_idx,
2242                unsafe { core::slice::from_raw_parts(entry.buffer.as_ptr(), len) },
2243                None,
2244            );
2245            trace_cb_start(desc_idx);
2246            unsafe {
2247                (entry.callback)(
2248                    entry.buffer.as_ptr(),
2249                    len,
2250                    entry.att.as_ptr(),
2251                    att_len,
2252                    entry.context,
2253                )
2254            };
2255            trace_cb_end(desc_idx);
2256            Ok(true)
2257        }
2258        Ok(None) => Ok(false),
2259        Err(_) => Err(TransportError::DeserializationError),
2260    }
2261}
2262
2263/// Readiness check for the C-style raw buffered subscription with attachment.
2264///
2265/// # Safety
2266/// `ptr` must point to a valid `SubBufferedRawInfoCEntry`.
2267pub(crate) unsafe fn sub_buffered_raw_info_c_has_data(ptr: *const u8) -> bool {
2268    let entry = unsafe { &*(ptr as *const SubBufferedRawInfoCEntry) };
2269    entry.handle.has_data()
2270}
2271
2272/// Phase 250 (Wave 2) — generic (type-erased) raw buffered subscription that
2273/// surfaces E2E [`IntegrityStatus`](nros_rmw::IntegrityStatus) (CRC + sequence
2274/// gap/dup) alongside the raw CDR bytes (`FnMut(&[u8], &IntegrityStatus)`).
2275///
2276/// The type-erased analog of [`SubSafetyEntry`]: the validator lives in the
2277/// `RmwSubscriber` and `take_validated` produces the status, so no typed
2278/// `M` is needed (the declarative `Node` path is generic). Flat inline payload
2279/// buffer; one sample per dispatch.
2280#[cfg(feature = "safety-e2e")]
2281#[repr(C)]
2282pub(crate) struct SubBufferedRawSafetyEntry<F> {
2283    pub(crate) handle: session::RmwSubscriber,
2284    /// Issue 1860 / phase-498 W1 -- the receive slot, in the arena's trailing
2285    /// region and sized at registration (from the type's bound when the
2286    /// caller names none), as `SubBufferedRawInfoCEntry` has been since
2287    /// phase-408 W5b. It was an inline `[u8; RX_BUF]`, so every entry of this
2288    /// shape reserved the image's closure maximum whatever its own type was.
2289    pub(crate) buffer: TrailingBuf,
2290    pub(crate) callback: F,
2291}
2292
2293/// Dispatch for the generic raw safety subscription: validate-receive into the
2294/// buffer, then pass the raw slice + status to the callback.
2295///
2296/// # Safety
2297/// `ptr` must point to a valid, aligned `SubBufferedRawSafetyEntry<F>`.
2298#[cfg(feature = "safety-e2e")]
2299pub(crate) unsafe fn sub_buffered_raw_safety_try_process<F>(
2300    ptr: *mut u8,
2301    _delta_us: u64,
2302    desc_idx: u8,
2303) -> Result<bool, TransportError>
2304where
2305    F: FnMut(&[u8], &nros_rmw::IntegrityStatus),
2306{
2307    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawSafetyEntry<F>) };
2308    match entry.handle.take_validated(entry.buffer.as_mut_slice()) {
2309        // Phase 8 — hooked. One sample per dispatch. A failed validation
2310        // still delivers the sample WITH its status, so this arm is the only
2311        // callback path; `Ok(None)` / `Err(_)` fire nothing.
2312        Ok(Some((len, status))) => {
2313            trace_take(desc_idx, &entry.buffer.as_slice()[..len], None);
2314            trace_cb_start(desc_idx);
2315            (entry.callback)(&entry.buffer.as_slice()[..len], &status);
2316            trace_cb_end(desc_idx);
2317            Ok(true)
2318        }
2319        Ok(None) => Ok(false),
2320        Err(_) => Err(TransportError::DeserializationError),
2321    }
2322}
2323
2324/// Readiness check for the generic raw safety subscription.
2325///
2326/// # Safety
2327/// `ptr` must point to a valid `SubBufferedRawSafetyEntry<F>`.
2328#[cfg(feature = "safety-e2e")]
2329pub(crate) unsafe fn sub_buffered_raw_safety_has_data<F>(ptr: *const u8) -> bool {
2330    let entry = unsafe { &*(ptr as *const SubBufferedRawSafetyEntry<F>) };
2331    entry.handle.has_data()
2332}
2333
2334/// Phase 269 W3 — the C analog of [`SubBufferedRawSafetyEntry`]: same flat inline
2335/// payload buffer + `take_validated` dispatch, but the callback is a plain
2336/// C function pointer (`RawSubscriptionSafetyCallback`) that receives the integrity
2337/// scalars alongside the CDR bytes.
2338///
2339/// phase-408 W5b — the payload slot is a [`TrailingBuf`] sized from the
2340/// registering caller's `rx_buffer_hint`, so this entry is no longer generic at
2341/// all: the `RX_BUF` const it was monomorphised over only ever arrived as
2342/// `DEFAULT_RX_BUF_SIZE`, and the status a validated sample carries is
2343/// per-sample side data, which is why the slot stays flat rather than becoming
2344/// a [`BufferStrategy`].
2345#[cfg(feature = "safety-e2e")]
2346#[repr(C)]
2347pub(crate) struct SubBufferedRawSafetyCEntry {
2348    pub(crate) handle: session::RmwSubscriber,
2349    pub(crate) buffer: TrailingBuf,
2350    pub(crate) callback: super::types::RawSubscriptionSafetyCallback,
2351    pub(crate) context: *mut core::ffi::c_void,
2352}
2353
2354/// Dispatch for the C-style raw validated subscription: validate-receive into the
2355/// buffer, then pass the raw slice + unpacked integrity scalars to the callback.
2356///
2357/// # Safety
2358/// `ptr` must point to a valid, aligned `SubBufferedRawSafetyCEntry`.
2359#[cfg(feature = "safety-e2e")]
2360pub(crate) unsafe fn sub_buffered_raw_safety_c_try_process(
2361    ptr: *mut u8,
2362    _delta_us: u64,
2363    desc_idx: u8,
2364) -> Result<bool, TransportError> {
2365    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawSafetyCEntry) };
2366    let payload = entry.buffer.as_mut_slice();
2367    match entry.handle.take_validated(payload) {
2368        // Phase 8 — hooked. One sample per dispatch. The `crc_valid` unpack
2369        // is executor bookkeeping, not user code, so it stays OUTSIDE the
2370        // span; the pair brackets only the FFI call.
2371        Ok(Some((len, status))) => {
2372            let crc_valid: i8 = match status.crc_valid {
2373                Some(true) => 1,
2374                Some(false) => 0,
2375                None => -1,
2376            };
2377            trace_take(
2378                desc_idx,
2379                unsafe { core::slice::from_raw_parts(entry.buffer.as_ptr(), len) },
2380                None,
2381            );
2382            trace_cb_start(desc_idx);
2383            unsafe {
2384                (entry.callback)(
2385                    entry.buffer.as_ptr(),
2386                    len,
2387                    status.gap,
2388                    status.duplicate,
2389                    crc_valid,
2390                    entry.context,
2391                )
2392            };
2393            trace_cb_end(desc_idx);
2394            Ok(true)
2395        }
2396        Ok(None) => Ok(false),
2397        Err(_) => Err(TransportError::DeserializationError),
2398    }
2399}
2400
2401/// Readiness check for the C-style raw validated subscription.
2402///
2403/// # Safety
2404/// `ptr` must point to a valid `SubBufferedRawSafetyCEntry`.
2405#[cfg(feature = "safety-e2e")]
2406pub(crate) unsafe fn sub_buffered_raw_safety_c_has_data(ptr: *const u8) -> bool {
2407    let entry = unsafe { &*(ptr as *const SubBufferedRawSafetyCEntry) };
2408    entry.handle.has_data()
2409}
2410
2411/// Buffered subscription entry for C-style raw callbacks (function pointer + context).
2412///
2413/// Same as `SubBufferedRawEntry` but uses `RawSubscriptionCallback` instead of
2414/// a Rust closure. Used by the C API and by the `register_subscription_buffered_raw_*`
2415/// methods.
2416///
2417/// # Where the caller's capture went — phase-456 W8
2418///
2419/// Phase-456 W1 put the caller's capture INSIDE this struct, as a fixed
2420/// `[u8; CALLBACK_CAPTURE_BYTES]` with ~~`CALLBACK_CAPTURE_BYTES`~~ equal to a C++
2421/// macro's value by construction. That made a number an ABI agreement between
2422/// two languages, with a runtime `BufferTooSmall` as the only thing standing
2423/// between a disagreement and a corrupted dispatch — a failure mode reachable
2424/// ONLY when the two sides drifted, which is to say a failure mode nobody could
2425/// test against.
2426///
2427/// W8 made the capture a RUNTIME LENGTH: exactly `capture.len()` bytes of arena,
2428/// with `context` pointing at them. Since phase-476 W0 those bytes sit at the end
2429/// of the entry's own trailing region (`Executor::place_capture`), so releasing
2430/// the entry releases them.
2431/// The bound is now the arena, which every other allocation here already shares,
2432/// and the constant is gone from both sides of the seam. The entry also stops
2433/// carrying 32 bytes that every non-capturing C registration paid for.
2434#[repr(C)]
2435pub(crate) struct SubBufferedRawCEntry {
2436    pub(crate) handle: session::RmwSubscriber,
2437    pub(crate) buffer: BufferStrategy,
2438    pub(crate) callback: RawSubscriptionCallback,
2439    /// The dispatch context. Either what the caller passed, or — when a capture
2440    /// was supplied — a pointer into the arena's own copy of it, so nothing the
2441    /// caller owns is referenced after registration returns.
2442    pub(crate) context: *mut core::ffi::c_void,
2443    /// phase-476 W2 — destroys that copy when the entry is dropped. Declared
2444    /// after `handle`, so the subscriber is gone before its capture is.
2445    pub(crate) capture: CaptureGuard,
2446    /// Issue 2215 — the contracted age row this subscription feeds, if any.
2447    pub(crate) age_mon: Option<RawAgeMon>,
2448}
2449
2450// ============================================================================
2451// In-place raw C subscription (phase-456 W8)
2452// ============================================================================
2453
2454/// In-place C-callback subscription entry — **no arena buffer**.
2455///
2456/// The C-family twin of [`SubInplaceEntry`], and the one the executor should
2457/// have had first: `RawSubscriptionCallback` is `(const uint8_t*, size_t,
2458/// void*)`, which is already a BORROWED-BYTES signature, so handing it the
2459/// backend's own receive slot costs nothing and needs no conversion — where the
2460/// Rust typed path has to deserialize an owned `&M` out of the same bytes.
2461///
2462/// Until phase-456 W8 the C registration path never consulted
2463/// `supports_process_in_place()`, so every C and C++ subscription on zenoh or
2464/// XRCE allocated a receive region the backend does not need — the same order
2465/// as issue 1340's ~9.7 KiB per subscription, and on the language surface that
2466/// had the easiest time doing without it.
2467#[repr(C)]
2468pub(crate) struct SubInplaceRawCEntry {
2469    pub(crate) handle: session::RmwSubscriber,
2470    pub(crate) callback: RawSubscriptionCallback,
2471    /// Same contract as [`SubBufferedRawCEntry::context`].
2472    pub(crate) context: *mut core::ffi::c_void,
2473    /// Same contract as [`SubBufferedRawCEntry::capture`].
2474    pub(crate) capture: CaptureGuard,
2475    /// Same contract as [`SubBufferedRawCEntry::age_mon`].
2476    pub(crate) age_mon: Option<RawAgeMon>,
2477}
2478
2479/// Dispatch for in-place C-style raw subscriptions.
2480///
2481/// Drains pending samples, up to [`IN_PLACE_DRAIN_LIMIT`], invoking the callback
2482/// directly on the backend's borrowed slot. Returns `Ok(true)` if any sample was dispatched.
2483///
2484/// # Safety
2485/// `ptr` must point to a valid, aligned [`SubInplaceRawCEntry`].
2486pub(crate) unsafe fn sub_inplace_raw_c_try_process(
2487    ptr: *mut u8,
2488    _delta_us: u64,
2489    desc_idx: u8,
2490) -> Result<bool, TransportError> {
2491    let entry = unsafe { &mut *(ptr as *mut SubInplaceRawCEntry) };
2492    // Split-borrow the handle from the callback + context (disjoint fields).
2493    let SubInplaceRawCEntry {
2494        handle,
2495        callback,
2496        context,
2497        age_mon,
2498        ..
2499    } = entry;
2500    let context = *context;
2501    let callback = *callback;
2502    let age_mon = *age_mon;
2503    drain_in_place(|| {
2504        // Phase 8 — hooked INSIDE the borrow closure, which the drain loop
2505        // re-enters once per pending sample, so N samples produce N spans. The
2506        // pair is fully contained in the closure, so the `?` below can never
2507        // fire between a start and its end.
2508        handle.process_raw_in_place(|raw| {
2509            observe_age_raw(raw, &age_mon);
2510            trace_take(desc_idx, raw, None);
2511            trace_cb_start(desc_idx);
2512            unsafe { callback(raw.as_ptr(), raw.len(), context) };
2513            trace_cb_end(desc_idx);
2514        })
2515    })
2516}
2517
2518/// Readiness check for in-place C-style raw subscriptions.
2519///
2520/// # Safety
2521/// `ptr` must point to a valid [`SubInplaceRawCEntry`].
2522pub(crate) unsafe fn sub_inplace_raw_c_has_data(ptr: *const u8) -> bool {
2523    let entry = unsafe { &*(ptr as *const SubInplaceRawCEntry) };
2524    entry.handle.has_data()
2525}
2526
2527/// In-place raw subscription entry for the Rust GENERIC path — issue 1340.
2528///
2529/// The Rust twin of [`SubInplaceRawCEntry`]: `F` is `FnMut(&[u8])`, a
2530/// borrowed-bytes callback, which is exactly what `process_raw_in_place` hands
2531/// over. So there is no receive region to reserve — the backend's own slot is
2532/// the buffer, for the duration of the call.
2533///
2534/// `#[repr(C)]` with `handle` first, like every other subscription entry: the
2535/// executor's tests reach the backend subscriber through the entry's offset,
2536/// and that cast is sound only while the handle leads.
2537///
2538/// Carries no age monitor, and loses none: the buffered entry it replaces on an
2539/// in-place backend ([`SubBufferedRawEntry`]) carries none either. The only
2540/// thing that does not move over is the ring, which is the point.
2541#[repr(C)]
2542pub(crate) struct SubInplaceRawEntry<F> {
2543    pub(crate) handle: session::RmwSubscriber,
2544    pub(crate) callback: F,
2545}
2546
2547/// Dispatch for in-place Rust raw subscriptions.
2548///
2549/// Drains pending samples, up to [`IN_PLACE_DRAIN_LIMIT`], invoking the callback
2550/// directly on the backend's borrowed slot. Returns `Ok(true)` if any sample was dispatched.
2551/// Same drain and the same trace pairing as [`sub_inplace_raw_c_try_process`],
2552/// which it mirrors.
2553///
2554/// # Safety
2555/// `ptr` must point to a valid, aligned [`SubInplaceRawEntry<F>`].
2556pub(crate) unsafe fn sub_inplace_raw_try_process<F: FnMut(&[u8])>(
2557    ptr: *mut u8,
2558    _delta_us: u64,
2559    desc_idx: u8,
2560) -> Result<bool, TransportError> {
2561    let entry = unsafe { &mut *(ptr as *mut SubInplaceRawEntry<F>) };
2562    // Split-borrow the handle from the callback (disjoint fields).
2563    let SubInplaceRawEntry { handle, callback } = entry;
2564    drain_in_place(|| {
2565        // Hooked INSIDE the borrow closure, which the drain loop re-enters once
2566        // per pending sample, so N samples produce N spans and the `?` below
2567        // can never fire between a start and its end.
2568        handle.process_raw_in_place(|raw| {
2569            trace_take(desc_idx, raw, None);
2570            trace_cb_start(desc_idx);
2571            callback(raw);
2572            trace_cb_end(desc_idx);
2573        })
2574    })
2575}
2576
2577/// Readiness check for in-place Rust raw subscriptions.
2578///
2579/// # Safety
2580/// `ptr` must point to a valid [`SubInplaceRawEntry<F>`].
2581pub(crate) unsafe fn sub_inplace_raw_has_data<F>(ptr: *const u8) -> bool {
2582    let entry = unsafe { &*(ptr as *const SubInplaceRawEntry<F>) };
2583    entry.handle.has_data()
2584}
2585
2586/// Drain helper for C-style raw buffered entries.
2587/// Issue 0737 — a transport ERROR is not "no data", and conflating them
2588/// destroys the sample without a trace.
2589///
2590/// Both arms used to read `if let Ok(Some(len)) = … else { break }`, which
2591/// treats `Err(_)` exactly like `Ok(None)`. The backend has ALREADY consumed
2592/// the sample by the time it reports the error, so the message is gone and the
2593/// only observable is that nothing arrived — indistinguishable from a publisher
2594/// that never published. 0737 spent two hosts' investigations inside that
2595/// ambiguity while the executor's own `alive — … 0 error(s)` line reported
2596/// health, because the error never reached the counter that prints it.
2597///
2598/// Now it propagates: `spin_once` maps an `Err` from `try_process` to
2599/// `subscription_errors`, so the count stops lying and the failure has a name.
2600unsafe fn drain_into_buffer_raw_c(entry: &mut SubBufferedRawCEntry) -> Result<(), TransportError> {
2601    match &entry.buffer {
2602        BufferStrategy::Triple(tb) => {
2603            let slot = tb.write_slot();
2604            if let Some(len) = entry.handle.take_serialized(slot)? {
2605                tb.writer_publish(len);
2606            }
2607        }
2608        BufferStrategy::Ring(ring) => {
2609            while let Some(slot) = ring.try_push() {
2610                match entry.handle.take_serialized(slot)? {
2611                    Some(len) => ring.commit_push(len),
2612                    None => break,
2613                }
2614            }
2615        }
2616    }
2617    Ok(())
2618}
2619
2620/// Dispatch for C-style raw buffered subscriptions.
2621///
2622/// # Safety
2623/// `ptr` must point to a valid, aligned `SubBufferedRawCEntry`.
2624pub(crate) unsafe fn sub_buffered_raw_c_try_process(
2625    ptr: *mut u8,
2626    _delta_us: u64,
2627    desc_idx: u8,
2628) -> Result<bool, TransportError> {
2629    let entry = unsafe { &mut *(ptr as *mut SubBufferedRawCEntry) };
2630
2631    // Issue 0737 — drain first, and let a transport error OUT. Anything already
2632    // buffered from an earlier spin is still dispatched below on the next call.
2633    unsafe { drain_into_buffer_raw_c(entry)? };
2634
2635    match &entry.buffer {
2636        // Phase 8 — hooked. Triple-buffered: at most one invocation per
2637        // `try_process`, so exactly one start/end pair, and none at all when
2638        // `reader_acquire` comes back empty.
2639        BufferStrategy::Triple(tb) => match tb.reader_acquire() {
2640            Some((data, len)) => {
2641                observe_age_raw(&data[..len], &entry.age_mon);
2642                trace_take(desc_idx, &data[..len], None);
2643                trace_cb_start(desc_idx);
2644                unsafe { (entry.callback)(data.as_ptr(), len, entry.context) };
2645                trace_cb_end(desc_idx);
2646                Ok(true)
2647            }
2648            None => Ok(false),
2649        },
2650        // Phase 8 — hooked INSIDE the loop, deliberately. A ring drains N
2651        // queued messages per `try_process` and fires the user callback once
2652        // per message; a pair outside the loop would report N invocations as
2653        // one, which is the granularity failure that ruled out hooking the
2654        // `try_process` boundary in the first place.
2655        BufferStrategy::Ring(ring) => {
2656            let mut did_work = false;
2657            while let Some((data, len)) = ring.try_pop() {
2658                observe_age_raw(&data[..len], &entry.age_mon);
2659                trace_take(desc_idx, &data[..len], None);
2660                trace_cb_start(desc_idx);
2661                unsafe { (entry.callback)(data.as_ptr(), len, entry.context) };
2662                trace_cb_end(desc_idx);
2663                ring.commit_pop();
2664                did_work = true;
2665            }
2666            Ok(did_work)
2667        }
2668    }
2669}
2670
2671/// Readiness check for C-style raw buffered subscriptions.
2672///
2673/// # Safety
2674/// `ptr` must point to a valid `SubBufferedRawCEntry`.
2675pub(crate) unsafe fn sub_buffered_raw_c_has_data(ptr: *const u8) -> bool {
2676    let entry = unsafe { &*(ptr as *const SubBufferedRawCEntry) };
2677    entry.handle.has_data() || entry.buffer.has_data()
2678}
2679
2680// ============================================================================
2681// phase-417 W5.a — TYPED C subscription delivery (caller-owned storage)
2682// ============================================================================
2683
2684/// Buffered subscription entry that deserialises into CALLER-OWNED storage
2685/// before dispatching (phase-417 W5.a, RFC-0089 stage 5).
2686///
2687/// Structurally [`SubBufferedRawCEntry`] plus two words: the caller's `msg`
2688/// pointer and the erased deserialiser for its type. Deliberately the same
2689/// buffering machinery — a typed subscription is a raw one with one extra step
2690/// between the ring and the callback, not a second arena and not a second
2691/// receive path.
2692///
2693/// `msg` is not owned here and is not dropped: it is the caller's storage,
2694/// which is exactly what makes typed delivery possible with no allocator (the
2695/// property rclc has and the C ledger wrongly claimed rclc lacked).
2696#[repr(C)]
2697pub(crate) struct SubBufferedTypedCEntry {
2698    pub(crate) handle: session::RmwSubscriber,
2699    pub(crate) buffer: BufferStrategy,
2700    /// Caller-owned message storage. Overwritten on every dispatch.
2701    pub(crate) msg: *mut core::ffi::c_void,
2702    pub(crate) deserialize: RawMessageDeserializeFn,
2703    pub(crate) callback: TypedSubscriptionCallback,
2704    pub(crate) context: *mut core::ffi::c_void,
2705}
2706
2707/// Drain helper for typed buffered entries — the raw one, over the typed entry.
2708///
2709/// Issue 0737's rule applies unchanged: a transport ERROR is not "no data", so
2710/// it propagates instead of being flattened into an empty take.
2711unsafe fn drain_into_buffer_typed_c(
2712    entry: &mut SubBufferedTypedCEntry,
2713) -> Result<(), TransportError> {
2714    match &entry.buffer {
2715        BufferStrategy::Triple(tb) => {
2716            let slot = tb.write_slot();
2717            if let Some(len) = entry.handle.take_serialized(slot)? {
2718                tb.writer_publish(len);
2719            }
2720        }
2721        BufferStrategy::Ring(ring) => {
2722            while let Some(slot) = ring.try_push() {
2723                match entry.handle.take_serialized(slot)? {
2724                    Some(len) => ring.commit_push(len),
2725                    None => break,
2726                }
2727            }
2728        }
2729    }
2730    Ok(())
2731}
2732
2733/// Deserialise one sample into the caller's storage and dispatch.
2734///
2735/// Returns `false` when the deserialiser refused the sample. The callback is
2736/// NOT invoked in that case — a caller that read `msg` after a failed decode
2737/// would be reading the previous message, or an `_init` default, under the
2738/// impression it was the one that just arrived. That is precisely the
2739/// "compile and differ" RFC-0089 forbids, so the failure costs the dispatch.
2740///
2741/// # Safety
2742/// `entry` must be a live typed entry; `data`/`len` a readable CDR sample.
2743unsafe fn typed_dispatch_one(
2744    entry: &SubBufferedTypedCEntry,
2745    data: *const u8,
2746    len: usize,
2747    desc_idx: u8,
2748) -> bool {
2749    let rc = unsafe { (entry.deserialize)(data, len, entry.msg) };
2750    if rc != 0 {
2751        report_typed_deserialize_failure(rc, len);
2752        return false;
2753    }
2754    trace_take(
2755        desc_idx,
2756        unsafe { core::slice::from_raw_parts(data, len) },
2757        None,
2758    );
2759    trace_cb_start(desc_idx);
2760    unsafe { (entry.callback)(entry.msg as *const core::ffi::c_void, entry.context) };
2761    trace_cb_end(desc_idx);
2762    true
2763}
2764
2765/// Count of samples dropped because the caller's deserialiser refused them.
2766/// A static for the reason [`DROPPED_TAKES`] is one.
2767static TYPED_DESERIALIZE_FAILURES: portable_atomic::AtomicU32 = portable_atomic::AtomicU32::new(0);
2768
2769/// Report a refused decode: first, then every 64th.
2770///
2771/// Rate-limited for the reason [`report_dropped_take`] is — a 40-participant
2772/// graph must not turn one type mismatch into a log flood (issue 0371's shape).
2773/// `nros_log`, never stdio (issue 0589), so this reaches a `no_std` image.
2774///
2775/// The single most likely cause is the one this message names first: the
2776/// generated struct's inline capacity is smaller than the sample. Both
2777/// `rclc_cdr_read_string` (`str_len > max_len`) and the bounded-sequence arm
2778/// (`len > capacity`) FAIL rather than truncate, so an oversized message
2779/// arrives here as a refusal and never as a short message the callback cannot
2780/// tell from a real one.
2781#[cold]
2782fn report_typed_deserialize_failure(rc: i32, len: usize) {
2783    let n = TYPED_DESERIALIZE_FAILURES.fetch_add(1, portable_atomic::Ordering::Relaxed);
2784    if n != 0 && !n.is_multiple_of(64) {
2785        return;
2786    }
2787    // phase-417 W5.a
2788    nros_log::log_error!(
2789        nros_log::get_logger("nros"),
2790        "typed subscription DROPPED a {len}-byte sample: deserialize returned \
2791         {rc}. The callback was NOT invoked and the storage still holds the \
2792         previous message. Usual cause: the sample does not fit the message \
2793         struct (a string/sequence longer than its declared bound) or the topic \
2794         carries a different type. Dropped {} so far",
2795        n + 1
2796    );
2797}
2798
2799/// Test-only accessor for [`TYPED_DESERIALIZE_FAILURES`].
2800///
2801/// The cfg MATCHES `mod tests`' own (`executor/mod.rs:95`), not a bare
2802/// `#[cfg(test)]`: the test module is `not(feature = "rmw-cffi")` too, so under
2803/// `test + rmw-cffi` a bare gate leaves this compiled with its only caller
2804/// gone, and `-D warnings` turns that into a build failure rather than a lint.
2805/// An accessor's gate has to be the gate of the thing that reads it — and
2806/// that gate gained `alloc` after this one was written, so under default
2807/// features this was compiled with no caller at all.
2808#[cfg(all(test, feature = "alloc", not(feature = "rmw-cffi")))]
2809pub(crate) fn typed_deserialize_failures() -> u32 {
2810    TYPED_DESERIALIZE_FAILURES.load(portable_atomic::Ordering::Relaxed)
2811}
2812
2813/// Dispatch for typed C subscriptions.
2814///
2815/// # Safety
2816/// `ptr` must point to a valid, aligned [`SubBufferedTypedCEntry`].
2817pub(crate) unsafe fn sub_buffered_typed_c_try_process(
2818    ptr: *mut u8,
2819    _delta_us: u64,
2820    desc_idx: u8,
2821) -> Result<bool, TransportError> {
2822    let entry = unsafe { &mut *(ptr as *mut SubBufferedTypedCEntry) };
2823
2824    unsafe { drain_into_buffer_typed_c(entry)? };
2825
2826    match &entry.buffer {
2827        BufferStrategy::Triple(tb) => match tb.reader_acquire() {
2828            Some((data, len)) => {
2829                if unsafe { typed_dispatch_one(entry, data.as_ptr(), len, desc_idx) } {
2830                    Ok(true)
2831                } else {
2832                    Err(TransportError::DeserializationError)
2833                }
2834            }
2835            None => Ok(false),
2836        },
2837        // A refused sample ENDS the drain and is reported, rather than being
2838        // skipped so the loop can keep going: `try_process` carries one verdict
2839        // per call, and a `Ok(true)` that also swallowed a decode failure would
2840        // never reach `subscription_errors`. The samples still queued behind it
2841        // are dispatched on the next spin — the ring is not cleared.
2842        BufferStrategy::Ring(ring) => {
2843            let mut did_work = false;
2844            while let Some((data, len)) = ring.try_pop() {
2845                let ok = unsafe { typed_dispatch_one(entry, data.as_ptr(), len, desc_idx) };
2846                ring.commit_pop();
2847                if !ok {
2848                    return Err(TransportError::DeserializationError);
2849                }
2850                did_work = true;
2851            }
2852            Ok(did_work)
2853        }
2854    }
2855}
2856
2857/// Readiness check for typed C subscriptions.
2858///
2859/// # Safety
2860/// `ptr` must point to a valid [`SubBufferedTypedCEntry`].
2861pub(crate) unsafe fn sub_buffered_typed_c_has_data(ptr: *const u8) -> bool {
2862    let entry = unsafe { &*(ptr as *const SubBufferedTypedCEntry) };
2863    entry.handle.has_data() || entry.buffer.has_data()
2864}
2865
2866// ============================================================================
2867// Dispatch functions
2868// ============================================================================
2869
2870/// Monomorphized subscription dispatch function (with MessageInfo).
2871///
2872/// # Safety
2873/// `ptr` must point to a valid, aligned `SubInfoEntry<M, F>`.
2874pub(crate) unsafe fn sub_info_try_process<M, F>(
2875    ptr: *mut u8,
2876    _delta_us: u64,
2877    desc_idx: u8,
2878) -> Result<bool, TransportError>
2879where
2880    M: RosMessage,
2881    F: FnMut(&M, Option<&MessageInfo>),
2882{
2883    let entry = unsafe { &mut *(ptr as *mut SubInfoEntry<M, F>) };
2884
2885    // LET mode: use pre-sampled data if available (no MessageInfo in snapshot)
2886    //
2887    // Phase 8 — hooked. This is a SECOND callback site, mutually exclusive
2888    // with the receive path below: LET mode dispatches the snapshot and
2889    // returns, so a dispatch emits one pair from here OR one from there,
2890    // never both.
2891    if entry.sampled_len > 0 {
2892        let len = entry.sampled_len;
2893        entry.sampled_len = 0;
2894        let mut reader = CdrReader::new_with_header(&entry.buffer.as_slice()[..len])
2895            .map_err(|_| TransportError::DeserializationError)?;
2896        let msg = M::deserialize(&mut reader).map_err(|_| TransportError::DeserializationError)?;
2897        trace_take(
2898            desc_idx,
2899            &entry.buffer.as_slice()[..len],
2900            <M as RosMessage>::STAMP_OFFSET,
2901        );
2902        trace_cb_start(desc_idx);
2903        (entry.callback)(&msg, None);
2904        trace_cb_end(desc_idx);
2905        return Ok(true);
2906    }
2907
2908    match entry
2909        .handle
2910        .take_serialized_with_info(entry.buffer.as_mut_slice())
2911    {
2912        // Phase 8 — hooked. One sample per dispatch; `Ok(None)` / `Err(_)`
2913        // fire nothing, and both `?`s precede the start hook.
2914        Ok(Some((len, info))) => {
2915            let mut reader = CdrReader::new_with_header(&entry.buffer.as_slice()[..len])
2916                .map_err(|_| TransportError::DeserializationError)?;
2917            let msg =
2918                M::deserialize(&mut reader).map_err(|_| TransportError::DeserializationError)?;
2919            trace_take(
2920                desc_idx,
2921                &entry.buffer.as_slice()[..len],
2922                <M as RosMessage>::STAMP_OFFSET,
2923            );
2924            trace_cb_start(desc_idx);
2925            (entry.callback)(&msg, info.as_ref());
2926            trace_cb_end(desc_idx);
2927            Ok(true)
2928        }
2929        Ok(None) => Ok(false),
2930        Err(_) => Err(TransportError::DeserializationError),
2931    }
2932}
2933
2934/// Monomorphized subscription dispatch function (with safety validation).
2935///
2936/// # Safety
2937/// `ptr` must point to a valid, aligned `SubSafetyEntry<M, F>`.
2938#[cfg(feature = "safety-e2e")]
2939pub(crate) unsafe fn sub_safety_try_process<M, F>(
2940    ptr: *mut u8,
2941    _delta_us: u64,
2942    desc_idx: u8,
2943) -> Result<bool, TransportError>
2944where
2945    M: RosMessage,
2946    F: FnMut(&M, &nros_rmw::IntegrityStatus),
2947{
2948    let entry = unsafe { &mut *(ptr as *mut SubSafetyEntry<M, F>) };
2949
2950    // LET mode: use pre-sampled data (no IntegrityStatus in snapshot)
2951    //
2952    // Phase 8 — hooked. A SECOND callback site, mutually exclusive with the
2953    // validated-receive path below (this one `return`s). The synthetic
2954    // all-clear `IntegrityStatus` is built inside the span because it is an
2955    // argument expression, not user code — it is three constant stores.
2956    if entry.sampled_len > 0 {
2957        let len = entry.sampled_len;
2958        entry.sampled_len = 0;
2959        let mut reader = CdrReader::new_with_header(&entry.buffer.as_slice()[..len])
2960            .map_err(|_| TransportError::DeserializationError)?;
2961        let msg = M::deserialize(&mut reader).map_err(|_| TransportError::DeserializationError)?;
2962        trace_take(
2963            desc_idx,
2964            &entry.buffer.as_slice()[..len],
2965            <M as RosMessage>::STAMP_OFFSET,
2966        );
2967        trace_cb_start(desc_idx);
2968        (entry.callback)(
2969            &msg,
2970            &nros_rmw::IntegrityStatus {
2971                gap: 0,
2972                duplicate: false,
2973                crc_valid: None,
2974            },
2975        );
2976        trace_cb_end(desc_idx);
2977        return Ok(true);
2978    }
2979
2980    match entry.handle.take_validated(entry.buffer.as_mut_slice()) {
2981        // Phase 8 — hooked. One sample per dispatch; both `?`s precede the
2982        // start hook, and `Ok(None)` / `Err(_)` fire nothing.
2983        Ok(Some((len, status))) => {
2984            let mut reader = CdrReader::new_with_header(&entry.buffer.as_slice()[..len])
2985                .map_err(|_| TransportError::DeserializationError)?;
2986            let msg =
2987                M::deserialize(&mut reader).map_err(|_| TransportError::DeserializationError)?;
2988            trace_take(
2989                desc_idx,
2990                &entry.buffer.as_slice()[..len],
2991                <M as RosMessage>::STAMP_OFFSET,
2992            );
2993            trace_cb_start(desc_idx);
2994            (entry.callback)(&msg, &status);
2995            trace_cb_end(desc_idx);
2996            Ok(true)
2997        }
2998        Ok(None) => Ok(false),
2999        Err(_) => Err(TransportError::DeserializationError),
3000    }
3001}
3002
3003/// Monomorphized service dispatch function.
3004///
3005/// # Safety
3006/// `ptr` must point to a valid, aligned `SrvEntry<Svc, F, REQ_BUF, REPLY_BUF>`.
3007pub(crate) unsafe fn srv_try_process<Svc, F, const REQ_BUF: usize, const REPLY_BUF: usize>(
3008    ptr: *mut u8,
3009    _delta_us: u64,
3010    desc_idx: u8,
3011) -> Result<bool, TransportError>
3012where
3013    Svc: RosService,
3014    F: FnMut(&Svc::Request) -> Svc::Reply,
3015{
3016    let entry = unsafe { &mut *(ptr as *mut SrvEntry<Svc, F, REQ_BUF, REPLY_BUF>) };
3017    // Split borrow: destructure entry to avoid aliasing issues
3018    let SrvEntry {
3019        handle,
3020        req_buffer,
3021        reply_buffer,
3022        callback,
3023        ..
3024    } = entry;
3025    handle
3026        // Phase 8 — hooked INSIDE the closure `handle_request` invokes, not
3027        // around `handle_request` itself. The closure runs once per request
3028        // actually received, so a spin with nothing pending emits nothing;
3029        // bracketing the outer call would have timed the receive/reply
3030        // machinery and fired on every empty poll.
3031        .handle_request::<Svc>(req_buffer, reply_buffer, |req| {
3032            trace_cb_start(desc_idx);
3033            let reply = (callback)(req);
3034            trace_cb_end(desc_idx);
3035            reply
3036        })
3037        .map_err(|_| TransportError::ServiceReplyFailed)
3038}
3039
3040/// Issue 1942 — [`srv_try_process`] for a callback that also takes the
3041/// request's [`ServiceInfo`](nros_core::ServiceInfo) (rclrs's shape). Same
3042/// [`SrvEntry`] layout; only the callback's signature differs.
3043///
3044/// # Safety
3045/// `ptr` must point to a valid `SrvEntry<Svc, F, REQ_BUF, REPLY_BUF>`.
3046pub(crate) unsafe fn srv_try_process_with_info<
3047    Svc,
3048    F,
3049    const REQ_BUF: usize,
3050    const REPLY_BUF: usize,
3051>(
3052    ptr: *mut u8,
3053    _delta_us: u64,
3054    desc_idx: u8,
3055) -> Result<bool, TransportError>
3056where
3057    Svc: RosService,
3058    F: FnMut(&Svc::Request, &nros_core::ServiceInfo) -> Svc::Reply,
3059{
3060    let entry = unsafe { &mut *(ptr as *mut SrvEntry<Svc, F, REQ_BUF, REPLY_BUF>) };
3061    let SrvEntry {
3062        handle,
3063        req_buffer,
3064        reply_buffer,
3065        callback,
3066        ..
3067    } = entry;
3068    handle
3069        // Traced inside the closure, as in `srv_try_process`.
3070        .handle_request_with_info::<Svc>(req_buffer, reply_buffer, |req, info| {
3071            trace_cb_start(desc_idx);
3072            let reply = (callback)(req, info);
3073            trace_cb_end(desc_idx);
3074            reply
3075        })
3076        .map_err(|_| TransportError::ServiceReplyFailed)
3077}
3078
3079/// Monomorphized drop function for arena entries.
3080///
3081/// # Safety
3082/// `ptr` must point to a valid, aligned `T` that has not been dropped.
3083pub(crate) unsafe fn drop_entry<T>(ptr: *mut u8) {
3084    unsafe { core::ptr::drop_in_place(ptr as *mut T) };
3085}
3086
3087/// What one executor cycle does to a timer's own `elapsed_us`.
3088pub(crate) enum TimerStep {
3089    /// Add this many microseconds, measured on the TIMER'S clock.
3090    Advance(u64),
3091    /// The timer's clock jumped BACKWARDS — a bag looping, a simulator reset,
3092    /// an NTP step. Restart the period rather than stalling the timer for the
3093    /// length of the jump, which is what accumulating a negative delta would
3094    /// amount to. rclcpp gets here through a jump callback; we need the
3095    /// behaviour, not (yet) the callback surface
3096    /// (`c:clock_add_jump_callback` stays declined).
3097    Restart,
3098}
3099
3100/// One cycle's advance for a timer, in the timer's OWN clock — phase-425 W4,
3101/// made shared by issue 1321.
3102///
3103/// `Steady` consumes the executor's spin delta, unchanged and free. The other
3104/// two READ their clock and diff against the last reading, which is what makes
3105/// a paused simulator pause the timer: `/clock` stops advancing, so the delta
3106/// is zero. A FORWARD jump is deliberately NOT special-cased: it lands in
3107/// `elapsed_us` as a backlog, and the overrun policy is the documented
3108/// mechanism for deciding whether a backlog replays (`CatchUp`) or coalesces
3109/// (`Skip`).
3110///
3111/// One spelling, because there are two callers: the dispatcher below, and the
3112/// budget-skip path in `spin_once`. That second one had the delta computation
3113/// open-coded as "add the executor's `delta_us`", which is a WALL quantity —
3114/// the same units error as issue 1321's park bound, but unbounded: it advanced
3115/// a `Ros` timer while `/clock` was paused, which is the one thing a ROS-time
3116/// timer must never do.
3117pub(crate) fn timer_clock_step(
3118    clock_source: TimerClockSource,
3119    last_clock_ns: &mut i64,
3120    spin_delta_us: u64,
3121) -> TimerStep {
3122    match clock_source {
3123        TimerClockSource::Steady => TimerStep::Advance(spin_delta_us),
3124        source => {
3125            let now_ns = source.now_ns();
3126            let step_ns = now_ns - *last_clock_ns;
3127            *last_clock_ns = now_ns;
3128            if step_ns < 0 {
3129                return TimerStep::Restart;
3130            }
3131            TimerStep::Advance((step_ns as u64) / 1_000)
3132        }
3133    }
3134}
3135
3136/// Advance a timer's own sense of time by one cycle WITHOUT dispatching it —
3137/// issue 0736's accounting, on issue 1321's clock.
3138///
3139/// Type-erased because its caller has a `TimerHeader`, not a `TimerEntry<F>`.
3140pub(crate) fn timer_advance_without_dispatch(header: &mut TimerHeader, spin_delta_us: u64) {
3141    match timer_clock_step(
3142        header.clock_source,
3143        &mut header.last_clock_ns,
3144        spin_delta_us,
3145    ) {
3146        TimerStep::Advance(us) => header.elapsed_us = header.elapsed_us.saturating_add(us),
3147        TimerStep::Restart => header.elapsed_us = 0,
3148    }
3149}
3150
3151/// A `Skip` timer's overrun after it fired: the periods it missed beyond the
3152/// one that fired, and what stays of `elapsed_us` on the phase grid.
3153///
3154/// Saturating, because `elapsed_us` can be BELOW one period here: a callback
3155/// that reset its own timer (`timer->reset()`, which upstream allows inside
3156/// the callback) zeroed it while the timer was firing. `0 / period - 1`
3157/// panicked a debug build (phase-518 W2: issue 2055's callback pump re-arms
3158/// its timer from a callback that sends again).
3159pub(crate) fn skip_overrun(elapsed_us: u64, period_us: u64) -> (u64, u64) {
3160    (
3161        (elapsed_us / period_us).saturating_sub(1),
3162        elapsed_us % period_us,
3163    )
3164}
3165
3166/// The call info for an activation that is due NOW — issue 1974.
3167///
3168/// `actual` is now on the timer's clock ([`TimerClockSource::dispatch_now_ns`]);
3169/// `expected` subtracts how far `elapsed_us` has run past `period_us`. A
3170/// zero-period timer ("fire every spin") has no deadline to be late for, so its
3171/// two times coincide.
3172pub(crate) fn timer_call_info(
3173    clock_source: TimerClockSource,
3174    last_clock_ns: i64,
3175    elapsed_us: u64,
3176    period_us: u64,
3177) -> TimerCallInfo {
3178    let actual = clock_source.dispatch_now_ns(last_clock_ns);
3179    let late_us = if period_us == 0 {
3180        0
3181    } else {
3182        elapsed_us.saturating_sub(period_us)
3183    };
3184    let late_ns = i64::try_from(late_us.saturating_mul(1_000)).unwrap_or(i64::MAX);
3185    TimerCallInfo {
3186        expected_call_time: actual.saturating_sub(late_ns),
3187        actual_call_time: actual,
3188        clock: clock_source,
3189        since_last_call_ns: i64::try_from(elapsed_us.saturating_mul(1_000)).unwrap_or(i64::MAX),
3190    }
3191}
3192
3193/// Monomorphized timer dispatch function.
3194///
3195/// # Safety
3196/// `ptr` must point to a valid, aligned `TimerEntry<F>`.
3197pub(crate) unsafe fn timer_try_process<F>(
3198    ptr: *mut u8,
3199    delta_us: u64,
3200    desc_idx: u8,
3201) -> Result<bool, TransportError>
3202where
3203    F: FnMut(&TimerCallInfo),
3204{
3205    let entry = unsafe { &mut *(ptr as *mut TimerEntry<F>) };
3206
3207    // Cancelled or one-shot already fired
3208    if entry.cancelled || (entry.oneshot && entry.fired) {
3209        return Ok(false);
3210    }
3211
3212    // phase-425 W4 — which clock advanced, and by how much. Shared with the
3213    // budget-skip path in `spin_once`, which advances the same counter without
3214    // dispatching (issue 0736): there is ONE answer to "which clock moves this
3215    // timer", and it is `timer_clock_step`.
3216    let delta_us = match timer_clock_step(entry.clock_source, &mut entry.last_clock_ns, delta_us) {
3217        TimerStep::Advance(us) => us,
3218        TimerStep::Restart => {
3219            entry.elapsed_us = 0;
3220            return Ok(false);
3221        }
3222    };
3223
3224    entry.elapsed_us = entry.elapsed_us.saturating_add(delta_us);
3225
3226    if entry.elapsed_us >= entry.period_us {
3227        // Phase 8 — hooked. Inside the due-check, so a timer polled on every
3228        // spin and not yet due emits nothing: `Ok(false)` is the COMMON
3229        // outcome here, and it is exactly the over-reporting that a hook at
3230        // the `try_process` boundary would have produced.
3231        // phase-474 I3 -- one tick in N when the timer is thinned.
3232        let traced = timer_tick_traced(desc_idx);
3233        // Issue 1974 — the ONE producer of a timer's call info, computed from
3234        // the very comparison that just decided the activation is due, so the
3235        // three language surfaces read the dispatcher's answer rather than
3236        // keeping their own. Lateness is how far `elapsed_us` ran past the
3237        // period; it is never negative here, so `actual >= expected` always.
3238        let info = timer_call_info(
3239            entry.clock_source,
3240            entry.last_clock_ns,
3241            entry.elapsed_us,
3242            entry.period_us,
3243        );
3244        if traced {
3245            trace_cb_start(desc_idx);
3246        }
3247        (entry.callback)(&info);
3248        // RFC-0108 D9 (issue 2675) -- the callback may have called back into
3249        // the executor (a C callback cancelling or resetting this very timer
3250        // writes this entry), so the reference from before it is stale:
3251        // derive it again from `ptr`.
3252        // SAFETY: as at the top; the entry is not released during dispatch
3253        // (a release is deferred until the dispatch ends, issue 1705).
3254        let entry = unsafe { &mut *(ptr as *mut TimerEntry<F>) };
3255        if traced {
3256            trace_cb_end(desc_idx);
3257        }
3258        if entry.oneshot {
3259            entry.fired = true;
3260        } else if entry.period_us == 0 {
3261            entry.elapsed_us = 0;
3262        } else {
3263            // Issue #505 — a stall leaves `elapsed_us` worth several
3264            // periods. `CatchUp` subtracts one period per pass, so the
3265            // backlog replays back-to-back; `Skip` drops the whole
3266            // backlog in one step and counts it, keeping the remainder
3267            // so activations stay on the original phase grid.
3268            match entry.overrun_policy {
3269                TimerOverrunPolicy::CatchUp => {
3270                    entry.elapsed_us = entry.elapsed_us.saturating_sub(entry.period_us);
3271                }
3272                TimerOverrunPolicy::Skip => {
3273                    let (missed, remainder) = skip_overrun(entry.elapsed_us, entry.period_us);
3274                    if missed > 0 {
3275                        entry.overruns = entry
3276                            .overruns
3277                            .saturating_add(u32::try_from(missed).unwrap_or(u32::MAX));
3278                    }
3279                    entry.elapsed_us = remainder;
3280                }
3281            }
3282        }
3283        Ok(true)
3284    } else {
3285        Ok(false)
3286    }
3287}
3288
3289/// Monomorphized action server dispatch function.
3290///
3291/// Polls goal acceptance, cancel handling, and result serving.
3292///
3293/// # Safety
3294/// `ptr` must point to a valid, aligned `ActionServerArenaEntry<...>`.
3295pub(crate) unsafe fn action_server_try_process<
3296    A,
3297    GoalF,
3298    CancelF,
3299    const GOAL_BUF: usize,
3300    const RESULT_BUF: usize,
3301    const FEEDBACK_BUF: usize,
3302    const MAX_GOALS: usize,
3303>(
3304    ptr: *mut u8,
3305    _delta_us: u64,
3306    desc_idx: u8,
3307) -> Result<bool, TransportError>
3308where
3309    A: RosAction,
3310    A::Goal: Clone,
3311    A::Result: Clone + Default,
3312    GoalF: FnMut(&nros_core::GoalUuid, &A::Goal) -> nros_core::GoalResponse,
3313    CancelF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode) -> nros_core::CancelResponse,
3314{
3315    type Entry<A, G, C, const GB: usize, const RB: usize, const FB: usize, const MG: usize> =
3316        ActionServerArenaEntry<A, G, C, GB, RB, FB, MG>;
3317    let entry = ptr as *mut Entry<A, GoalF, CancelF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>;
3318    // RFC-0108 D9 / phase-573 W2b, as `action_server_raw_try_process`: a
3319    // callback may reach this entry again (`ActionServerHandle::complete_goal`
3320    // through a raw executor pointer), which derives its own `&mut` to the
3321    // server. So no reference to the server lives across a callback: each step
3322    // takes a fresh one, from a raw place that covers the server's bytes and
3323    // not the callbacks', and each callback is borrowed through its own field.
3324    //
3325    // SAFETY (each use): `ptr` points to a valid entry (this fn's contract);
3326    // a server reference ends before any callback runs, and a callback
3327    // reference covers that callback's bytes alone. The closure's result has
3328    // an unbounded lifetime, so each use stays one expression: never bind it
3329    // across a callback, and never hold two at once.
3330    let server = move || unsafe { &mut *core::ptr::addr_of_mut!((*entry).server) };
3331
3332    let mut did_work = false;
3333
3334    // Handle cancels first: receive and select, ask the callback per goal
3335    // with the server released, then reply.
3336    //
3337    // Phase 8 — the trace pair wraps each callback, so nothing is emitted on
3338    // the common no-request spin.
3339    if let Ok(Some(selection)) = server().core.recv_cancel() {
3340        let mut accepted = [false; MAX_GOALS];
3341        for (slot, row) in accepted.iter_mut().zip(&selection.rows) {
3342            if let Some(row) = row {
3343                // SAFETY: as above.
3344                let cancel_callback =
3345                    unsafe { &mut *core::ptr::addr_of_mut!((*entry).cancel_callback) };
3346                trace_cb_start(desc_idx);
3347                let resp = (cancel_callback)(&row.goal_id, row.status);
3348                trace_cb_end(desc_idx);
3349                *slot = resp == nros_core::CancelResponse::Accept;
3350            }
3351        }
3352        if server().core.reply_cancel(&selection, &accepted).is_ok() {
3353            did_work = true;
3354        }
3355    }
3356
3357    // Handle new goals: decode an owned goal, ask the callback with the
3358    // server released, then answer.
3359    if let Ok(Some((raw_req, goal))) = server().recv_goal() {
3360        // SAFETY: as above.
3361        let goal_callback = unsafe { &mut *core::ptr::addr_of_mut!((*entry).goal_callback) };
3362        // Phase 8 — hooked inside the `Ok(Some(..))` arm: no goal request,
3363        // no goal callback, nothing emitted.
3364        trace_cb_start(desc_idx);
3365        let response = (goal_callback)(&raw_req.goal_id, &goal);
3366        trace_cb_end(desc_idx);
3367        if matches!(
3368            server().finish_goal(raw_req, goal, response.is_accepted()),
3369            Ok(Some(_))
3370        ) {
3371            did_work = true;
3372        }
3373    }
3374
3375    // Handle result requests
3376    if matches!(server().try_handle_get_result(), Ok(Some(_))) {
3377        did_work = true;
3378    }
3379
3380    Ok(did_work)
3381}
3382
3383/// Monomorphized raw action server dispatch function.
3384///
3385/// Polls goal acceptance, cancel handling, and result serving using raw bytes.
3386///
3387/// # Safety
3388/// `ptr` must point to a valid, aligned `ActionServerRawArenaEntry<...>`.
3389pub(crate) unsafe fn action_server_raw_try_process<
3390    const GOAL_BUF: usize,
3391    const RESULT_BUF: usize,
3392    const FEEDBACK_BUF: usize,
3393    const MAX_GOALS: usize,
3394>(
3395    ptr: *mut u8,
3396    _delta_us: u64,
3397    desc_idx: u8,
3398) -> Result<bool, TransportError> {
3399    type Entry<const G: usize, const R: usize, const F: usize, const M: usize> =
3400        ActionServerRawArenaEntry<G, R, F, M>;
3401    // RFC-0108 D9 / phase-573 W2b: every user callback below may re-enter
3402    // this entry through the C API (`rclc_action_succeed`,
3403    // `rclc_action_publish_feedback`, ...), which derives its own `&mut` to
3404    // it from the arena. So no reference into the entry lives across a
3405    // callback: each step takes a fresh one from `ptr` and drops it before
3406    // the next callback runs, and the callbacks read only copies.
3407    //
3408    // SAFETY (each use): `ptr` points to a valid entry (this fn's contract),
3409    // and the reference ends before any user callback runs.
3410    let entry =
3411        || unsafe { &mut *(ptr as *mut Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>) };
3412    let (goal_callback, cancel_callback, accepted_callback, context) = {
3413        let e = entry();
3414        (
3415            e.goal_callback,
3416            e.cancel_callback,
3417            e.accepted_callback,
3418            e.context,
3419        )
3420    };
3421
3422    let mut did_work = false;
3423
3424    // Handle cancels first: receive and select, ask the callback per goal
3425    // with the core released, then reply.
3426    //
3427    // Phase 8 — the trace pair wraps each callback, so nothing is emitted on
3428    // the common no-request spin.
3429    if let Ok(Some(selection)) = entry().core.recv_cancel() {
3430        let mut accepted = [false; MAX_GOALS];
3431        for (slot, row) in accepted.iter_mut().zip(&selection.rows) {
3432            if let Some(row) = row {
3433                trace_cb_start(desc_idx);
3434                let resp = unsafe { cancel_callback(&row.goal_id, row.status, context) };
3435                trace_cb_end(desc_idx);
3436                *slot = resp == nros_core::CancelResponse::Accept;
3437            }
3438        }
3439        let _ = entry().core.reply_cancel(&selection, &accepted);
3440        did_work = true;
3441    }
3442
3443    // Handle new goals
3444    if let Ok(Some(raw_req)) = entry().core.try_recv_goal_request() {
3445        // The goal bytes, addressed from `ptr` itself rather than through a
3446        // reference the callback's own derive would invalidate.
3447        // SAFETY: `ptr` points to a valid entry; no reference is formed.
3448        let goal_data = unsafe {
3449            core::ptr::addr_of!(
3450                (*(ptr as *const Entry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF, MAX_GOALS>))
3451                    .core
3452                    .goal_buffer
3453            )
3454        } as *const u8;
3455        let data_len = raw_req.data_len.min(GOAL_BUF);
3456        // Phase 8 — hooked inside the `Ok(Some(..))` arm: no goal request,
3457        // no goal callback, nothing emitted.
3458        trace_cb_start(desc_idx);
3459        let response = unsafe { goal_callback(&raw_req.goal_id, goal_data, data_len, context) };
3460        trace_cb_end(desc_idx);
3461
3462        if response.is_accepted() {
3463            // Send the accept reply *before* running any long-running
3464            // post-accept hook so the client observes acceptance promptly.
3465            let _ = entry()
3466                .core
3467                .accept_goal(raw_req.goal_id, raw_req.sequence_number);
3468            // Phase 8 — the post-accept hook is a THIRD, separate user
3469            // callback: optional, and run only on the accepted branch, so
3470            // it carries its own pair rather than being folded into the
3471            // goal callback's span above.
3472            if let Some(post) = accepted_callback {
3473                trace_cb_start(desc_idx);
3474                unsafe { post(&raw_req.goal_id, context) };
3475                trace_cb_end(desc_idx);
3476            }
3477        } else {
3478            let _ = entry().core.reject_goal(raw_req.sequence_number);
3479        }
3480        did_work = true;
3481    }
3482
3483    // Handle result requests (empty default result for raw API)
3484    if let Ok(Some(_)) = entry().core.try_handle_get_result_raw(&[]) {
3485        did_work = true;
3486    }
3487
3488    Ok(did_work)
3489}
3490
3491/// Monomorphized raw action client dispatch function.
3492///
3493/// Polls the action client core's non-blocking methods:
3494/// 1. Goal acceptance reply (`try_recv_send_goal_reply`)
3495/// 2. Feedback (`try_recv_feedback_raw`)
3496/// 3. Result reply (`try_recv_get_result_reply`)
3497///
3498/// Invokes the corresponding callback when data is available.
3499///
3500/// # Safety
3501/// `ptr` must point to a valid, aligned `ActionClientRawArenaEntry<...>`.
3502/// RFC-0069 / issues 0418 + 0035 — **retired as a correctness mechanism.**
3503///
3504/// This sniffed whether a payload already began with a CDR encapsulation header
3505/// (`00 <id> <opts> <opts>`) and read it directly if so. That is a VALUE test,
3506/// not a framing test, and it cannot tell the two apart: a leading `uint32` of
3507/// 256 serializes little-endian as `00 01 00 00` — byte for byte the LE encap
3508/// header. A sequence of length 256 is enough.
3509///
3510/// It was harmless while only Cyclone took the false branch. 0418 stopped the
3511/// producer writing an inner header, so EVERY payload began consulting it, and
3512/// a body whose first word happened to look like a header had that word eaten
3513/// as framing — issue #35's "sequence deserialized to len 0", reached through a
3514/// payload value instead of a framing bug.
3515///
3516/// Kept only for the pre-0418 diagnostic below, never for a decode decision.
3517#[cfg(test)]
3518fn payload_has_cdr_encap(p: &[u8]) -> bool {
3519    p.len() >= 4 && p[0] == 0x00 && matches!(p[1], 0x00 | 0x01 | 0x06 | 0x07 | 0x0a | 0x0b)
3520}
3521
3522/// Deserialize an action result/feedback field payload, restoring the per-message
3523/// CDR encapsulation header the backend's typed framing may have stripped (#175).
3524/// `raw` is the field bytes at the payload offset; `top_encap` is the enclosing
3525/// message's leading 4-byte encap (always a valid header). When `raw` already
3526/// begins with an encap (zenoh/XRCE) it is read directly; when it does not
3527/// (Cyclone `dds_stream` drops the inner encap of a nested message field) the
3528/// top-level encap is spliced in front into a `CAP`-byte scratch buffer first.
3529fn read_action_field<M: nros_serdes::Deserialize, const CAP: usize>(
3530    top_encap: &[u8],
3531    raw: &[u8],
3532) -> Option<M> {
3533    // ALWAYS splice (RFC-0069 / issue 0418). Post-0418 the producer writes no
3534    // inner encapsulation header, and neither does Cyclone's `dds_stream` (it
3535    // drops the inner encap of a nested field, #175) — so the payload is field
3536    // bytes in every case and the enclosing message's encap is the right one to
3537    // read them with.
3538    //
3539    // This used to branch on `payload_has_cdr_encap(raw)`. That sniff is a value
3540    // test and gets it wrong for a body starting `00 01 00 00` (a `uint32` of
3541    // 256, e.g. a 256-element sequence), eating the leading data word — see the
3542    // retired helper above.
3543    if top_encap.len() < 4 || raw.len() + 4 > CAP {
3544        return None;
3545    }
3546    let mut buf = [0u8; CAP];
3547    buf[0..4].copy_from_slice(&top_encap[0..4]);
3548    buf[4..4 + raw.len()].copy_from_slice(raw);
3549    let mut reader = CdrReader::new_with_header(&buf[..4 + raw.len()]).ok()?;
3550    M::deserialize(&mut reader).ok()
3551}
3552
3553pub(crate) unsafe fn action_client_raw_try_process<
3554    const GOAL_BUF: usize,
3555    const RESULT_BUF: usize,
3556    const FEEDBACK_BUF: usize,
3557>(
3558    ptr: *mut u8,
3559    _delta_us: u64,
3560    desc_idx: u8,
3561) -> Result<bool, TransportError> {
3562    let entry = unsafe {
3563        &mut *(ptr as *mut ActionClientRawArenaEntry<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>)
3564    };
3565    let ActionClientRawArenaEntry {
3566        core,
3567        goal_response_callback,
3568        feedback_callback,
3569        result_callback,
3570        cancel_response_callback,
3571        context,
3572    } = entry;
3573
3574    let mut did_work = false;
3575
3576    // 1. Poll goal acceptance reply
3577    // Issue 2009 — the goal is the one the reply's request was ABOUT. It used
3578    // to be rebuilt from `goal_counter`, i.e. the most recently SENT goal, so
3579    // two goals in flight swapped acceptances.
3580    if let Ok(Some((total_len, goal_id))) = core.try_recv_send_goal_reply_for() {
3581        if let Some(cb) = goal_response_callback {
3582            // Reply CDR: header (4) + accepted (u8) + stamp
3583            let accepted = crate::action_frame::goal_accepted(&core.result_buffer[..total_len]);
3584            // Phase 8 — hooked at the invocation, inside both the
3585            // `Ok(Some(..))` arm and the `Some(cb)` guard: an unregistered
3586            // callback or an empty poll emits nothing.
3587            trace_cb_start(desc_idx);
3588            unsafe { cb(&goal_id, accepted, *context) };
3589            trace_cb_end(desc_idx);
3590        }
3591        did_work = true;
3592    }
3593
3594    // 2. Poll feedback
3595    if let Ok(Some((goal_id, total_len))) = core.try_recv_feedback_raw() {
3596        if let Some(cb) = feedback_callback {
3597            // Layout `[encap 4][GoalUuid.uuid 16][fields]` — see `action_frame`.
3598            // Issue 2014 — the offset (`action_frame::FEEDBACK_PAYLOAD_OFFSET`)
3599            // and the splice are spelled once, in `action_frame`.
3600            //
3601            // #175 + RFC-0069/0418 — the payload is field bytes on every
3602            // backend now: Cyclone's `dds_stream` drops the inner encap of a
3603            // nested field, and since 0418 the producer never writes one. So
3604            // splice the enclosing message's encap unconditionally. This used
3605            // to branch on an encap SNIFF, which mis-fires on a body whose
3606            // first word is 0x00010000 (see the retired helper).
3607            let mut spliced = [0u8; FEEDBACK_BUF];
3608            if let Some(n) = crate::action_frame::splice_feedback(
3609                &core.feedback_buffer[..total_len],
3610                &mut spliced,
3611            ) {
3612                // Phase 8 — a DISTINCT callback from the goal-response one,
3613                // with its own pair. Hooked inside the guard: a short
3614                // payload runs no user code and must emit nothing.
3615                trace_cb_start(desc_idx);
3616                unsafe { cb(&goal_id, spliced.as_ptr(), n, *context) };
3617                trace_cb_end(desc_idx);
3618            }
3619        }
3620        did_work = true;
3621    }
3622
3623    // 3. Poll result reply — issue 2009: attributed to the goal its request
3624    //    named, not to the most recently sent goal.
3625    if let Ok(Some((total_len, goal_id))) = core.try_recv_get_result_reply_for() {
3626        if let Some(cb) = result_callback {
3627            // Layout `[encap 4][status i8][pad → 8][fields]` — see
3628            // `action_frame`. Slicing at 5 (Phase 96.1) leaked the three pad
3629            // bytes into the payload and emptied every C++/XRCE result.
3630            // Issue 2014 — status, payload offset and splice come from
3631            // `action_frame`, the one spelling every consumer shares.
3632            //
3633            // #175 + RFC-0069/0418 — restore the result's CDR encapsulation
3634            // header. The fields arrive raw on every backend now: Cyclone sends
3635            // `GetResult_Response` as a TYPED sample whose `result` is a NESTED
3636            // field, so `dds_stream` consumes the inner encap; and since 0418
3637            // the producer never writes one. The consumer
3638            // (`CallbackCtx::message` / `ffi_deserialize`) reads with
3639            // `new_with_header`, so splice the reply's top-level encap in front
3640            // unconditionally. It used to branch on an encap SNIFF, which a
3641            // leading `int32` of 256 (`00 01 00 00`) defeats — see the retired
3642            // `payload_has_cdr_encap`.
3643            let reply = &core.result_buffer[..total_len];
3644            let mut spliced = [0u8; RESULT_BUF];
3645            if let (Some(status), Some(n)) = (
3646                crate::action_frame::result_status(reply),
3647                crate::action_frame::splice_result(reply, &mut spliced),
3648            ) {
3649                // Phase 8 — the third distinct callback on this entry, its
3650                // own pair. Inside the guard, which can skip the call entirely.
3651                trace_cb_start(desc_idx);
3652                unsafe { cb(&goal_id, status, spliced.as_ptr(), n, *context) };
3653                trace_cb_end(desc_idx);
3654            }
3655        }
3656        did_work = true;
3657    }
3658
3659    // 4. Poll cancel reply — issue 2030. Only when a callback is registered:
3660    //    a surface with no callback must find the reply still there. Taking it
3661    //    retires its request from `pending_cancel`, which is what frees the
3662    //    slot; before this, nothing on the C callback tier took one and the
3663    //    fifth `rclc_action_cancel_goal` was refused. Issue 2034 — the request's
3664    //    sequence id and the whole frame go along, so C++ can hand the reply to
3665    //    the future waiting on THAT request, with its `goals_canceling` list.
3666    if let Some(cb) = cancel_response_callback
3667        && let Ok(Some((total_len, seq, goal_id))) = core.try_recv_cancel_reply_seq()
3668    {
3669        let reply = &core.result_buffer[..total_len];
3670        let code = crate::action_frame::cancel_return_code(reply)
3671            .and_then(nros_core::CancelResponseCode::from_i8)
3672            .unwrap_or(nros_core::CancelResponseCode::Rejected);
3673        let n = crate::action_frame::cancel_goals_count(reply).unwrap_or(0);
3674        // Phase 8 — the fourth distinct callback on this entry, its own pair.
3675        trace_cb_start(desc_idx);
3676        unsafe {
3677            cb(
3678                &goal_id,
3679                seq,
3680                code,
3681                n,
3682                reply.as_ptr(),
3683                reply.len(),
3684                *context,
3685            )
3686        };
3687        trace_cb_end(desc_idx);
3688        did_work = true;
3689    }
3690
3691    Ok(did_work)
3692}
3693
3694/// Monomorphized raw service-client dispatch function.
3695///
3696/// Checks `reply_ready` (set by the transport waker) before calling
3697/// `take_response_raw`. This avoids blind polling on every spin tick —
3698/// the only cost per tick is an atomic load when no reply is pending.
3699///
3700/// # Safety
3701/// `ptr` must point to a valid, aligned `ServiceClientRawArenaEntry<REPLY_BUF>`.
3702pub(crate) unsafe fn service_client_raw_try_process<const REPLY_BUF: usize>(
3703    ptr: *mut u8,
3704    _delta_us: u64,
3705    desc_idx: u8,
3706) -> Result<bool, TransportError> {
3707    use core::sync::atomic::Ordering;
3708    let entry = unsafe { &mut *(ptr as *mut ServiceClientRawArenaEntry<REPLY_BUF>) };
3709
3710    if !entry.pending {
3711        return Ok(false);
3712    }
3713    // phase-492 W4 — a client registered WITHOUT a response callback is the
3714    // polling shape (`rclc_client_take_response`): its reply belongs to that
3715    // call. Taking it here dropped it, because there was no callback to hand
3716    // it to and `pending` was cleared — so a C component that sent a request
3717    // and polled from a timer never saw a single reply while the server
3718    // answered every one. Leave it in the handle for the poll.
3719    if entry.callback.is_none() && entry.request_id_callback.is_none() {
3720        return Ok(false);
3721    }
3722
3723    // Clear the waker flag if set (consumed by this check).
3724    entry.reply_ready.store(false, Ordering::Release);
3725
3726    // Issue 2009 — dispatched only if the reply names the call in flight; a
3727    // late reply to an earlier call is dropped here, not handed to this one.
3728    let ServiceClientRawArenaEntry {
3729        handle,
3730        reply_buffer,
3731        sequences,
3732        ..
3733    } = &mut *entry;
3734    match take_client_reply(handle, reply_buffer, sequences) {
3735        Ok(Some((len, seq))) => {
3736            entry.pending = false;
3737            // Issue 2136 — the request-id shape, when registered, in place of
3738            // the plain one. The id is read before anything else takes on
3739            // this handle, so it describes this reply.
3740            if let Some(cb) = entry.request_id_callback {
3741                let mut id = RawRequestId::for_response(
3742                    &nros_rmw::ClientTrait::response_info(&entry.handle),
3743                    seq,
3744                );
3745                trace_cb_start(desc_idx);
3746                unsafe { cb(entry.reply_buffer.as_ptr(), len, &mut id, entry.context) };
3747                trace_cb_end(desc_idx);
3748                return Ok(true);
3749            }
3750            // Phase 8 — hooked inside the `Some(cb)` arm. A client with no
3751            // callback never reaches here (see above); the not-pending and
3752            // `Ok(None)` paths return before this point too.
3753            if let Some(cb) = entry.callback {
3754                trace_cb_start(desc_idx);
3755                unsafe { cb(entry.reply_buffer.as_ptr(), len, entry.context) };
3756                trace_cb_end(desc_idx);
3757            }
3758            Ok(true)
3759        }
3760        Ok(None) => Ok(false),
3761        Err(_) => {
3762            entry.pending = false;
3763            Err(TransportError::ServiceRequestFailed)
3764        }
3765    }
3766}
3767
3768/// F-independent prefix of a typed service-client
3769/// callback entry. `#[repr(C)]` guarantees it is the leading member of every
3770/// [`ServiceClientCallbackEntry`] regardless of the closure type `F`, so a
3771/// `ServiceClientCallback` handle can hold a `*mut` to it and send requests
3772/// (serialize → `send_request_raw` → set `pending`) without naming `F`.
3773#[repr(C)]
3774pub struct ServiceClientSendHeader<const REPLY_BUF: usize> {
3775    pub handle: session::RmwServiceClient,
3776    pub reply_buffer: [u8; REPLY_BUF],
3777    pub pending: bool,
3778    /// Set by the transport waker when a reply arrives (mirrors the raw entry).
3779    pub reply_ready: core::sync::atomic::AtomicBool,
3780    /// The id of the call in flight (mirrors the raw entry).
3781    pub sequences: ClientSequences,
3782}
3783
3784/// Typed service-client callback entry (RFC-0041, Phase 239.1). The executor
3785/// eager-drains the reply at `spin_once` and dispatches it as a deserialized
3786/// `Svc::Reply` to the user closure — the typed analogue of
3787/// [`ServiceClientRawArenaEntry`]. The send side goes through the embedded
3788/// [`ServiceClientSendHeader`] (offset 0) via a `ServiceClientCallback` handle.
3789#[repr(C)]
3790pub(crate) struct ServiceClientCallbackEntry<Svc: RosService, F, const REPLY_BUF: usize> {
3791    pub(crate) hdr: ServiceClientSendHeader<REPLY_BUF>,
3792    pub(crate) callback: F,
3793    pub(crate) _phantom: PhantomData<Svc>,
3794}
3795
3796/// Issue 2148 — what a typed callback client hands each reply to. Two shapes:
3797/// [`ReplyOnly`] (`FnMut(&Reply)`, `create_client_with_callback`) and
3798/// [`ReplyWithInfo`] (`FnMut(&Reply, &ServiceInfo)`,
3799/// `create_client_with_callback_with_info`). One dispatch serves both; the
3800/// info is read only for the shape that asks for it.
3801pub(crate) trait ClientReplyCallback<R> {
3802    /// Run the user closure. `info` reads the reply's
3803    /// [`ServiceInfo`](nros_core::ServiceInfo) from the handle that just took
3804    /// it; it is called only by a shape that wants the info.
3805    fn on_reply(&mut self, reply: &R, info: impl FnOnce() -> nros_core::ServiceInfo);
3806}
3807
3808/// Issue 2148 — the reply-only shape (`FnMut(&Reply)`).
3809pub(crate) struct ReplyOnly<F>(pub(crate) F);
3810
3811impl<R, F: FnMut(&R)> ClientReplyCallback<R> for ReplyOnly<F> {
3812    fn on_reply(&mut self, reply: &R, _info: impl FnOnce() -> nros_core::ServiceInfo) {
3813        (self.0)(reply)
3814    }
3815}
3816
3817/// Issue 2148 — the reply-plus-info shape (`FnMut(&Reply, &ServiceInfo)`),
3818/// rclrs's `(Response, ServiceInfo)` and upstream `rmw_take_response`'s
3819/// `rmw_service_info_t`, as [`Promise::take_with_info`](super::handles::Promise::take_with_info)
3820/// reports it.
3821pub(crate) struct ReplyWithInfo<F>(pub(crate) F);
3822
3823impl<R, F: FnMut(&R, &nros_core::ServiceInfo)> ClientReplyCallback<R> for ReplyWithInfo<F> {
3824    fn on_reply(&mut self, reply: &R, info: impl FnOnce() -> nros_core::ServiceInfo) {
3825        let info = info();
3826        (self.0)(reply, &info)
3827    }
3828}
3829
3830/// Monomorphized typed service-client dispatch (RFC-0041, Phase 239.1).
3831///
3832/// Mirrors [`service_client_raw_try_process`] but deserializes the reply into
3833/// `Svc::Reply` and invokes the typed closure. Single in-flight request gated by
3834/// `hdr.pending`; the reply view is dropped before return (no escape).
3835///
3836/// # Safety
3837/// `ptr` must point to a valid, aligned `ServiceClientCallbackEntry<Svc, F, REPLY_BUF>`.
3838pub(crate) unsafe fn service_client_callback_try_process<Svc, F, const REPLY_BUF: usize>(
3839    ptr: *mut u8,
3840    _delta_us: u64,
3841    desc_idx: u8,
3842) -> Result<bool, TransportError>
3843where
3844    Svc: RosService,
3845    F: ClientReplyCallback<Svc::Reply>,
3846{
3847    use core::sync::atomic::Ordering;
3848    let entry = unsafe { &mut *(ptr as *mut ServiceClientCallbackEntry<Svc, F, REPLY_BUF>) };
3849
3850    if !entry.hdr.pending {
3851        return Ok(false);
3852    }
3853    entry.hdr.reply_ready.store(false, Ordering::Release);
3854
3855    // Issue 2009 — see `service_client_raw_try_process`.
3856    let ServiceClientSendHeader {
3857        handle,
3858        reply_buffer,
3859        sequences,
3860        ..
3861    } = &mut entry.hdr;
3862    match take_client_reply(handle, reply_buffer, sequences) {
3863        Ok(Some((len, _seq))) => {
3864            entry.hdr.pending = false;
3865            let mut reader = CdrReader::new_with_header(&entry.hdr.reply_buffer[..len])
3866                .map_err(|_| TransportError::DeserializationError)?;
3867            // Fully-qualify the `Deserialize` trait (mirrors the
3868            // `DeserializeView` call above): arena.rs imports
3869            // `DeserializeView` but not `Deserialize`, so the bare
3870            // `Svc::Reply::deserialize` only resolved when a default/std feature
3871            // happened to glob it into scope — under `rmw-cffi` (embedded) it
3872            // failed E0599. The fully-qualified path resolves under every feature.
3873            let reply = <Svc::Reply as nros_serdes::Deserialize>::deserialize(&mut reader)
3874                .map_err(|_| TransportError::DeserializationError)?;
3875            // Phase 8 — hooked AFTER both deserialization `?`s. Placing the
3876            // start any earlier would let a `DeserializationError` return
3877            // between start and end and leave an unbalanced span; here the
3878            // callback is the only thing between the pair, so the measured
3879            // interval is user code and nothing else.
3880            // Issue 2148 — the info is read from the handle that matched this
3881            // reply, before anything else can take on it (as
3882            // `Promise::take_with_info` does); only the with-info shape reads it,
3883            // and that one copy of a plain struct is inside the span.
3884            //
3885            // Phase-573 W2b (RFC-0108 D9) — the callback may send the next
3886            // request through its `ServiceClientCallback`, which writes this
3887            // entry's send header. So the info closure holds the entry's
3888            // POINTER, not a reference into `hdr` (a reference captured in a
3889            // closure argument is protected for the whole `on_reply` call),
3890            // and reads the handle only when the with-info shape asks.
3891            let info = || {
3892                // SAFETY: `ptr` is this entry (the fn's contract). The shared
3893                // borrow covers the handle's bytes alone (never `callback`,
3894                // which `on_reply` is running) and ends with this one read.
3895                let handle = unsafe {
3896                    &*core::ptr::addr_of!(
3897                        (*(ptr as *const ServiceClientCallbackEntry<Svc, F, REPLY_BUF>))
3898                            .hdr
3899                            .handle
3900                    )
3901                };
3902                nros_rmw::ClientTrait::response_info(handle)
3903            };
3904            trace_cb_start(desc_idx);
3905            entry.callback.on_reply(&reply, info);
3906            trace_cb_end(desc_idx);
3907            Ok(true)
3908        }
3909        Ok(None) => Ok(false),
3910        Err(_) => {
3911            entry.hdr.pending = false;
3912            Err(TransportError::ServiceRequestFailed)
3913        }
3914    }
3915}
3916
3917/// Typed action-client callback entry (RFC-0041, Phase 239.2). The executor
3918/// eager-drains the three client receives (goal-response / feedback / result)
3919/// at `spin_once` and dispatches them as deserialized `A::Feedback` / `A::Result`
3920/// to typed closures — the typed analogue of [`ActionClientRawArenaEntry`]. The
3921/// send side (`send_goal` / `get_result`) goes through the embedded `core`
3922/// (offset 0) via an `ActionClientCallback` handle.
3923#[repr(C)]
3924pub(crate) struct ActionClientCallbackEntry<
3925    A: RosAction,
3926    GRespF,
3927    FbF,
3928    ResF,
3929    const GOAL_BUF: usize,
3930    const RESULT_BUF: usize,
3931    const FEEDBACK_BUF: usize,
3932> {
3933    pub(crate) core: ActionClientCore<GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>,
3934    /// RFC-0041 / Phase 239.5 — the feedback stream's QoS-depth buffer. The
3935    /// callback path drains `core.feedback_subscriber` directly into this ring
3936    /// (depth > 1) or triple-buffer (depth ≤ 1), so a burst of feedbacks between
3937    /// spins is buffered/reported instead of overwriting a single slot — and the
3938    /// shared `ActionClientCore` buffers (the `Promise` path) stay untouched.
3939    pub(crate) feedback_buffer: BufferStrategy,
3940    pub(crate) on_goal_response: GRespF,
3941    pub(crate) on_feedback: FbF,
3942    pub(crate) on_result: ResF,
3943    pub(crate) _phantom: PhantomData<A>,
3944}
3945
3946/// Decode one raw feedback slot (outer header + GoalUuid at [4..20] + inner-CDR
3947/// payload at `offset`) and invoke the typed feedback closure (Phase 239.5).
3948///
3949/// `desc_idx` is threaded in purely so the Phase 8 callback-trace pair can
3950/// live at the invocation itself. This function has no entry and no slot of
3951/// its own to recover an identity from, and it returns WITHOUT firing on a
3952/// short payload or a failed field read — so bracketing its two call sites
3953/// instead would report invocations that never happened.
3954#[inline]
3955fn dispatch_feedback<A, F, const FEEDBACK_BUF: usize>(
3956    data: &[u8],
3957    on_feedback: &mut F,
3958    desc_idx: u8,
3959) where
3960    A: RosAction,
3961    F: FnMut(&nros_core::GoalUuid, &A::Feedback),
3962{
3963    // Issue 2014 — offsets from `action_frame`.
3964    let (Some(goal_id), Some(fields)) = (
3965        crate::action_frame::feedback_goal_id(data),
3966        crate::action_frame::feedback_fields(data),
3967    ) else {
3968        return;
3969    };
3970    // #175 — restore the feedback's per-message encap if a typed transport
3971    // framing (Cyclone) stripped it; the message's top-level encap is `data[0..4]`.
3972    //
3973    // Phase 8 — hooked INSIDE the `if let Some(fb)`: the early `return`
3974    // above and a `None` from `read_action_field` both leave the user
3975    // closure un-run, and neither may emit a span.
3976    if let Some(fb) = read_action_field::<A::Feedback, FEEDBACK_BUF>(data, fields) {
3977        trace_cb_start(desc_idx);
3978        on_feedback(&goal_id, &fb);
3979        trace_cb_end(desc_idx);
3980    }
3981}
3982
3983/// Monomorphized typed action-client dispatch (RFC-0041, Phase 239.2). Mirrors
3984/// [`action_client_raw_try_process`] but deserializes the feedback / result
3985/// payloads into `A::Feedback` / `A::Result` and invokes the typed closures.
3986///
3987/// # Safety
3988/// `ptr` must point to a valid, aligned `ActionClientCallbackEntry<…>`.
3989#[allow(clippy::type_complexity)]
3990pub(crate) unsafe fn action_client_callback_try_process<
3991    A,
3992    GRespF,
3993    FbF,
3994    ResF,
3995    const GOAL_BUF: usize,
3996    const RESULT_BUF: usize,
3997    const FEEDBACK_BUF: usize,
3998>(
3999    ptr: *mut u8,
4000    _delta_us: u64,
4001    desc_idx: u8,
4002) -> Result<bool, TransportError>
4003where
4004    A: RosAction,
4005    GRespF: FnMut(&nros_core::GoalUuid, bool),
4006    FbF: FnMut(&nros_core::GoalUuid, &A::Feedback),
4007    ResF: FnMut(&nros_core::GoalUuid, nros_core::GoalStatusCode, &A::Result),
4008{
4009    type Entry<A, G, Fb, R, const GB: usize, const RB: usize, const FB: usize> =
4010        ActionClientCallbackEntry<A, G, Fb, R, GB, RB, FB>;
4011    // Phase-573 W2b (RFC-0108 D9) — a callback may send through its
4012    // `ActionClientCallback` (`send_goal`, `get_result`), which writes this
4013    // entry's `core`. So each step takes a fresh reference from `ptr`, and no
4014    // borrow of `core` taken before a callback is used after it.
4015    //
4016    // SAFETY (each use): `ptr` points to a valid entry (this fn's contract).
4017    let entry = || unsafe {
4018        &mut *(ptr as *mut Entry<A, GRespF, FbF, ResF, GOAL_BUF, RESULT_BUF, FEEDBACK_BUF>)
4019    };
4020
4021    let mut did_work = false;
4022
4023    // 1. Goal-acceptance reply (single-outstanding → gated single buffer).
4024    // Issue 2009 — the goal is the one the reply's request was ABOUT, not the
4025    // most recently sent one.
4026    if let Ok(Some((total_len, goal_id))) = entry().core.try_recv_send_goal_reply_for() {
4027        let e = entry();
4028        let accepted = crate::action_frame::goal_accepted(&e.core.result_buffer[..total_len]);
4029        // Phase 8 — hooked inside the `Ok(Some(..))` arm; an empty poll is
4030        // the common case and runs no user code.
4031        trace_cb_start(desc_idx);
4032        (e.on_goal_response)(&goal_id, accepted);
4033        trace_cb_end(desc_idx);
4034        did_work = true;
4035    }
4036
4037    // 2. Feedback — a stream: drain `feedback_subscriber` into the QoS-depth ring
4038    //    (Phase 239.5), then dispatch each slot. Each slot holds the raw feedback
4039    //    message: outer CDR header (4) + GoalUuid (16) + inner-CDR payload; see the
4040    //    raw dispatcher for the layout rationale (233.6).
4041    {
4042        // The callbacks below may write `core`; nothing in this block uses
4043        // `core` after one runs (the ring loop pops only from the ring).
4044        let ActionClientCallbackEntry {
4045            core,
4046            feedback_buffer,
4047            on_feedback,
4048            ..
4049        } = entry();
4050        match feedback_buffer {
4051            BufferStrategy::Triple(tb) => {
4052                let slot = tb.write_slot();
4053                if let Ok(Some(len)) = core.feedback_subscriber.take_serialized(slot) {
4054                    tb.writer_publish(len);
4055                }
4056                if let Some((data, len)) = tb.reader_acquire() {
4057                    // Phase 8 — the pair lives INSIDE `dispatch_feedback`
4058                    // (it can return without firing); `desc_idx` is threaded
4059                    // in so the leaf can name itself.
4060                    dispatch_feedback::<A, _, FEEDBACK_BUF>(&data[..len], on_feedback, desc_idx);
4061                    did_work = true;
4062                }
4063            }
4064            BufferStrategy::Ring(ring) => {
4065                while let Some(slot) = ring.try_push() {
4066                    match core.feedback_subscriber.take_serialized(slot) {
4067                        Ok(Some(len)) => ring.commit_push(len),
4068                        _ => break,
4069                    }
4070                }
4071                while let Some((data, len)) = ring.try_pop() {
4072                    // Phase 8 — one pair per drained slot, emitted by
4073                    // `dispatch_feedback` itself, so a ring draining N
4074                    // messages reports N invocations rather than one.
4075                    dispatch_feedback::<A, _, FEEDBACK_BUF>(&data[..len], on_feedback, desc_idx);
4076                    ring.commit_pop();
4077                    did_work = true;
4078                }
4079            }
4080        }
4081    }
4082
4083    // 3. Result reply — status at byte 4, payload at [8 ..] (header + status +
4084    //    align pad); see the raw dispatcher (Phase 96.1).
4085    if let Ok(Some((total_len, goal_id))) = entry().core.try_recv_get_result_reply_for() {
4086        let e = entry();
4087        let reply = &e.core.result_buffer[..total_len];
4088        // Issue 2014 — status and payload offset from `action_frame`.
4089        if let (Some(status), Some(fields)) = (
4090            crate::action_frame::result_status(reply),
4091            crate::action_frame::result_fields(reply),
4092        ) {
4093            // #175 — restore the result's per-message encap if a typed transport
4094            // framing (Cyclone) stripped it; the reply's top-level encap is
4095            // `reply[0..4]`.
4096            if let Some(res) = read_action_field::<A::Result, RESULT_BUF>(reply, fields) {
4097                // Phase 8 — inside the `Some(res)` arm: a failed
4098                // deserialize leaves `on_result` un-run and must emit
4099                // nothing. Distinct callback, its own pair.
4100                trace_cb_start(desc_idx);
4101                (e.on_result)(&goal_id, status, &res);
4102                trace_cb_end(desc_idx);
4103            }
4104        }
4105        did_work = true;
4106    }
4107
4108    Ok(did_work)
4109}
4110
4111/// Issue 2081 — how a raw service entry calls its callback: with the request
4112/// bytes alone, or with the request's id beside them.
4113pub(crate) trait RawServiceDispatch: Copy {
4114    /// Call the callback for one taken request. `handle` is the server the
4115    /// request was just taken from, so its `request_info()` describes it.
4116    ///
4117    /// # Safety
4118    /// The pointers are the dispatch's own buffers, valid for the call.
4119    #[allow(clippy::too_many_arguments)]
4120    unsafe fn invoke(
4121        self,
4122        handle: &session::RmwServiceServer,
4123        req: *const u8,
4124        req_len: usize,
4125        resp: *mut u8,
4126        resp_cap: usize,
4127        resp_len: *mut usize,
4128        context: *mut core::ffi::c_void,
4129    ) -> bool;
4130}
4131
4132impl RawServiceDispatch for RawServiceCallback {
4133    unsafe fn invoke(
4134        self,
4135        _handle: &session::RmwServiceServer,
4136        req: *const u8,
4137        req_len: usize,
4138        resp: *mut u8,
4139        resp_cap: usize,
4140        resp_len: *mut usize,
4141        context: *mut core::ffi::c_void,
4142    ) -> bool {
4143        unsafe { self(req, req_len, resp, resp_cap, resp_len, context) }
4144    }
4145}
4146
4147impl RawServiceDispatch for RawServiceRequestIdCallback {
4148    unsafe fn invoke(
4149        self,
4150        handle: &session::RmwServiceServer,
4151        req: *const u8,
4152        req_len: usize,
4153        resp: *mut u8,
4154        resp_cap: usize,
4155        resp_len: *mut usize,
4156        context: *mut core::ffi::c_void,
4157    ) -> bool {
4158        // The take that just succeeded is the one `request_info` describes.
4159        let mut id = RawRequestId::from_service_info(&nros_rmw::ServiceTrait::request_info(handle));
4160        unsafe { self(req, req_len, &mut id, resp, resp_cap, resp_len, context) }
4161    }
4162}
4163
4164/// Monomorphized raw service dispatch function.
4165///
4166/// # Safety
4167/// `ptr` must point to a valid, aligned `SrvRawEntry<REQ_BUF, REPLY_BUF, C>`.
4168pub(crate) unsafe fn srv_raw_try_process<
4169    const REQ_BUF: usize,
4170    const REPLY_BUF: usize,
4171    C: RawServiceDispatch,
4172>(
4173    ptr: *mut u8,
4174    _delta_us: u64,
4175    desc_idx: u8,
4176) -> Result<bool, TransportError> {
4177    let entry = unsafe { &mut *(ptr as *mut SrvRawEntry<REQ_BUF, REPLY_BUF, C>) };
4178    let SrvRawEntry {
4179        handle,
4180        req_buffer,
4181        reply_buffer,
4182        callback,
4183        context,
4184        capture: _,
4185    } = entry;
4186    let buf_start = req_buffer.as_ptr() as usize;
4187    let (data_offset, data_len, seq_num) = match handle.take_request(req_buffer) {
4188        Ok(Some(request)) => {
4189            let offset = (request.data.as_ptr() as usize).saturating_sub(buf_start);
4190            let len = request.data.len();
4191            let seq = request.sequence_number;
4192            (offset, len, seq)
4193        }
4194        Ok(None) => return Ok(false),
4195        // issue 1088 — a request is pending and the backend has no free
4196        // reply-correlation slot. Keep the KIND: rewriting it to
4197        // `ServiceReplyFailed` made a saturated server read as a broken one in
4198        // `SpinOnceResult`, and hid the one condition the caller can act on.
4199        Err(TransportError::WouldBlock) => return Err(TransportError::WouldBlock),
4200        Err(_) => return Err(TransportError::ServiceReplyFailed),
4201    };
4202
4203    let mut resp_len: usize = 0;
4204    // Phase 8 — hooked below the `Ok(None) => return Ok(false)` arm of the
4205    // receive, so an empty poll emits nothing. The `?` on `send_response`
4206    // sits AFTER `trace_cb_end`, so no early exit can strand an open span.
4207    trace_cb_start(desc_idx);
4208    let ok = unsafe {
4209        callback.invoke(
4210            handle,
4211            req_buffer.as_ptr().add(data_offset),
4212            data_len,
4213            reply_buffer.as_mut_ptr(),
4214            REPLY_BUF,
4215            &mut resp_len,
4216            *context,
4217        )
4218    };
4219    trace_cb_end(desc_idx);
4220    if ok && resp_len > 0 {
4221        handle
4222            .send_response(seq_num, &reply_buffer[..resp_len])
4223            .map_err(|_| TransportError::ServiceReplyFailed)?;
4224    }
4225    Ok(true)
4226}
4227
4228/// Monomorphized guard condition dispatch function.
4229///
4230/// # Safety
4231/// `ptr` must point to a valid, aligned `GuardConditionEntry<F>`.
4232pub(crate) unsafe fn guard_try_process<F>(
4233    ptr: *mut u8,
4234    _delta_us: u64,
4235    desc_idx: u8,
4236) -> Result<bool, TransportError>
4237where
4238    F: FnMut(),
4239{
4240    let entry = unsafe { &mut *(ptr as *mut GuardConditionEntry<F>) };
4241    if entry.flag.swap(false, portable_atomic::Ordering::AcqRel) {
4242        // Phase 8 — hooked inside the flag-consuming branch, the same shape
4243        // as `timer_try_process`. A guard is polled on every spin and is
4244        // almost always un-triggered, so `Ok(false)` is the common outcome
4245        // and must stay silent.
4246        trace_cb_start(desc_idx);
4247        (entry.callback)();
4248        trace_cb_end(desc_idx);
4249        Ok(true)
4250    } else {
4251        Ok(false)
4252    }
4253}
4254
4255// ============================================================================
4256// Readiness check functions
4257// ============================================================================
4258
4259/// SubInfoEntry readiness.
4260///
4261/// # Safety
4262/// `ptr` must point to a valid `SubInfoEntry<M, F>`.
4263pub(crate) unsafe fn sub_info_has_data<M, F>(ptr: *const u8) -> bool {
4264    let entry = unsafe { &*(ptr as *const SubInfoEntry<M, F>) };
4265    entry.handle.has_data()
4266}
4267
4268/// SubSafetyEntry readiness.
4269///
4270/// # Safety
4271/// `ptr` must point to a valid `SubSafetyEntry<M, F>`.
4272#[cfg(feature = "safety-e2e")]
4273pub(crate) unsafe fn sub_safety_has_data<M, F>(ptr: *const u8) -> bool {
4274    let entry = unsafe { &*(ptr as *const SubSafetyEntry<M, F>) };
4275    entry.handle.has_data()
4276}
4277
4278/// Service readiness: check `has_request()` on the service handle.
4279///
4280/// # Safety
4281/// `ptr` must point to a valid `SrvEntry<Svc, F, RQ, RP>`.
4282pub(crate) unsafe fn srv_has_data<Svc: RosService, F, const RQ: usize, const RP: usize>(
4283    ptr: *const u8,
4284) -> bool {
4285    let entry = unsafe { &*(ptr as *const SrvEntry<Svc, F, RQ, RP>) };
4286    entry.handle.has_request()
4287}
4288
4289/// Raw service readiness.
4290///
4291/// # Safety
4292/// `ptr` must point to a valid `SrvRawEntry<RQ, RP, C>`.
4293pub(crate) unsafe fn srv_raw_has_data<const RQ: usize, const RP: usize, C: RawServiceDispatch>(
4294    ptr: *const u8,
4295) -> bool {
4296    let entry = unsafe { &*(ptr as *const SrvRawEntry<RQ, RP, C>) };
4297    entry.handle.has_request()
4298}
4299
4300/// Guard condition readiness: check the atomic flag.
4301///
4302/// # Safety
4303/// `ptr` must point to a valid `GuardConditionEntry<F>`.
4304pub(crate) unsafe fn guard_has_data<F>(ptr: *const u8) -> bool {
4305    let entry = unsafe { &*(ptr as *const GuardConditionEntry<F>) };
4306    entry.flag.load(portable_atomic::Ordering::Acquire)
4307}
4308
4309/// Timers and action entries are always considered ready.
4310pub(crate) unsafe fn always_ready(_ptr: *const u8) -> bool {
4311    true
4312}
4313
4314// ============================================================================
4315// LET pre-sample functions
4316// ============================================================================
4317
4318/// Pre-sample a typed subscription with MessageInfo for LET mode.
4319///
4320/// # Safety
4321/// `ptr` must point to a valid, aligned `SubInfoEntry<M, F>`.
4322pub(crate) unsafe fn sub_info_pre_sample<M, F>(ptr: *mut u8) {
4323    let entry = unsafe { &mut *(ptr as *mut SubInfoEntry<M, F>) };
4324    // For LET, we sample only the data (MessageInfo is not preserved in the snapshot)
4325    entry.sampled_len = match entry.handle.take_serialized(entry.buffer.as_mut_slice()) {
4326        Ok(Some(len)) => len,
4327        _ => 0,
4328    };
4329}
4330
4331/// Pre-sample a safety subscription for LET mode.
4332///
4333/// # Safety
4334/// `ptr` must point to a valid, aligned `SubSafetyEntry<M, F>`.
4335#[cfg(feature = "safety-e2e")]
4336pub(crate) unsafe fn sub_safety_pre_sample<M, F>(ptr: *mut u8) {
4337    let entry = unsafe { &mut *(ptr as *mut SubSafetyEntry<M, F>) };
4338    entry.sampled_len = match entry.handle.take_serialized(entry.buffer.as_mut_slice()) {
4339        Ok(Some(len)) => len,
4340        _ => 0,
4341    };
4342}
4343
4344/// No-op pre-sample for non-subscription entries (services, timers, etc.).
4345pub(crate) unsafe fn no_pre_sample(_ptr: *mut u8) {}
4346
4347// ============================================================================
4348// Monomorphized handle operation functions
4349// ============================================================================
4350
4351/// Action server: publish feedback via arena entry.
4352///
4353/// # Safety
4354/// `ptr` must point to a valid `ActionServerArenaEntry`.
4355pub(crate) unsafe fn as_publish_feedback<
4356    A,
4357    GoalF,
4358    CancelF,
4359    const GB: usize,
4360    const RB: usize,
4361    const FB: usize,
4362    const MG: usize,
4363>(
4364    ptr: *mut u8,
4365    goal_id: &nros_core::GoalUuid,
4366    feedback: &A::Feedback,
4367) -> Result<(), NodeError>
4368where
4369    A: RosAction,
4370{
4371    // Phase-573 W2b — the server's bytes only, never the callbacks': this
4372    // is reached from inside a running callback, which holds its own.
4373    let server = unsafe {
4374        &mut *core::ptr::addr_of_mut!(
4375            (*(ptr as *mut ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4376        )
4377    };
4378    server.publish_feedback(goal_id, feedback)
4379}
4380
4381/// Action server: complete a goal via arena entry.
4382///
4383/// # Safety
4384/// `ptr` must point to a valid `ActionServerArenaEntry`.
4385pub(crate) unsafe fn as_complete_goal<
4386    A,
4387    GoalF,
4388    CancelF,
4389    const GB: usize,
4390    const RB: usize,
4391    const FB: usize,
4392    const MG: usize,
4393>(
4394    ptr: *mut u8,
4395    goal_id: &nros_core::GoalUuid,
4396    status: nros_core::GoalStatusCode,
4397    result: A::Result,
4398) -> Result<(), NodeError>
4399where
4400    A: RosAction,
4401{
4402    // Phase-573 W2b — the server's bytes only, never the callbacks': this
4403    // is reached from inside a running callback, which holds its own.
4404    let server = unsafe {
4405        &mut *core::ptr::addr_of_mut!(
4406            (*(ptr as *mut ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4407        )
4408    };
4409    server.complete_goal(goal_id, status, result)
4410}
4411
4412/// Action server: set goal status via arena entry.
4413///
4414/// # Safety
4415/// `ptr` must point to a valid `ActionServerArenaEntry`.
4416pub(crate) unsafe fn as_set_goal_status<
4417    A,
4418    GoalF,
4419    CancelF,
4420    const GB: usize,
4421    const RB: usize,
4422    const FB: usize,
4423    const MG: usize,
4424>(
4425    ptr: *mut u8,
4426    goal_id: &nros_core::GoalUuid,
4427    status: nros_core::GoalStatusCode,
4428) where
4429    A: RosAction,
4430{
4431    // Phase-573 W2b — the server's bytes only, never the callbacks': this
4432    // is reached from inside a running callback, which holds its own.
4433    let server = unsafe {
4434        &mut *core::ptr::addr_of_mut!(
4435            (*(ptr as *mut ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4436        )
4437    };
4438    server.set_goal_status(goal_id, status);
4439}
4440
4441/// Action server: get active goal count via arena entry.
4442///
4443/// # Safety
4444/// `ptr` must point to a valid `ActionServerArenaEntry`.
4445pub(crate) unsafe fn as_active_goal_count<
4446    A,
4447    GoalF,
4448    CancelF,
4449    const GB: usize,
4450    const RB: usize,
4451    const FB: usize,
4452    const MG: usize,
4453>(
4454    ptr: *const u8,
4455) -> usize
4456where
4457    A: RosAction,
4458{
4459    // Phase-573 W2b — the server's bytes only, as `as_complete_goal`.
4460    let server = unsafe {
4461        &*core::ptr::addr_of!(
4462            (*(ptr as *const ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4463        )
4464    };
4465    server.active_goal_count()
4466}
4467
4468/// Action server: eagerly reclaim delivered results — phase-417 W4.b.
4469///
4470/// # Safety
4471/// `ptr` must point to a valid `ActionServerArenaEntry`.
4472pub(crate) unsafe fn as_expire_goals<
4473    A,
4474    GoalF,
4475    CancelF,
4476    const GB: usize,
4477    const RB: usize,
4478    const FB: usize,
4479    const MG: usize,
4480>(
4481    ptr: *mut u8,
4482) -> usize
4483where
4484    A: RosAction,
4485{
4486    // Phase-573 W2b — the server's bytes only, never the callbacks': this
4487    // is reached from inside a running callback, which holds its own.
4488    let server = unsafe {
4489        &mut *core::ptr::addr_of_mut!(
4490            (*(ptr as *mut ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4491        )
4492    };
4493    server.expire_goals()
4494}
4495
4496/// Action server: does this server still know `goal_id`? — phase-417 W4.b.
4497///
4498/// # Safety
4499/// `ptr` must point to a valid `ActionServerArenaEntry`.
4500pub(crate) unsafe fn as_goal_exists<
4501    A,
4502    GoalF,
4503    CancelF,
4504    const GB: usize,
4505    const RB: usize,
4506    const FB: usize,
4507    const MG: usize,
4508>(
4509    ptr: *const u8,
4510    goal_id: &nros_core::GoalUuid,
4511) -> bool
4512where
4513    A: RosAction,
4514{
4515    // Phase-573 W2b — the server's bytes only, as `as_complete_goal`.
4516    let server = unsafe {
4517        &*core::ptr::addr_of!(
4518            (*(ptr as *const ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4519        )
4520    };
4521    server.goal_exists(goal_id)
4522}
4523
4524/// Raw action server: publish feedback via arena entry.
4525///
4526/// # Safety
4527/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4528pub(crate) unsafe fn as_raw_publish_feedback<
4529    const GB: usize,
4530    const RB: usize,
4531    const FB: usize,
4532    const MG: usize,
4533>(
4534    ptr: *mut u8,
4535    goal_id: &nros_core::GoalUuid,
4536    feedback_data: *const u8,
4537    feedback_len: usize,
4538) -> Result<(), NodeError> {
4539    let entry = unsafe { &mut *(ptr as *mut ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4540    let feedback_cdr = unsafe { core::slice::from_raw_parts(feedback_data, feedback_len) };
4541    entry.core.publish_feedback_raw(goal_id, feedback_cdr)
4542}
4543
4544/// Raw action server: complete a goal via arena entry.
4545///
4546/// # Safety
4547/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4548pub(crate) unsafe fn as_raw_complete_goal<
4549    const GB: usize,
4550    const RB: usize,
4551    const FB: usize,
4552    const MG: usize,
4553>(
4554    ptr: *mut u8,
4555    goal_id: &nros_core::GoalUuid,
4556    status: nros_core::GoalStatusCode,
4557    result_data: *const u8,
4558    result_len: usize,
4559) -> Result<(), NodeError> {
4560    let entry = unsafe { &mut *(ptr as *mut ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4561    let result_cdr = unsafe { core::slice::from_raw_parts(result_data, result_len) };
4562    entry.core.complete_goal_raw(goal_id, status, result_cdr)
4563}
4564
4565/// Raw action server: set goal status via arena entry.
4566///
4567/// # Safety
4568/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4569pub(crate) unsafe fn as_raw_set_goal_status<
4570    const GB: usize,
4571    const RB: usize,
4572    const FB: usize,
4573    const MG: usize,
4574>(
4575    ptr: *mut u8,
4576    goal_id: &nros_core::GoalUuid,
4577    status: nros_core::GoalStatusCode,
4578) {
4579    let entry = unsafe { &mut *(ptr as *mut ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4580    entry.core.set_goal_status(goal_id, status);
4581}
4582
4583/// Raw action server: get active goal count via arena entry.
4584///
4585/// # Safety
4586/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4587pub(crate) unsafe fn as_raw_active_goal_count<
4588    const GB: usize,
4589    const RB: usize,
4590    const FB: usize,
4591    const MG: usize,
4592>(
4593    ptr: *const u8,
4594) -> usize {
4595    let entry = unsafe { &*(ptr as *const ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4596    entry.core.active_goal_count()
4597}
4598
4599/// Raw action server: eagerly reclaim delivered results — phase-417 W4.b.
4600///
4601/// # Safety
4602/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4603pub(crate) unsafe fn as_raw_expire_goals<
4604    const GB: usize,
4605    const RB: usize,
4606    const FB: usize,
4607    const MG: usize,
4608>(
4609    ptr: *mut u8,
4610) -> usize {
4611    let entry = unsafe { &mut *(ptr as *mut ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4612    entry.core.expire_completed_results()
4613}
4614
4615/// Raw action server: does this server still know `goal_id`? — phase-417 W4.b.
4616///
4617/// # Safety
4618/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4619pub(crate) unsafe fn as_raw_goal_exists<
4620    const GB: usize,
4621    const RB: usize,
4622    const FB: usize,
4623    const MG: usize,
4624>(
4625    ptr: *const u8,
4626    goal_id: &nros_core::GoalUuid,
4627) -> bool {
4628    let entry = unsafe { &*(ptr as *const ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4629    entry.core.goal_exists(goal_id)
4630}
4631
4632/// Raw action server: iterate active goals via arena entry.
4633///
4634/// # Safety
4635/// `ptr` must point to a valid `ActionServerRawArenaEntry`.
4636pub(crate) unsafe fn as_raw_for_each_active_goal<
4637    const GB: usize,
4638    const RB: usize,
4639    const FB: usize,
4640    const MG: usize,
4641>(
4642    ptr: *const u8,
4643    f: &mut dyn FnMut(&super::action_core::RawActiveGoal),
4644) {
4645    let entry = unsafe { &*(ptr as *const ActionServerRawArenaEntry<GB, RB, FB, MG>) };
4646    for goal in entry.core.active_goals() {
4647        f(goal);
4648    }
4649}
4650
4651/// Action server: iterate active goals via arena entry.
4652///
4653/// Calls `f` for each active goal, reconstructing `ActiveGoal<A>` from
4654/// the core's `RawActiveGoal` and the parallel typed goals vec.
4655///
4656/// # Safety
4657/// `ptr` must point to a valid `ActionServerArenaEntry`.
4658pub(crate) unsafe fn as_for_each_active_goal<
4659    A,
4660    GoalF,
4661    CancelF,
4662    const GB: usize,
4663    const RB: usize,
4664    const FB: usize,
4665    const MG: usize,
4666>(
4667    ptr: *const u8,
4668    f: &mut dyn FnMut(&ActiveGoal<A>),
4669) where
4670    A: RosAction + 'static,
4671    A::Goal: Clone,
4672{
4673    // Phase-573 W2b — the server's bytes only, as `as_complete_goal`.
4674    let server = unsafe {
4675        &*core::ptr::addr_of!(
4676            (*(ptr as *const ActionServerArenaEntry<A, GoalF, CancelF, GB, RB, FB, MG>)).server
4677        )
4678    };
4679    for (i, raw_goal) in server.core.active_goals().iter().enumerate() {
4680        let active = ActiveGoal {
4681            goal_id: raw_goal.goal_id,
4682            status: raw_goal.status,
4683            goal: server.typed_goals[i].clone(),
4684        };
4685        f(&active);
4686    }
4687}
4688
4689#[cfg(test)]
4690mod borrowed_sub_tests {
4691    use nros_core::{CdrReader, CdrWriter, DeserError};
4692
4693    use super::*;
4694
4695    // Hand-written borrowed message mirroring what codegen will emit for
4696    // `{ uint32 width; uint8[] data; }` in `borrowed` mode (Phase 229.6).
4697    struct ImageView<'a> {
4698        width: u32,
4699        data: &'a [u8],
4700    }
4701
4702    impl<'a> DeserializeView<'a> for ImageView<'a> {
4703        fn deserialize_view(reader: &mut CdrReader<'a>) -> Result<Self, DeserError> {
4704            let width = reader.read_u32()?;
4705            let data = reader.read_slice_u8()?;
4706            Ok(ImageView { width, data })
4707        }
4708    }
4709
4710    // Zero-sized borrowed-family marker (codegen emits `struct ImageViewable;`).
4711    struct ImageViewable;
4712    impl ViewableMessage for ImageViewable {
4713        type View<'a> = ImageView<'a>;
4714        const TYPE_NAME: &'static str = "test_msgs::msg::dds_::Image_";
4715        const TYPE_HASH: &'static str = "borrowed-test-hash";
4716    }
4717
4718    // The borrowed view must alias the source CDR buffer (no `heapless::Vec`
4719    // copy) — the whole point of `borrowed` mode (issue 0007).
4720    #[test]
4721    fn borrowed_view_is_zero_copy_into_source_buffer() {
4722        let payload: [u8; 64] = core::array::from_fn(|i| i as u8);
4723        let mut buf = [0u8; 128];
4724        let written = {
4725            let mut w = CdrWriter::new_with_header(&mut buf).unwrap();
4726            w.write_u32(7).unwrap();
4727            w.write_sequence_len(payload.len()).unwrap();
4728            w.write_bytes(&payload).unwrap();
4729            w.position()
4730        };
4731
4732        let mut reader = CdrReader::new_with_header(&buf[..written]).unwrap();
4733        let view = ImageView::deserialize_view(&mut reader).unwrap();
4734
4735        assert_eq!(view.width, 7);
4736        assert_eq!(view.data, &payload[..]);
4737
4738        // The borrowed slice points INTO `buf`, proving zero-copy.
4739        let buf_start = buf.as_ptr() as usize;
4740        let buf_end = buf_start + buf.len();
4741        let data_ptr = view.data.as_ptr() as usize;
4742        assert!(
4743            data_ptr >= buf_start && data_ptr < buf_end,
4744            "borrowed data must alias the source buffer (zero-copy)"
4745        );
4746    }
4747
4748    // Phase 231 Wave 3 (RFC-0038) — single-copy proof. The in-place subscription
4749    // entry carries handle + callback only; the buffered entry additionally
4750    // carries the arena `BufferStrategy` (the copy-#1 staging buffer). So the
4751    // in-place entry is strictly smaller — proving the arena buffer (and copy #1)
4752    // is gone for backends that support in-place dispatch.
4753    #[test]
4754    fn inplace_entry_drops_the_arena_buffer() {
4755        type Cb = fn(&u32);
4756        assert!(
4757            core::mem::size_of::<SubInplaceEntry<u32, Cb>>()
4758                < core::mem::size_of::<SubBufferedEntry<u32, Cb>>(),
4759            "in-place entry must be smaller than the buffered entry (no arena BufferStrategy)"
4760        );
4761    }
4762
4763    // Compile-time proof that the codegen marker + GAT + a borrowed closure
4764    // satisfy exactly the bounds the executor's borrowed dispatch
4765    // (`sub_buffered_view_try_process`) and registration require.
4766    fn assert_borrowed_sub_bounds<B, F>(_callback: F)
4767    where
4768        B: ViewableMessage + 'static,
4769        F: for<'a> FnMut(&B::View<'a>) + 'static,
4770    {
4771    }
4772
4773    #[test]
4774    fn borrowed_marker_satisfies_dispatch_bounds() {
4775        assert_borrowed_sub_bounds::<ImageViewable, _>(|view: &ImageView<'_>| {
4776            let _ = view.width;
4777            let _ = view.data.len();
4778        });
4779    }
4780}
4781
4782/// RFC-0069 / issues 0418 + 0035 — the action payload envelope carries exactly
4783/// ONE CDR header, and reading it back must not eat a data word.
4784///
4785/// The RFC lists this as the acceptance item "most likely to be skipped: its
4786/// absence is why the divergence survived a redesign in the first place." These
4787/// sit at the level the corruption happens — `read_action_field`, the consumer
4788/// half of the 0418 producer/consumer pair.
4789#[cfg(test)]
4790mod action_envelope_tests {
4791    use nros_core::{CdrWriter, Deserialize, Serialize};
4792
4793    use super::*;
4794
4795    /// Three `int32`s. The FIRST is the one that matters: give it the value 256
4796    /// and the body's leading bytes are `00 01 00 00` — byte for byte the
4797    /// little-endian CDR encapsulation header.
4798    #[derive(Debug, PartialEq)]
4799    struct Body {
4800        first: i32,
4801        rest: [i32; 2],
4802    }
4803
4804    impl Serialize for Body {
4805        fn serialize(&self, w: &mut CdrWriter) -> Result<(), nros_serdes::SerError> {
4806            w.write_i32(self.first)?;
4807            for v in &self.rest {
4808                w.write_i32(*v)?;
4809            }
4810            Ok(())
4811        }
4812    }
4813
4814    impl Deserialize for Body {
4815        fn deserialize(r: &mut CdrReader) -> Result<Self, nros_serdes::DeserError> {
4816            Ok(Body {
4817                first: r.read_i32()?,
4818                rest: [r.read_i32()?, r.read_i32()?],
4819            })
4820        }
4821    }
4822
4823    const LE_ENCAP: [u8; 4] = [0x00, 0x01, 0x00, 0x00];
4824
4825    /// Serialize the way the 0418 PRODUCER does: fields only, no inner header.
4826    fn produce_headerless(body: &Body, buf: &mut [u8]) -> usize {
4827        let mut w = CdrWriter::new(buf);
4828        body.serialize(&mut w).expect("serialize");
4829        w.position()
4830    }
4831
4832    #[test]
4833    fn headerless_payload_round_trips() {
4834        let body = Body {
4835            first: 7,
4836            rest: [1, 1],
4837        };
4838        let mut buf = [0u8; 64];
4839        let n = produce_headerless(&body, &mut buf);
4840
4841        let got = read_action_field::<Body, 64>(&LE_ENCAP, &buf[..n])
4842            .expect("consumer must decode the headerless payload");
4843        assert_eq!(got, body, "issue 0035: the reader ate a data word");
4844    }
4845
4846    /// THE hazard 0418's own doc names and did not test.
4847    ///
4848    /// `payload_has_cdr_encap` was a VALUE sniff: a leading `int32` of 256 is
4849    /// `00 01 00 00`, indistinguishable from the LE encap header. While the
4850    /// producer wrote an inner header only Cyclone took the other branch, so it
4851    /// never mattered; once 0418 made every payload headerless the sniff was
4852    /// consulted for all of them, and this body had its first word eaten as
4853    /// framing — `first` came back as `rest[0]`. Issue #35 reached through a
4854    /// payload VALUE rather than a framing bug.
4855    #[test]
4856    fn a_leading_word_that_looks_like_an_encap_is_data_not_framing() {
4857        let body = Body {
4858            first: 256,
4859            rest: [11, 12],
4860        };
4861        let mut buf = [0u8; 64];
4862        let n = produce_headerless(&body, &mut buf);
4863
4864        assert_eq!(
4865            &buf[..4],
4866            &LE_ENCAP,
4867            "precondition: an int32 of 256 IS the LE encap byte pattern"
4868        );
4869        assert!(
4870            payload_has_cdr_encap(&buf[..n]),
4871            "precondition: the retired sniff cannot tell this from a header"
4872        );
4873
4874        let got = read_action_field::<Body, 64>(&LE_ENCAP, &buf[..n]).expect("must decode");
4875        assert_eq!(
4876            got, body,
4877            "the leading word is DATA — reading it as framing is issue #35"
4878        );
4879    }
4880
4881    /// The version break RFC-0069 accepts, asserted rather than assumed.
4882    ///
4883    /// A pre-0418 peer sends `[inner header][fields]`. The consumer no longer
4884    /// sniffs, so it splices unconditionally and the inner header is read as
4885    /// data. Old and new images are wire-incompatible on action payloads — the
4886    /// RFC's "silent version skew" risk, made explicit here so the next reader
4887    /// finds it as a decision and not as a mystery.
4888    #[test]
4889    fn a_pre_0418_double_header_payload_does_not_decode_as_itself() {
4890        let body = Body {
4891            first: 5,
4892            rest: [6, 7],
4893        };
4894        let mut inner = [0u8; 64];
4895        let n = produce_headerless(&body, &mut inner);
4896        let mut withhdr = [0u8; 68];
4897        withhdr[..4].copy_from_slice(&LE_ENCAP);
4898        withhdr[4..4 + n].copy_from_slice(&inner[..n]);
4899
4900        let got = read_action_field::<Body, 68>(&LE_ENCAP, &withhdr[..4 + n]);
4901        assert_ne!(
4902            got,
4903            Some(body),
4904            "a pre-0418 payload must NOT silently appear to decode — the wire \
4905             format changed and the skew is expected to fail"
4906        );
4907    }
4908}
4909
4910/// Issue #505 — timer overrun policy. `timer_try_process` takes the
4911/// elapsed delta directly, so a stall is expressible as a single large
4912/// delta and every case here is a pure unit test.
4913#[cfg(test)]
4914mod timer_overrun_tests {
4915    use super::*;
4916
4917    /// Drive `entry` through one `try_process` pass, crediting `delta_ms`
4918    /// worth of elapsed time (the dispatcher's unit is microseconds).
4919    fn step<F: FnMut(&TimerCallInfo)>(entry: &mut TimerEntry<F>, delta_ms: u64) -> bool {
4920        // SAFETY: `entry` is a live, aligned `TimerEntry<F>`.
4921        unsafe {
4922            timer_try_process::<F>(
4923                (entry as *mut TimerEntry<F>).cast::<u8>(),
4924                delta_ms * 1000,
4925                0,
4926            )
4927            .unwrap()
4928        }
4929    }
4930
4931    /// Same, in microseconds — the dispatcher's native unit.
4932    fn step_us<F: FnMut(&TimerCallInfo)>(entry: &mut TimerEntry<F>, delta_us: u64) -> bool {
4933        // SAFETY: `entry` is a live, aligned `TimerEntry<F>`.
4934        unsafe {
4935            timer_try_process::<F>((entry as *mut TimerEntry<F>).cast::<u8>(), delta_us, 0).unwrap()
4936        }
4937    }
4938
4939    fn periodic(
4940        period_us: u64,
4941        policy: TimerOverrunPolicy,
4942    ) -> TimerEntry<impl FnMut(&TimerCallInfo)> {
4943        TimerEntry {
4944            period_us,
4945            elapsed_us: 0,
4946            overruns: 0,
4947            overruns_reported: 0,
4948            oneshot: false,
4949            fired: false,
4950            cancelled: false,
4951            overrun_policy: policy,
4952            clock_source: TimerClockSource::Steady,
4953            last_clock_ns: 0,
4954            callback: |_: &TimerCallInfo| {},
4955        }
4956    }
4957
4958    #[test]
4959    fn skip_is_the_default_policy() {
4960        assert_eq!(TimerOverrunPolicy::default(), TimerOverrunPolicy::Skip);
4961    }
4962
4963    #[test]
4964    fn skip_coalesces_a_stall_into_one_activation() {
4965        // The observed failure: a ~200 ms preemption of a 10 ms timer
4966        // replayed as a burst of activations. Under Skip the backlog
4967        // costs exactly one activation plus a counter bump.
4968        let mut t = periodic(10_000, TimerOverrunPolicy::Skip);
4969        assert!(step(&mut t, 205));
4970        assert_eq!(t.overruns, 19, "205 ms of a 10 ms period = 20 due, 1 fired");
4971        // Nothing is owed: the next pass waits out the remaining period.
4972        assert!(!step(&mut t, 4));
4973        assert!(step(&mut t, 1));
4974    }
4975
4976    #[test]
4977    fn skip_preserves_the_phase_grid() {
4978        // 205 ms leaves a 5 ms remainder; keeping it means the next fire
4979        // lands 5 ms later, back on the original 10 ms grid, instead of
4980        // re-anchoring to the moment the stall ended.
4981        let mut t = periodic(10_000, TimerOverrunPolicy::Skip);
4982        assert!(step(&mut t, 205));
4983        assert_eq!(t.elapsed_us, 5_000);
4984    }
4985
4986    #[test]
4987    fn catchup_replays_every_missed_period() {
4988        let mut t = periodic(10_000, TimerOverrunPolicy::CatchUp);
4989        assert!(step(&mut t, 205));
4990        // One activation per pass until the backlog drains, with no
4991        // further time credited.
4992        let mut replays = 0;
4993        while step(&mut t, 0) {
4994            replays += 1;
4995            assert!(replays < 64, "backlog must drain");
4996        }
4997        assert_eq!(replays, 19);
4998        assert_eq!(t.overruns, 0, "CatchUp loses nothing, so counts nothing");
4999    }
5000
5001    #[test]
5002    fn on_time_ticks_never_count_as_overruns() {
5003        let mut t = periodic(10_000, TimerOverrunPolicy::Skip);
5004        for _ in 0..100 {
5005            assert!(step(&mut t, 10));
5006        }
5007        assert_eq!(t.overruns, 0);
5008        assert_eq!(t.elapsed_us, 0);
5009    }
5010
5011    #[test]
5012    fn a_single_late_period_is_one_overrun() {
5013        // Exactly two periods due = one fired, one dropped.
5014        let mut t = periodic(10_000, TimerOverrunPolicy::Skip);
5015        assert!(step(&mut t, 20));
5016        assert_eq!(t.overruns, 1);
5017    }
5018
5019    #[test]
5020    fn oneshot_ignores_the_policy() {
5021        let mut t = TimerEntry {
5022            period_us: 10_000,
5023            elapsed_us: 0,
5024            overruns: 0,
5025            overruns_reported: 0,
5026            oneshot: true,
5027            fired: false,
5028            cancelled: false,
5029            overrun_policy: TimerOverrunPolicy::Skip,
5030            clock_source: TimerClockSource::Steady,
5031            last_clock_ns: 0,
5032            callback: |_: &TimerCallInfo| {},
5033        };
5034        assert!(step(&mut t, 205));
5035        assert_eq!(t.overruns, 0);
5036        assert!(!step(&mut t, 205), "a fired one-shot stays fired");
5037    }
5038
5039    #[test]
5040    fn sub_millisecond_periods_are_expressible() {
5041        // Issue #505 — the dispatcher's unit is microseconds, so a
5042        // 500 us period is a real period rather than the "fires every
5043        // spin" degenerate case a millisecond field forced it into.
5044        let mut t = periodic(500, TimerOverrunPolicy::Skip);
5045        // 200 us of credit is not enough...
5046        assert!(!step_us(&mut t, 200));
5047        // ...600 us total is.
5048        assert!(step_us(&mut t, 400));
5049        assert_eq!(t.overruns, 0);
5050        assert_eq!(t.elapsed_us, 100, "phase remainder survives");
5051    }
5052
5053    #[test]
5054    fn a_stalled_sub_millisecond_timer_counts_whole_periods() {
5055        let mut t = periodic(500, TimerOverrunPolicy::Skip);
5056        assert!(step_us(&mut t, 5_000)); // 10 periods due
5057        assert_eq!(t.overruns, 9);
5058    }
5059
5060    #[test]
5061    fn zero_period_does_not_divide_by_zero() {
5062        // Degenerate but reachable: `TimerDuration::from_millis(0)` or a
5063        // sub-millisecond period truncated to 0 by `as_millis`.
5064        let mut t = periodic(0, TimerOverrunPolicy::Skip);
5065        assert!(step(&mut t, 5));
5066        assert_eq!(t.overruns, 0);
5067        assert_eq!(t.elapsed_us, 0);
5068    }
5069
5070    #[test]
5071    fn overrun_count_saturates_instead_of_wrapping() {
5072        let mut t = periodic(1_000, TimerOverrunPolicy::Skip);
5073        t.overruns = u32::MAX - 1;
5074        assert!(step(&mut t, 1_000));
5075        assert_eq!(t.overruns, u32::MAX);
5076    }
5077}
5078
5079/// issue 1437 / phase-444 — the layout invariant the three
5080/// `Executor::*_handle` accessors read the arena through.
5081///
5082/// Those accessors resolve an arena entry to its transport handle from
5083/// `(EntryKind, offset)` ALONE, with no knowledge of the shape the entry was
5084/// monomorphised into — 12 subscription shapes, 2 service-server, 2
5085/// service-client, differing in buffer sizes, message types and callback
5086/// types. That works because every one of them is `#[repr(C)]` with its
5087/// handle as the FIRST field, so `arena_base + offset` is the handle pointer
5088/// for all of them.
5089///
5090/// It is an invariant nothing else states and a compiler would not catch:
5091/// prepending a field to any entry below leaves every caller compiling and
5092/// makes the accessors read the new field AS a handle. So it is measured
5093/// here, per shape, rather than asserted in a comment beside the cast.
5094#[cfg(test)]
5095mod handle_offset_tests {
5096    use super::*;
5097
5098    /// One instantiation per SHAPE. The const-generic buffer sizes are
5099    /// deliberately not the defaults — a shape whose handle offset depended
5100    /// on them would be exactly the bug this exists to catch, and equal
5101    /// numbers everywhere would hide it.
5102    macro_rules! handle_at_zero {
5103        ($($name:literal => $ty:ty),* $(,)?) => {
5104            $(assert_eq!(
5105                core::mem::offset_of!($ty, handle),
5106                0,
5107                concat!($name, " must begin with its handle — \
5108                         Executor::*_handle resolves an arena entry by \
5109                         (kind, offset) and casts arena_base + offset \
5110                         straight to the handle type"),
5111            );)*
5112        };
5113    }
5114
5115    #[test]
5116    fn every_arena_entry_begins_with_its_handle() {
5117        type Cb = fn();
5118        handle_at_zero! {
5119            "SubInfoEntry"            => SubInfoEntry<u8, Cb>,
5120            "SubBufferedEntry"        => SubBufferedEntry<u8, Cb>,
5121            "SubInplaceEntry"         => SubInplaceEntry<u8, Cb>,
5122            "SubBufferedRawEntry"     => SubBufferedRawEntry<Cb>,
5123            "SubBufferedViewEntry"    => SubBufferedViewEntry<u8, Cb>,
5124            "SubBufferedRawInfoEntry" => SubBufferedRawInfoEntry<Cb>,
5125            "SubBufferedRawInfoCEntry" => SubBufferedRawInfoCEntry,
5126            "SubBufferedRawCEntry"    => SubBufferedRawCEntry,
5127            "SubBufferedTypedCEntry"  => SubBufferedTypedCEntry,
5128            "SrvRawEntry"             => SrvRawEntry<43, 47>,
5129            "ServiceClientRawArenaEntry" => ServiceClientRawArenaEntry<53>,
5130            "ServiceClientSendHeader" => ServiceClientSendHeader<59>,
5131        }
5132    }
5133}
5134
5135/// Issue 1632 — the Rust arena's drop log prints the size the sample needed
5136/// beside the buffer, as the C++ one has since issue 1612.
5137///
5138/// The sink keeps what was logged, so the test reads what a human would see.
5139/// The sink is process-global, so the cells serialise; the drop counter is
5140/// never touched, since other cells advance it too (issue 2082).
5141#[cfg(test)]
5142mod dropped_take_log_tests {
5143    use super::{drop_is_reported, log_dropped_take};
5144    use nros_rmw::TransportError;
5145
5146    struct CapturingSink {
5147        lines: std::sync::Mutex<std::vec::Vec<std::string::String>>,
5148    }
5149
5150    impl nros_log::LogSink for CapturingSink {
5151        fn log(&self, record: &nros_log::Record<'_>) {
5152            if record.message.contains("subscription take DROPPED") {
5153                self.lines
5154                    .lock()
5155                    .unwrap_or_else(std::sync::PoisonError::into_inner)
5156                    .push(record.message.into());
5157            }
5158        }
5159    }
5160
5161    static CAPTURE: std::sync::OnceLock<&'static CapturingSink> = std::sync::OnceLock::new();
5162    static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());
5163
5164    /// The line this call logged. The sink is process-global, so another
5165    /// cell's drop may land beside it; `cap` picks this call's line out, and
5166    /// each call site passes a buffer size no other cell uses (issue 2082).
5167    fn logged_one(err: TransportError, cap: usize, recorded: Option<usize>) -> std::string::String {
5168        let _g = SERIAL
5169            .lock()
5170            .unwrap_or_else(std::sync::PoisonError::into_inner);
5171        let sink = CAPTURE.get_or_init(|| {
5172            let sink: &'static CapturingSink =
5173                std::boxed::Box::leak(std::boxed::Box::new(CapturingSink {
5174                    lines: std::sync::Mutex::new(std::vec::Vec::new()),
5175                }));
5176            assert!(nros_log::add_sink(sink), "no sink slot left");
5177            sink
5178        });
5179        let marker = std::format!("{cap}-byte buffer");
5180        let mine = || -> std::vec::Vec<std::string::String> {
5181            sink.lines
5182                .lock()
5183                .unwrap_or_else(std::sync::PoisonError::into_inner)
5184                .iter()
5185                .filter(|l| l.contains(&marker))
5186                .cloned()
5187                .collect()
5188        };
5189        sink.lines
5190            .lock()
5191            .unwrap_or_else(std::sync::PoisonError::into_inner)
5192            .clear();
5193        // A record nros_log lost to its hold queue (issue 2000) is raised
5194        // again. Always as drop number one, never through DROPPED_TAKES.
5195        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
5196        let seen = nros_log::early::emit_until_delivered(
5197            || log_dropped_take(&err, cap, recorded, 0),
5198            || !mine().is_empty(),
5199            || {
5200                std::thread::yield_now();
5201                std::time::Instant::now() < deadline
5202            },
5203        );
5204        let lines = mine();
5205        assert!(seen, "no line for a {cap}-byte buffer: {lines:?}");
5206        // A re-raise can deliver the line twice; every copy is the same drop.
5207        assert!(
5208            lines.iter().all(|l| *l == lines[0]),
5209            "the copies disagree: {lines:?}"
5210        );
5211        lines[0].clone()
5212    }
5213
5214    #[test]
5215    fn the_drop_log_names_the_sample_size_beside_the_buffer() {
5216        let line = logged_one(TransportError::BufferTooSmall, 4093, Some(1000));
5217        assert!(line.contains("1000-byte sample"), "no sample size: {line}");
5218        assert!(line.contains("4093-byte buffer"), "no buffer size: {line}");
5219        // nros_log's buffer is all-or-nothing; the drop count is the tail.
5220        assert!(line.contains("Dropped 1 so far"), "truncated: {line}");
5221    }
5222
5223    #[test]
5224    fn an_unknown_size_and_a_staging_refusal_print_as_unknown() {
5225        let unknown = logged_one(TransportError::BufferTooSmall, 4091, None);
5226        assert!(unknown.contains("?-byte sample"), "{unknown}");
5227        // `MessageTooLarge` is the backend's staging buffer, refused before a
5228        // take measured anything: an earlier take's size must not be printed.
5229        let staging = logged_one(TransportError::MessageTooLarge, 4087, Some(1000));
5230        assert!(staging.contains("?-byte sample"), "{staging}");
5231        assert!(!staging.contains("1000"), "{staging}");
5232    }
5233
5234    #[test]
5235    fn the_first_drop_and_every_64th_are_reported() {
5236        assert!(drop_is_reported(0));
5237        assert!(!drop_is_reported(1));
5238        assert!(!drop_is_reported(63));
5239        assert!(drop_is_reported(64));
5240        assert!(!drop_is_reported(65));
5241        assert!(drop_is_reported(128));
5242    }
5243}