Skip to main content

dynamo_runtime/
nvtx.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! NVTX timeline-annotation helpers for Nsight Systems profiling.
5//!
6//! Backed by the `nvtx` crate, which vendors NVIDIA's header-only **NVTX v3** C API
7//! and compiles it in with `cc`. There is no link-time dependency on any NVTX shared
8//! library: the v3 headers compile to inert stubs that lazily `dlopen` the profiler's
9//! injection library named by `NVTX_INJECTION64_PATH` the first time an annotation
10//! fires. With no profiler attached, nothing is loaded at all.
11//!
12//! This is why v3 matters on CUDA 13: CUDA 13 removed `libnvToolsExt.so`, which the
13//! older v2 C API (and cudarc's binding to it) resolved by `dlopen` — a hard failure
14//! when the file is absent. v3 has no such library to find, so markers work on CUDA 13
15//! natively — the same mechanism TensorRT-LLM's own Python markers use, which puts both
16//! on one timeline.
17//!
18//! # Gating (two-level)
19//!
20//! | Cargo feature `nvtx` | `DYN_NVTX` env | Effect                                        |
21//! |----------------------|----------------------------|-----------------------------------------------|
22//! | off (default)        | any                        | macros compile to nothing; zero overhead      |
23//! | on                   | unset                      | inlined `Relaxed` load + branch per site      |
24//! | on                   | `1`/`true`/`on`/`yes`      | two allocations + an FFI call per annotation  |
25//!
26//! The disabled-but-compiled-in row is not free, only cheap. Each macro tests
27//! [`enabled()`] in the caller, which inlines to a relaxed load of a static `AtomicBool`
28//! and a branch that predicts perfectly; the name and its `core::fmt::Arguments` are
29//! built only on the taken side. Verified by disassembling a release build with the
30//! repo's `profiling` profile: the disabled path is a load, a `test`, and a jump to the
31//! function tail, with no call and no `Arguments` construction.
32//!
33//! The enabled path is **not** cheap: the `nvtx` crate renders the name with
34//! `to_string()` and then copies it into a `CString`, so each annotation costs two heap
35//! allocations on top of the injection-library call. Measured at 4096 concurrent
36//! streams on mock workers, a range costs about 0.1 µs with no profiler attached and
37//! about 1.3 µs under `nsys -t nvtx`. Keep the second figure in mind when reading a
38//! profile of a per-chunk path: the observer effect is real.
39//!
40//! # Caveats inherited from the `nvtx` crate
41//!
42//! - **Range ids are narrowed to `i32`.** `nvtx-sys/export.c` declares
43//!   `int ffi_range_start(...)` / `void ffi_range_end(int)`, but NVTX's `nvtxRangeId_t`
44//!   is `uint64_t`. If an injection library ever handed back an id with bits above 31
45//!   set, the id passed to `nvtxRangeEnd` would differ from the one returned and the
46//!   range would never close — an unterminated bar on the timeline.
47//!
48//!   Measured against Nsight Systems 2026.4.1: ids are allocated sequentially from 1,
49//!   so a 300,000-range capture (200k raw start/end pairs plus 100k guard-managed
50//!   ranges) saw a maximum id of 200,000, zero negative ids, and all 300,000 ranges
51//!   closed. The narrowing has ~2^31 of headroom per process at that allocation rate
52//!   and does not bite in practice. Re-check if the injection library ever changes its
53//!   id scheme; widening it means a local `cc` shim over the v3 headers, since the
54//!   narrowing is in the vendored C, not in the Rust declarations [`ffi`] corrects.
55//! - **Interior NULs in names are sanitized, not fatal.** The upstream crate builds its
56//!   `CString` with `CString::new(..).expect(..)`, so an interpolated name carrying a NUL
57//!   would panic the annotated request path. [`ffi`] below owns that conversion instead
58//!   and substitutes U+FFFD, because a profiling aid must never be able to abort the
59//!   work it is measuring.
60//! - **The upstream `ffi_range_end` binding does not match its C definition.** In `nvtx`
61//!   1.3.0, `nvtx-sys/export.c` defines `void ffi_range_end(int)` while `src/bindings.rs`
62//!   declares it `-> c_int`. Every guarded range end would cross that mismatched ABI, so
63//!   [`ffi`] declares the whole surface itself, matching `export.c` exactly.
64//!
65//! # Usage
66//!
67//! ```rust,ignore
68//! let _r = dynamo_nvtx_range!("preprocess.tokenize"); // RAII — ends at scope end
69//! let _r = dynamo_nvtx_range!("request.{}", request_id); // format args also work
70//! dynamo_nvtx_push!("codec.encode");
71//! dynamo_nvtx_pop!();
72//! dynamo_nvtx_mark!("stream.first_token");
73//! dynamo_nvtx_name_thread!("tokio-worker-0");
74//! ```
75//!
76//! # Range flavors
77//!
78//! [`dynamo_nvtx_range!`] opens an NVTX **start/end** range, which carries an explicit
79//! id and is therefore correct in async code: the guard may be created on one tokio
80//! worker thread and dropped on another after an `.await`. [`dynamo_nvtx_push!`] /
81//! [`dynamo_nvtx_pop!`] use the thread-local nested range stack and must be paired on
82//! the same thread with no `.await` in between.
83//!
84//! # Name arguments
85//!
86//! A string literal is treated as a **format string**, so a literal containing `{}` or
87//! `{name}` interpolates rather than appearing verbatim. `dynamo_nvtx_range!("map{}")`
88//! fails to compile; `dynamo_nvtx_range!("a{b}")` silently captures a local `b`. Use
89//! `dynamo_nvtx_range!("{}", "map{}")` for a literal brace.
90//!
91//! # Build
92//!
93//! ```bash
94//! cargo build --profile profiling --features dynamo-runtime/nvtx
95//! ```
96//!
97//! Prefer `dynamo-runtime/nvtx` over a bare `--features nvtx` at the workspace root:
98//! the latter also selects the `nvtx` feature of `kvbm-engine`, whose markers have no
99//! `DYN_NVTX` runtime switch and would fire unconditionally.
100
101use anyhow::Context as _;
102
103#[cfg(feature = "nvtx")]
104use std::sync::atomic::{AtomicBool, Ordering};
105
106#[cfg(feature = "nvtx")]
107static NVTX_ENABLED: AtomicBool = AtomicBool::new(false);
108
109/// Name of the runtime switch. Shared verbatim with the Python layer
110/// (`dynamo.common.utils.nvtx_utils`), which parses it with the same vocabulary.
111pub const ENV_VAR: &str = "DYN_NVTX";
112
113/// Corrected declarations for the C shim that `nvtx` 1.3.0 compiles and links.
114///
115/// The upstream `src/bindings.rs` is not usable as-is: it declares
116/// `ffi_range_end` as returning `c_int` where `nvtx-sys/export.c` defines it
117/// `void`, and it builds every name with `CString::new(..).expect(..)`, which
118/// turns an interior NUL in an interpolated marker name into a panic on the
119/// path being profiled. These declarations match `export.c` exactly and the
120/// conversion below cannot fail.
121///
122/// The symbols come from the static `libnvtx.a` that the `nvtx` crate's build
123/// script compiles with `cc`; depending on that crate is what puts them on the
124/// link line. A rename upstream surfaces as a link error, not as silent drift.
125#[cfg(feature = "nvtx")]
126mod ffi {
127    use std::ffi::{CString, c_char, c_int};
128
129    #[link(name = "nvtx")]
130    unsafe extern "C" {
131        fn ffi_range_push(message: *const c_char) -> c_int;
132        fn ffi_range_pop() -> c_int;
133        fn ffi_range_start(message: *const c_char) -> c_int;
134        fn ffi_range_end(id: c_int);
135        fn ffi_mark(message: *const c_char);
136        fn ffi_name_thread(name: *const c_char);
137    }
138
139    /// Render a marker name into a NUL-terminated C string, infallibly.
140    ///
141    /// An interior NUL is replaced with U+FFFD rather than rejected: the name
142    /// is a human-readable label on a timeline, so a mangled label is a far
143    /// better outcome than either a lost range or a panic. The allocation
144    /// count is unchanged from the upstream path (one `String`, one
145    /// `CString`); the `replace` only runs on the rare bad name.
146    fn c_name<M: std::fmt::Display>(name: M) -> CString {
147        let rendered = name.to_string();
148        let cleaned = if rendered.as_bytes().contains(&0) {
149            rendered.replace('\0', "\u{fffd}")
150        } else {
151            rendered
152        };
153        // No interior NUL remains, so this cannot fail; the fallback keeps the
154        // guarantee local instead of resting on that reasoning alone.
155        CString::new(cleaned).unwrap_or_default()
156    }
157
158    pub fn range_push<M: std::fmt::Display>(name: M) {
159        let name = c_name(name);
160        // SAFETY: signature matches `int ffi_range_push(const char *)` in
161        // nvtx-sys/export.c; the pointer is valid for the call's duration.
162        unsafe { ffi_range_push(name.as_ptr()) };
163    }
164
165    pub fn range_pop() {
166        // SAFETY: signature matches `int ffi_range_pop(void)`.
167        unsafe { ffi_range_pop() };
168    }
169
170    pub fn range_start<M: std::fmt::Display>(name: M) -> c_int {
171        let name = c_name(name);
172        // SAFETY: signature matches `int ffi_range_start(const char *)`.
173        unsafe { ffi_range_start(name.as_ptr()) }
174    }
175
176    pub fn range_end(id: c_int) {
177        // SAFETY: signature matches `void ffi_range_end(int)`. `id` is one
178        // previously returned by `range_start`.
179        unsafe { ffi_range_end(id) };
180    }
181
182    pub fn mark<M: std::fmt::Display>(name: M) {
183        let name = c_name(name);
184        // SAFETY: signature matches `void ffi_mark(const char *)`.
185        unsafe { ffi_mark(name.as_ptr()) };
186    }
187
188    pub fn name_thread<M: std::fmt::Display>(name: M) {
189        let name = c_name(name);
190        // SAFETY: signature matches `void ffi_name_thread(const char *)`.
191        unsafe { ffi_name_thread(name.as_ptr()) };
192    }
193}
194
195// ── Public API ───────────────────────────────────────────────────────────────
196
197/// Parse the switch value, rejecting anything outside the shared vocabulary.
198///
199/// Split out from [`init`] so the contract can be tested without mutating the
200/// process environment, which is unsound while other tests run in parallel.
201fn parse_switch(raw: Option<&str>) -> anyhow::Result<bool> {
202    match raw {
203        // Delegated to the canonical parser rather than hand-rolled: the
204        // accepted set (1/true/on/yes, 0/false/off/no, empty) is exactly what
205        // `nvtx_utils._parse_enabled` mirrors on the Python side.
206        Some(value) => crate::config::parse_bool(value)
207            .with_context(|| format!("{ENV_VAR} is not a recognized boolean")),
208        None => Ok(false),
209    }
210}
211
212/// Initialise the NVTX subsystem from the [`ENV_VAR`] environment variable.
213/// Must be called once at runtime startup before any annotation macros fire.
214///
215/// The value is validated even when the `nvtx` Cargo feature is off. `DYN_NVTX`
216/// is one switch shared with the Python layer, which rejects an unrecognized
217/// value outright; if this half quietly read `DYN_NVTX=maybe` as "off", the same
218/// capture would half-start and the operator would be told nothing. Rejecting it
219/// in both halves is what makes it a single switch.
220///
221/// Storing the flag and emitting markers remain no-ops without the feature.
222pub fn init() -> anyhow::Result<()> {
223    let enabled = match std::env::var(ENV_VAR) {
224        Ok(raw) => parse_switch(Some(&raw))?,
225        Err(std::env::VarError::NotPresent) => parse_switch(None)?,
226        Err(std::env::VarError::NotUnicode(raw)) => {
227            anyhow::bail!("{ENV_VAR}={raw:?} is not valid unicode")
228        }
229    };
230
231    #[cfg(feature = "nvtx")]
232    {
233        NVTX_ENABLED.store(enabled, Ordering::Relaxed);
234        if enabled {
235            tracing::info!("NVTX annotations enabled ({ENV_VAR})");
236        }
237    }
238    #[cfg(not(feature = "nvtx"))]
239    let _ = enabled;
240
241    Ok(())
242}
243
244/// Returns `true` when the `nvtx` feature is compiled in **and** `DYN_NVTX` is set.
245#[inline(always)]
246pub fn enabled() -> bool {
247    #[cfg(feature = "nvtx")]
248    {
249        return NVTX_ENABLED.load(Ordering::Relaxed);
250    }
251    #[allow(unreachable_code)]
252    false
253}
254
255/// Push an NVTX range onto the calling thread's stack.
256/// No-op (compiled out) when the `nvtx` feature is off.
257#[inline(always)]
258pub fn push_impl<M: std::fmt::Display>(name: M) {
259    #[cfg(feature = "nvtx")]
260    {
261        if NVTX_ENABLED.load(Ordering::Relaxed) {
262            ffi::range_push(name);
263        }
264    }
265    let _ = name;
266}
267
268/// Pop the innermost NVTX range from the calling thread's stack.
269/// No-op (compiled out) when the `nvtx` feature is off.
270#[inline(always)]
271pub fn pop_impl() {
272    #[cfg(feature = "nvtx")]
273    {
274        if NVTX_ENABLED.load(Ordering::Relaxed) {
275            ffi::range_pop();
276        }
277    }
278}
279
280/// Record an instantaneous NVTX marker on the calling thread's timeline.
281/// No-op (compiled out) when the `nvtx` feature is off.
282#[inline(always)]
283pub fn mark_impl<M: std::fmt::Display>(name: M) {
284    #[cfg(feature = "nvtx")]
285    {
286        if NVTX_ENABLED.load(Ordering::Relaxed) {
287            ffi::mark(name);
288        }
289    }
290    let _ = name;
291}
292
293/// Name the current OS thread in the Nsight Systems timeline.
294/// No-op (compiled out) when the `nvtx` feature is off.
295#[inline(always)]
296pub fn name_current_thread_impl<M: std::fmt::Display>(name: M) {
297    #[cfg(feature = "nvtx")]
298    {
299        if NVTX_ENABLED.load(Ordering::Relaxed) {
300            ffi::name_thread(name);
301        }
302    }
303    let _ = name;
304}
305
306// ── RAII guard ───────────────────────────────────────────────────────────────
307
308/// RAII guard that ends an NVTX start/end range when dropped.
309/// Construct with [`dynamo_nvtx_range!`].
310///
311/// Start/end ranges (rather than the thread-nested push/pop stack) are used so the
312/// guard stays correct when it is held across an `.await` and the task resumes on a
313/// different tokio worker thread.
314#[cfg(feature = "nvtx")]
315pub struct NvtxRangeGuard {
316    /// NVTX range id; `None` when annotations are disabled at runtime.
317    id: Option<i32>,
318}
319
320/// Zero-sized no-op guard used when the `nvtx` feature is off.
321#[cfg(not(feature = "nvtx"))]
322pub struct NvtxRangeGuard;
323
324impl NvtxRangeGuard {
325    #[doc(hidden)]
326    #[inline(always)]
327    pub fn new<M: std::fmt::Display>(name: M) -> Self {
328        #[cfg(feature = "nvtx")]
329        {
330            // Re-checked rather than assumed: the macros gate on `enabled()`
331            // first, but `new` is public and must not open a range behind the
332            // switch's back.
333            let id = NVTX_ENABLED
334                .load(Ordering::Relaxed)
335                .then(|| ffi::range_start(name));
336            NvtxRangeGuard { id }
337        }
338        #[cfg(not(feature = "nvtx"))]
339        {
340            let _ = name;
341            NvtxRangeGuard
342        }
343    }
344
345    /// A guard that ends nothing — the cold half of the macros' `enabled()` branch.
346    #[doc(hidden)]
347    #[inline(always)]
348    pub fn inactive() -> Self {
349        #[cfg(feature = "nvtx")]
350        {
351            NvtxRangeGuard { id: None }
352        }
353        #[cfg(not(feature = "nvtx"))]
354        {
355            NvtxRangeGuard
356        }
357    }
358}
359
360#[cfg(feature = "nvtx")]
361impl Drop for NvtxRangeGuard {
362    fn drop(&mut self) {
363        if let Some(id) = self.id {
364            ffi::range_end(id);
365        }
366    }
367}
368
369#[cfg(not(feature = "nvtx"))]
370impl Drop for NvtxRangeGuard {
371    fn drop(&mut self) {}
372}
373
374// ── Macros ───────────────────────────────────────────────────────────────────
375//
376// Every macro tests `enabled()` *first*, in the caller. That inlines to a
377// `Relaxed` load plus a predictable branch, and — critically — keeps the
378// `core::fmt::Arguments` construction and the call into this module on the cold
379// side of it. Passing `format_args!` straight into a helper instead would build
380// the 32-byte `Arguments` on the caller's stack unconditionally and defeat
381// inlining, costing ~5-15ns per site even with annotations switched off. That
382// matters: `worker.egress.*` fires once per streamed chunk.
383//
384// Consequence to know about: in the `$name:expr` arm the name expression is
385// only evaluated when annotations are enabled. Do not pass an expression whose
386// side effects you depend on.
387
388/// Push a named NVTX range onto the calling thread's nested range stack.
389///
390/// Accepts either a `Display` expression or `format!`-style arguments.
391/// Must be paired with [`dynamo_nvtx_pop!`] on the same thread, with no `.await`
392/// in between — use [`dynamo_nvtx_range!`] in async code.
393/// Zero-cost when the `nvtx` Cargo feature is off.
394#[macro_export]
395macro_rules! dynamo_nvtx_push {
396    ($fmt:literal $(, $arg:expr)* $(,)?) => {
397        if $crate::nvtx::enabled() {
398            $crate::nvtx::push_impl(::core::format_args!($fmt $(, $arg)*));
399        }
400    };
401    ($name:expr) => {
402        if $crate::nvtx::enabled() {
403            $crate::nvtx::push_impl($name);
404        }
405    };
406}
407
408/// Pop the innermost NVTX range from the calling thread's nested range stack.
409/// Zero-cost when the `nvtx` Cargo feature is off.
410#[macro_export]
411macro_rules! dynamo_nvtx_pop {
412    () => {
413        $crate::nvtx::pop_impl()
414    };
415}
416
417/// Record an instantaneous NVTX marker on the calling thread's timeline.
418/// Accepts either a `Display` expression or `format!`-style arguments.
419/// Zero-cost when the `nvtx` Cargo feature is off.
420#[macro_export]
421macro_rules! dynamo_nvtx_mark {
422    ($fmt:literal $(, $arg:expr)* $(,)?) => {
423        if $crate::nvtx::enabled() {
424            $crate::nvtx::mark_impl(::core::format_args!($fmt $(, $arg)*));
425        }
426    };
427    ($name:expr) => {
428        if $crate::nvtx::enabled() {
429            $crate::nvtx::mark_impl($name);
430        }
431    };
432}
433
434/// Open a named NVTX range that closes automatically at end of scope.
435///
436/// ```rust,ignore
437/// let _r = dynamo_nvtx_range!("preprocess.tokenize");
438/// let _r = dynamo_nvtx_range!("backend.decode.{}", request_id);
439/// // range closes here
440/// ```
441///
442/// Safe to hold across `.await`: the range is an NVTX start/end pair, not a
443/// thread-local push/pop.
444/// Zero-cost when the `nvtx` Cargo feature is off.
445#[macro_export]
446macro_rules! dynamo_nvtx_range {
447    ($fmt:literal $(, $arg:expr)* $(,)?) => {
448        if $crate::nvtx::enabled() {
449            $crate::nvtx::NvtxRangeGuard::new(::core::format_args!($fmt $(, $arg)*))
450        } else {
451            $crate::nvtx::NvtxRangeGuard::inactive()
452        }
453    };
454    ($name:expr) => {
455        if $crate::nvtx::enabled() {
456            $crate::nvtx::NvtxRangeGuard::new($name)
457        } else {
458            $crate::nvtx::NvtxRangeGuard::inactive()
459        }
460    };
461}
462
463/// Annotate the current OS thread in the Nsight Systems timeline.
464/// Zero-cost when the `nvtx` Cargo feature is off.
465#[macro_export]
466macro_rules! dynamo_nvtx_name_thread {
467    ($fmt:literal $(, $arg:expr)* $(,)?) => {
468        if $crate::nvtx::enabled() {
469            $crate::nvtx::name_current_thread_impl(::core::format_args!($fmt $(, $arg)*));
470        }
471    };
472    ($name:expr) => {
473        if $crate::nvtx::enabled() {
474            $crate::nvtx::name_current_thread_impl($name);
475        }
476    };
477}
478
479#[cfg(test)]
480mod tests {
481    /// Serialises the tests that toggle [`super::NVTX_ENABLED`]. The flag is
482    /// process-global and this binary runs its tests on parallel threads, so
483    /// without this a test asserting "disabled" can observe another test's
484    /// "enabled" window.
485    #[cfg(feature = "nvtx")]
486    static NVTX_ENABLED_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
487
488    /// Exclusive access to [`NVTX_ENABLED`] for the lifetime of the guard, with the
489    /// previous value restored on drop.
490    ///
491    /// Restoring in `Drop` rather than at the end of the test body is what makes a
492    /// failing assertion safe: an `assert!` or `.expect()` that panics mid-test
493    /// would otherwise leave the flag `true`, and — because the lock deliberately
494    /// ignores poisoning — the next test to assert "disabled" would observe that
495    /// leaked value and fail for an unrelated reason.
496    #[cfg(feature = "nvtx")]
497    struct EnabledFlag {
498        _lock: std::sync::MutexGuard<'static, ()>,
499        restore: bool,
500    }
501
502    #[cfg(feature = "nvtx")]
503    impl EnabledFlag {
504        /// Take the lock and set the flag, remembering the value to restore.
505        fn set(value: bool) -> Self {
506            use std::sync::atomic::Ordering;
507            // Ignore poisoning: a panic in another test must not cascade into
508            // unrelated failures here.
509            let _lock = NVTX_ENABLED_LOCK
510                .lock()
511                .unwrap_or_else(|poisoned| poisoned.into_inner());
512            let restore = super::NVTX_ENABLED.swap(value, Ordering::Relaxed);
513            Self { _lock, restore }
514        }
515
516        /// Flip the flag mid-test. Still restored to the original value on drop.
517        fn store(&self, value: bool) {
518            super::NVTX_ENABLED.store(value, std::sync::atomic::Ordering::Relaxed);
519        }
520    }
521
522    #[cfg(feature = "nvtx")]
523    impl Drop for EnabledFlag {
524        fn drop(&mut self) {
525            super::NVTX_ENABLED.store(self.restore, std::sync::atomic::Ordering::Relaxed);
526        }
527    }
528
529    /// Fire every annotation entry point, in both macro arms.
530    fn exercise_all_sites() {
531        dynamo_nvtx_name_thread!("nvtx-unit-test");
532        dynamo_nvtx_mark!("test.mark");
533        dynamo_nvtx_mark!("test.mark.{}", 1);
534
535        dynamo_nvtx_push!("test.push");
536        dynamo_nvtx_push!("test.push.{}", 2);
537        dynamo_nvtx_pop!();
538        dynamo_nvtx_pop!();
539
540        // Non-literal arm: a `Display` expression rather than a format string.
541        let name = String::from("test.range.dynamic");
542        let _dynamic = dynamo_nvtx_range!(&name);
543        let _outer = dynamo_nvtx_range!("test.range");
544        let _inner = dynamo_nvtx_range!("test.range.{}", 3);
545    }
546
547    /// Exercises the NVTX v3 entry points end to end. With no profiler attached the
548    /// header-only stubs are inert, so this asserts the calls resolve and return
549    /// rather than that anything is recorded — the regression it guards is the v2
550    /// failure mode, where a missing `libnvToolsExt.so` aborted the process.
551    ///
552    /// `NVTX_ENABLED` is set directly rather than through `DYN_NVTX` +
553    /// [`super::init`]: this binary runs its tests in parallel threads, where mutating
554    /// the process environment is unsound.
555    #[test]
556    fn annotations_are_safe_with_no_profiler_attached() {
557        #[cfg(feature = "nvtx")]
558        {
559            let _flag = EnabledFlag::set(true);
560            assert!(super::enabled());
561            exercise_all_sites();
562        }
563
564        // Every site must also be callable with annotations off.
565        #[cfg(not(feature = "nvtx"))]
566        assert!(!super::enabled());
567        exercise_all_sites();
568    }
569
570    /// The switch must accept exactly what `nvtx_utils._parse_enabled` accepts on
571    /// the Python side, and reject everything else rather than reading it as "off".
572    /// A value that disables one half and raises in the other is not one switch.
573    #[test]
574    fn switch_parsing_matches_the_python_half() {
575        assert!(!super::parse_switch(None).expect("unset is a valid off"));
576
577        for on in ["1", "true", "TRUE", " on ", "yes"] {
578            assert!(super::parse_switch(Some(on)).expect("recognized"), "{on:?}");
579        }
580        for off in ["0", "false", "off", "no", ""] {
581            assert!(
582                !super::parse_switch(Some(off)).expect("recognized"),
583                "{off:?}"
584            );
585        }
586        for junk in ["maybe", "2", "enabled", "-1"] {
587            let err = super::parse_switch(Some(junk))
588                .expect_err("an unrecognized value must not read as off");
589            assert!(
590                err.to_string().contains(super::ENV_VAR),
591                "the error must name the variable the operator set: {err}"
592            );
593        }
594    }
595
596    /// A marker name is a label on a timeline; it must never be able to abort the
597    /// work being profiled. The upstream crate's `CString::new(..).expect(..)`
598    /// would panic here, which is why the conversion is owned locally.
599    #[test]
600    fn an_interior_nul_in_a_name_does_not_panic() {
601        #[cfg(feature = "nvtx")]
602        let _flag = EnabledFlag::set(true);
603
604        let hostile = "test.range.\u{0}injected";
605        let _range = dynamo_nvtx_range!("{}", hostile);
606        dynamo_nvtx_mark!("{}", hostile);
607        dynamo_nvtx_push!("{}", hostile);
608        dynamo_nvtx_pop!();
609        dynamo_nvtx_name_thread!("{}", hostile);
610    }
611
612    // ── Send-ness ────────────────────────────────────────────────────────────
613
614    fn assert_send<T: Send>() {}
615
616    /// The whole reason [`super::NvtxRangeGuard`] holds a start/end range id rather
617    /// than relying on the thread-nested push/pop stack is that it must be able to
618    /// live inside a future — which requires `Send` for `tokio::spawn`. This is a
619    /// compile-time assertion; it must hold in both feature configurations.
620    #[test]
621    fn range_guard_is_send() {
622        assert_send::<super::NvtxRangeGuard>();
623    }
624
625    // ── Macro arm coverage ───────────────────────────────────────────────────
626
627    /// One representative shape per macro arm: a bare literal, a literal with
628    /// format args, and a non-literal `Display` expression.
629    fn exercise_every_macro_arm() {
630        let owned = String::from("test.arg.string");
631        let number: u32 = 7;
632
633        dynamo_nvtx_mark!("test.mark.literal");
634        dynamo_nvtx_mark!("test.mark.{}", number);
635        dynamo_nvtx_mark!(&owned);
636
637        dynamo_nvtx_push!("test.push.literal");
638        dynamo_nvtx_push!("test.push.{}", number);
639        dynamo_nvtx_push!(&owned);
640        for _ in 0..3 {
641            dynamo_nvtx_pop!();
642        }
643
644        dynamo_nvtx_name_thread!("test.thread.literal");
645        dynamo_nvtx_name_thread!("test.thread.{}", number);
646        dynamo_nvtx_name_thread!(&owned);
647
648        let _r1 = dynamo_nvtx_range!("test.range.literal");
649        let _r2 = dynamo_nvtx_range!("test.range.{}", number);
650        let _r3 = dynamo_nvtx_range!(&owned);
651    }
652
653    #[test]
654    fn every_macro_arm_compiles_and_runs() {
655        #[cfg(feature = "nvtx")]
656        {
657            let flag = EnabledFlag::set(false);
658            exercise_every_macro_arm();
659
660            flag.store(true);
661            exercise_every_macro_arm();
662        }
663
664        #[cfg(not(feature = "nvtx"))]
665        exercise_every_macro_arm();
666    }
667
668    // ── Enabled/disabled transitions ─────────────────────────────────────────
669
670    #[cfg(not(feature = "nvtx"))]
671    #[test]
672    fn enabled_is_always_false_without_the_feature() {
673        assert!(!super::enabled());
674        // `init` still validates the switch without the feature, so it returns a
675        // `Result`. The outcome depends on whatever `DYN_NVTX` the developer's
676        // shell happens to carry and is asserted by
677        // `switch_parsing_matches_the_python_half`; what matters here is that no
678        // value of it can turn annotations on in this build.
679        let _ = super::init();
680        assert!(!super::enabled());
681    }
682
683    #[cfg(feature = "nvtx")]
684    #[test]
685    fn enabled_tracks_the_atomic_in_both_directions() {
686        let flag = EnabledFlag::set(false);
687        assert!(!super::enabled());
688        flag.store(true);
689        assert!(super::enabled());
690        flag.store(false);
691        assert!(!super::enabled());
692    }
693
694    /// A guard samples the runtime switch once, at construction: a range opened
695    /// while disabled must stay a no-op even if annotations are switched on before
696    /// it drops (otherwise the drop would end a range that was never started).
697    #[cfg(feature = "nvtx")]
698    #[test]
699    fn guard_samples_the_switch_at_construction() {
700        let flag = EnabledFlag::set(false);
701        let disabled = dynamo_nvtx_range!("test.switch.disabled");
702        assert!(
703            disabled.id.is_none(),
704            "a range opened while disabled must not allocate an NVTX id"
705        );
706
707        flag.store(true);
708        let enabled = dynamo_nvtx_range!("test.switch.enabled");
709        assert!(
710            enabled.id.is_some(),
711            "a range opened while enabled must allocate an NVTX id"
712        );
713
714        drop(disabled);
715        drop(enabled);
716    }
717}