Skip to main content

dynamo_runtime/
runtime.rs

1// SPDX-FileCopyrightText: Copyright (c) 2024-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The [Runtime] module is the interface for [crate::component::Component]
5//! to access shared resources. These include thread pool, memory allocators and other shared resources.
6//!
7//! The [Runtime] holds the primary [`CancellationToken`] which can be used to terminate all attached
8//! [`crate::component::Component`].
9//!
10//! We expect in the future to offer topologically aware thread and memory resources, but for now the
11//! set of resources is limited to the thread pool and cancellation token.
12//!
13//! Notes: We will need to do an evaluation on what is fully public, what is pub(crate) and what is
14//! private; however, for now we are exposing most objects as fully public while the API is maturing.
15
16use super::utils::GracefulShutdownTracker;
17use crate::{
18    compute,
19    config::{self, RuntimeConfig},
20};
21
22use futures::Future;
23use once_cell::sync::OnceCell;
24use std::{
25    mem::ManuallyDrop,
26    sync::{Arc, atomic::Ordering},
27    time::Duration,
28};
29use tokio::{signal, sync::Mutex, task::JoinHandle};
30
31pub use tokio_util::sync::CancellationToken;
32
33const DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_SECS: u64 = 15 * 60;
34
35pub(crate) fn graceful_shutdown_timeout() -> Duration {
36    let timeout_secs = std::env::var(
37        config::environment_names::runtime::DYN_RUNTIME_GRACEFUL_SHUTDOWN_TIMEOUT_SECS,
38    )
39    .ok()
40    .and_then(|s| s.parse::<u64>().ok())
41    .unwrap_or(DEFAULT_GRACEFUL_SHUTDOWN_TIMEOUT_SECS);
42
43    Duration::from_secs(timeout_secs)
44}
45
46/// How long the Velo response service stays open after the main token is
47/// cancelled: the HTTP service's drain, `DYN_HTTP_GRACEFUL_SHUTDOWN_TIMEOUT_SECS`
48/// (default 5, read by dynamo-llm). Requests it admits may still be queued or
49/// tokenizing, and register their responses later.
50fn velo_response_drain_window() -> Duration {
51    let timeout_secs =
52        std::env::var(config::environment_names::llm::DYN_HTTP_GRACEFUL_SHUTDOWN_TIMEOUT_SECS)
53            .ok()
54            .and_then(|s| s.parse::<u64>().ok())
55            .unwrap_or(5);
56
57    Duration::from_secs(timeout_secs)
58}
59
60/// How long Velo responses still open after that window get to finish.
61const VELO_RESPONSE_DRAIN_HEADROOM: Duration = Duration::from_secs(10);
62
63/// Types of Tokio runtimes that can be used to construct a Dynamo [Runtime].
64#[derive(Clone, Debug)]
65pub(crate) enum RuntimeType {
66    Shared(Arc<ManuallyDrop<tokio::runtime::Runtime>>),
67    External(tokio::runtime::Handle),
68}
69
70/// Local [Runtime] which provides access to shared resources local to the physical node/machine.
71#[derive(Debug, Clone)]
72pub struct Runtime {
73    id: Arc<String>,
74    primary: RuntimeType,
75    secondary: RuntimeType,
76    cancellation_token: CancellationToken,
77    endpoint_shutdown_token: CancellationToken,
78    shutdown_started: CancellationToken,
79    graceful_shutdown_tracker: Arc<GracefulShutdownTracker>,
80    velo_response_service: Arc<crate::pipeline::network::velo_response::RuntimeService>,
81    compute_pool: Option<Arc<compute::ComputePool>>,
82    block_in_place_permits: Option<Arc<tokio::sync::Semaphore>>,
83}
84
85impl Runtime {
86    fn new(runtime: RuntimeType, secondary: Option<RuntimeType>) -> anyhow::Result<Runtime> {
87        // Initialise NVTX toggle once from environment (no-op when feature is off).
88        // A malformed DYN_NVTX fails startup rather than silently profiling nothing.
89        crate::nvtx::init()?;
90
91        // worker id
92        let id = Arc::new(uuid::Uuid::new_v4().to_string());
93
94        // create a cancellation token
95        let cancellation_token = CancellationToken::new();
96
97        // create endpoint shutdown token as a child of the main token
98        let endpoint_shutdown_token = cancellation_token.child_token();
99        let shutdown_started = endpoint_shutdown_token.child_token();
100
101        // secondary runtime for background ectd/nats tasks
102        let secondary = match secondary {
103            Some(secondary) => secondary,
104            None => {
105                tracing::debug!("Created secondary runtime with single thread");
106                RuntimeType::Shared(Arc::new(ManuallyDrop::new(
107                    RuntimeConfig::single_threaded().create_runtime()?,
108                )))
109            }
110        };
111
112        // Initialize compute pool with default config
113        // This will be properly configured when created from RuntimeConfig
114        let compute_pool = None;
115        let block_in_place_permits = None;
116
117        let velo_response_service =
118            Arc::new(crate::pipeline::network::velo_response::RuntimeService::new(runtime.clone()));
119        Ok(Runtime {
120            id,
121            primary: runtime,
122            secondary,
123            cancellation_token,
124            endpoint_shutdown_token,
125            shutdown_started,
126            graceful_shutdown_tracker: Arc::new(GracefulShutdownTracker::new()),
127            velo_response_service,
128            compute_pool,
129            block_in_place_permits,
130        })
131    }
132
133    fn new_with_config(
134        runtime: RuntimeType,
135        secondary: Option<RuntimeType>,
136        config: &RuntimeConfig,
137    ) -> anyhow::Result<Runtime> {
138        let mut rt = Self::new(runtime, secondary)?;
139
140        // Create compute pool from configuration
141        let compute_config = crate::compute::ComputeConfig {
142            num_threads: config.compute_threads,
143            stack_size: config.compute_stack_size,
144            thread_prefix: config.compute_thread_prefix.clone(),
145            pin_threads: false,
146        };
147
148        // Check if compute pool is explicitly disabled
149        if config.compute_threads == Some(0) {
150            tracing::info!("Compute pool disabled (compute_threads = 0)");
151        } else {
152            match crate::compute::ComputePool::new(compute_config) {
153                Ok(pool) => {
154                    rt.compute_pool = Some(Arc::new(pool));
155                    tracing::debug!(
156                        "Initialized compute pool with {} threads",
157                        rt.compute_pool.as_ref().unwrap().num_threads()
158                    );
159                }
160                Err(e) => {
161                    tracing::warn!(
162                        "Failed to create compute pool: {}. CPU-intensive operations will use spawn_blocking",
163                        e
164                    );
165                }
166            }
167        }
168
169        // Initialize block_in_place semaphore based on actual worker threads
170        let num_workers = config
171            .num_worker_threads
172            .unwrap_or_else(|| std::thread::available_parallelism().unwrap().get());
173        // Reserve at least one thread for async work
174        let permits = num_workers.saturating_sub(1).max(1);
175        rt.block_in_place_permits = Some(Arc::new(tokio::sync::Semaphore::new(permits)));
176        tracing::debug!(
177            "Initialized block_in_place permits: {} (from {} worker threads)",
178            permits,
179            num_workers
180        );
181
182        Ok(rt)
183    }
184
185    /// Initialize thread-local compute context on the current thread
186    /// This should be called on each Tokio worker thread
187    pub fn initialize_thread_local(&self) {
188        if let (Some(pool), Some(permits)) = (&self.compute_pool, &self.block_in_place_permits) {
189            crate::compute::thread_local::initialize_context(Arc::clone(pool), Arc::clone(permits));
190        }
191        // Name this worker thread in the Nsight Systems timeline (no-op when nvtx feature is off)
192        let thread_name = std::thread::current()
193            .name()
194            .map(|n| n.to_string())
195            .unwrap_or_else(|| format!("tokio-worker-{:?}", std::thread::current().id()));
196        crate::nvtx::name_current_thread_impl(&thread_name);
197    }
198
199    /// Initialize thread-local compute context on all worker threads using a barrier
200    /// This ensures every worker thread has its thread-local context initialized
201    pub async fn initialize_all_thread_locals(&self) -> anyhow::Result<()> {
202        if let (Some(pool), Some(permits)) = (&self.compute_pool, &self.block_in_place_permits) {
203            // First, detect how many worker threads we actually have
204            let num_workers = self.detect_worker_thread_count().await;
205
206            if num_workers == 0 {
207                return Err(anyhow::anyhow!("No worker threads detected"));
208            }
209
210            // Create a barrier that all threads must reach
211            let barrier = Arc::new(std::sync::Barrier::new(num_workers));
212            let init_pool = Arc::clone(pool);
213            let init_permits = Arc::clone(permits);
214
215            // Spawn exactly one blocking task per worker thread
216            let mut handles = Vec::new();
217            for i in 0..num_workers {
218                let barrier_clone = Arc::clone(&barrier);
219                let pool_clone = Arc::clone(&init_pool);
220                let permits_clone = Arc::clone(&init_permits);
221
222                let handle = tokio::task::spawn_blocking(move || {
223                    // Wait at barrier - ensures all threads are participating
224                    barrier_clone.wait();
225
226                    // Now initialize thread-local storage
227                    crate::compute::thread_local::initialize_context(pool_clone, permits_clone);
228
229                    // Get thread ID for logging
230                    let thread_id = std::thread::current().id();
231                    tracing::trace!(
232                        "Initialized thread-local compute context on thread {:?} (worker {})",
233                        thread_id,
234                        i
235                    );
236                });
237                handles.push(handle);
238            }
239
240            // Wait for all tasks to complete
241            for handle in handles {
242                handle.await?;
243            }
244
245            tracing::info!(
246                "Successfully initialized thread-local compute context on {} worker threads",
247                num_workers
248            );
249        } else {
250            tracing::debug!("No compute pool configured, skipping thread-local initialization");
251        }
252        Ok(())
253    }
254
255    /// Detect the number of worker threads in the runtime
256    async fn detect_worker_thread_count(&self) -> usize {
257        use parking_lot::Mutex;
258        use std::collections::HashSet;
259
260        let thread_ids = Arc::new(Mutex::new(HashSet::new()));
261        let mut handles = Vec::new();
262
263        // Spawn many blocking tasks to ensure we hit all threads
264        // We use spawn_blocking because it runs on worker threads
265        let num_probes = 100;
266        for _ in 0..num_probes {
267            let ids = Arc::clone(&thread_ids);
268            let handle = tokio::task::spawn_blocking(move || {
269                let thread_id = std::thread::current().id();
270                ids.lock().insert(thread_id);
271            });
272            handles.push(handle);
273        }
274
275        // Wait for all probes to complete
276        for handle in handles {
277            let _ = handle.await;
278        }
279
280        let count = thread_ids.lock().len();
281        tracing::debug!("Detected {count} worker threads in runtime");
282        count
283    }
284
285    pub fn from_current() -> anyhow::Result<Runtime> {
286        Runtime::from_handle(tokio::runtime::Handle::current())
287    }
288
289    pub fn from_handle(handle: tokio::runtime::Handle) -> anyhow::Result<Runtime> {
290        let primary = RuntimeType::External(handle.clone());
291        let secondary = RuntimeType::External(handle);
292        Runtime::new(primary, Some(secondary))
293    }
294
295    /// Like [`Runtime::from_handle`], but also attaches the compute pool and `block_in_place`
296    /// permits that `config` implies, the way [`Runtime::from_settings`] does.
297    ///
298    /// For when the Tokio runtime is owned elsewhere — a process-wide `OnceCell`, say — so only a
299    /// handle can be borrowed, but the [`RuntimeConfig`] behind it is known.
300    pub fn from_handle_with_config(
301        handle: tokio::runtime::Handle,
302        config: &RuntimeConfig,
303    ) -> anyhow::Result<Runtime> {
304        let primary = RuntimeType::External(handle.clone());
305        let secondary = RuntimeType::External(handle);
306        Runtime::new_with_config(primary, Some(secondary), config)
307    }
308
309    /// Create a [`Runtime`] instance from the settings
310    /// See [`config::RuntimeConfig::from_settings`]
311    pub fn from_settings() -> anyhow::Result<Runtime> {
312        let config = config::RuntimeConfig::from_settings()?;
313        let runtime = Arc::new(ManuallyDrop::new(config.create_runtime()?));
314        let primary = RuntimeType::Shared(runtime.clone());
315        let secondary = RuntimeType::External(runtime.handle().clone());
316        Runtime::new_with_config(primary, Some(secondary), &config)
317    }
318
319    /// Create a [`Runtime`] with two single-threaded async tokio runtime
320    pub fn single_threaded() -> anyhow::Result<Runtime> {
321        let config = config::RuntimeConfig::single_threaded();
322        let owned = RuntimeType::Shared(Arc::new(ManuallyDrop::new(config.create_runtime()?)));
323        Runtime::new(owned, None)
324    }
325
326    /// Returns the unique identifier for the [`Runtime`]
327    pub fn id(&self) -> &str {
328        &self.id
329    }
330
331    /// Returns a [`tokio::runtime::Handle`] for the primary/application thread pool
332    pub fn primary(&self) -> tokio::runtime::Handle {
333        self.primary.handle()
334    }
335
336    /// Returns a [`tokio::runtime::Handle`] for the secondary/background thread pool
337    pub fn secondary(&self) -> tokio::runtime::Handle {
338        self.secondary.handle()
339    }
340
341    /// Access the primary [`CancellationToken`] for the [`Runtime`]
342    pub fn primary_token(&self) -> CancellationToken {
343        self.cancellation_token.clone()
344    }
345
346    /// Creates a child [`CancellationToken`] tied to the life-cycle of the [`Runtime`]'s endpoint shutdown token.
347    pub fn child_token(&self) -> CancellationToken {
348        self.endpoint_shutdown_token.child_token()
349    }
350
351    /// Get access to the graceful shutdown tracker
352    pub(crate) fn graceful_shutdown_tracker(&self) -> Arc<GracefulShutdownTracker> {
353        self.graceful_shutdown_tracker.clone()
354    }
355
356    pub(crate) fn velo_response_service(
357        &self,
358    ) -> Arc<crate::pipeline::network::velo_response::RuntimeService> {
359        self.velo_response_service.clone()
360    }
361
362    /// Get access to the compute pool for CPU-intensive operations
363    ///
364    /// Returns None if the compute pool was not initialized (e.g., due to configuration error)
365    pub fn compute_pool(&self) -> Option<&Arc<crate::compute::ComputePool>> {
366        self.compute_pool.as_ref()
367    }
368
369    /// Withdraw readiness before application draining without stopping the
370    /// endpoints or transports still needed to complete that drain.
371    pub fn mark_shutting_down(&self) {
372        if !self.shutdown_started.is_cancelled() {
373            tracing::info!("Runtime readiness withdrawn for shutdown");
374            self.shutdown_started.cancel();
375        }
376    }
377
378    pub fn is_shutting_down(&self) -> bool {
379        self.shutdown_started.is_cancelled()
380    }
381
382    /// Observe shutdown from its start, rather than waiting for transport teardown.
383    pub fn shutdown_started_token(&self) -> CancellationToken {
384        self.shutdown_started.child_token()
385    }
386
387    /// Shuts down the [`Runtime`] instance
388    pub fn shutdown(&self) {
389        self.mark_shutting_down();
390        tracing::info!("Runtime shutdown initiated");
391
392        // Spawn the shutdown coordination task BEFORE cancelling tokens
393        let tracker = self.graceful_shutdown_tracker.clone();
394        let main_token = self.cancellation_token.clone();
395        let endpoint_token = self.endpoint_shutdown_token.clone();
396        let velo_response_service = self.velo_response_service.clone();
397
398        // Use the runtime handle to spawn the task
399        let handle = self.primary();
400        handle.spawn(async move {
401            // Phase 1: Cancel endpoint shutdown token to stop accepting new requests
402            tracing::info!("Phase 1: Cancelling endpoint shutdown token");
403            endpoint_token.cancel();
404
405            // Phase 2: Wait for all graceful endpoints to complete
406            tracing::info!("Phase 2: Waiting for graceful endpoints to complete");
407
408            let count = tracker.get_count();
409            tracing::info!("Active graceful endpoints: {count}");
410
411            if count != 0 {
412                let timeout = graceful_shutdown_timeout();
413                if tokio::time::timeout(timeout, tracker.wait_for_completion())
414                    .await
415                    .is_err()
416                {
417                    let remaining = tracker.get_count();
418                    tracing::error!(
419                        timeout_secs = timeout.as_secs(),
420                        remaining_endpoints = remaining,
421                        "Graceful endpoint shutdown timed out; proceeding with runtime teardown"
422                    );
423                }
424            }
425
426            // Phase 3: Now connections will be disconnected to backend services (e.g. NATS/ETCD) by cancelling the main token
427            tracing::info!("Phase 3: Connections to backend services will now be disconnected");
428            velo_response_service.close();
429            main_token.cancel();
430
431            // The main token also starts the HTTP drain, so close the response
432            // service only after that drain and its streams finish. Other
433            // Runtime owners in this process keep their shared service alive.
434            // The main token is already cancelled and nothing awaits this task,
435            // so a slow close cannot hold up shutdown.
436            velo_response_service
437                .drain(velo_response_drain_window(), VELO_RESPONSE_DRAIN_HEADROOM)
438                .await;
439            velo_response_service.shutdown().await;
440        });
441    }
442}
443
444impl RuntimeType {
445    /// Get [`tokio::runtime::Handle`] to runtime
446    pub(crate) fn handle(&self) -> tokio::runtime::Handle {
447        match self {
448            RuntimeType::External(rt) => rt.clone(),
449            RuntimeType::Shared(rt) => rt.handle().clone(),
450        }
451    }
452}
453
454/// Handle dropping a tokio runtime from an async context.
455///
456/// When used from the Python bindings the runtime will be dropped from (I think) Python's asyncio.
457/// Tokio does not allow this and will panic. That panic prevents logging from printing it's last
458/// messages, which makes knowing what went wrong very difficult.
459///
460/// This is the panic:
461/// > pyo3_runtime.PanicException: Cannot drop a runtime in a context where blocking is not allowed.
462/// > This happens when a runtime is dropped from within an asynchronous context.
463///
464/// Hence we wrap the runtime in a ManuallyDrop and use tokio's alternative shutdown if we detect
465/// that we are inside an async runtime.
466impl Drop for RuntimeType {
467    fn drop(&mut self) {
468        match self {
469            RuntimeType::External(_) => {}
470            RuntimeType::Shared(arc) => {
471                let Some(md_runtime) = Arc::get_mut(arc) else {
472                    // Only drop if we are the only owner of the shared pointer, meaning
473                    // one strong count and no weak count.
474                    return;
475                };
476                if tokio::runtime::Handle::try_current().is_ok() {
477                    // We are inside an async runtime.
478                    let tokio_runtime = unsafe { ManuallyDrop::take(md_runtime) };
479                    tokio_runtime.shutdown_background();
480                } else {
481                    // We are not inside an async context, dropping the runtime is safe.
482                    //
483                    // We never reach this case. I'm not sure why, something about the interaction
484                    // with pyo3 and Python lifetimes.
485                    //
486                    // Process is gone so doesn't really matter, but TODO now that we realize it.
487                    unsafe { ManuallyDrop::drop(md_runtime) };
488                }
489            }
490        }
491    }
492}
493
494#[cfg(test)]
495mod tests {
496    use super::*;
497    use crate::config::environment_names::runtime as env_runtime;
498
499    #[tokio::test(start_paused = true)]
500    async fn shutdown_cancels_main_token_after_graceful_timeout() {
501        temp_env::async_with_vars(
502            [(
503                env_runtime::DYN_RUNTIME_GRACEFUL_SHUTDOWN_TIMEOUT_SECS,
504                Some("5"),
505            )],
506            async {
507                let runtime = Runtime::from_current().unwrap();
508                let tracker = runtime.graceful_shutdown_tracker();
509                let _guard = tracker.register_task();
510                let main_token = runtime.primary_token();
511                let endpoint_token = runtime.child_token();
512
513                runtime.shutdown();
514                tokio::task::yield_now().await;
515
516                assert!(endpoint_token.is_cancelled());
517                assert!(!main_token.is_cancelled());
518                assert_eq!(tracker.get_count(), 1);
519
520                tokio::time::advance(Duration::from_secs(4)).await;
521                tokio::task::yield_now().await;
522
523                assert!(!main_token.is_cancelled());
524
525                tokio::time::advance(Duration::from_secs(1)).await;
526                tokio::task::yield_now().await;
527
528                assert!(main_token.is_cancelled());
529                assert_eq!(tracker.get_count(), 1);
530            },
531        )
532        .await;
533    }
534}