dynamo_runtime/
runtime.rs1use 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
46fn 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
60const VELO_RESPONSE_DRAIN_HEADROOM: Duration = Duration::from_secs(10);
62
63#[derive(Clone, Debug)]
65pub(crate) enum RuntimeType {
66 Shared(Arc<ManuallyDrop<tokio::runtime::Runtime>>),
67 External(tokio::runtime::Handle),
68}
69
70#[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 crate::nvtx::init()?;
90
91 let id = Arc::new(uuid::Uuid::new_v4().to_string());
93
94 let cancellation_token = CancellationToken::new();
96
97 let endpoint_shutdown_token = cancellation_token.child_token();
99 let shutdown_started = endpoint_shutdown_token.child_token();
100
101 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 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 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 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 let num_workers = config
171 .num_worker_threads
172 .unwrap_or_else(|| std::thread::available_parallelism().unwrap().get());
173 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 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 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 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 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 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 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 barrier_clone.wait();
225
226 crate::compute::thread_local::initialize_context(pool_clone, permits_clone);
228
229 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 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 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 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 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 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 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 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 pub fn id(&self) -> &str {
328 &self.id
329 }
330
331 pub fn primary(&self) -> tokio::runtime::Handle {
333 self.primary.handle()
334 }
335
336 pub fn secondary(&self) -> tokio::runtime::Handle {
338 self.secondary.handle()
339 }
340
341 pub fn primary_token(&self) -> CancellationToken {
343 self.cancellation_token.clone()
344 }
345
346 pub fn child_token(&self) -> CancellationToken {
348 self.endpoint_shutdown_token.child_token()
349 }
350
351 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 pub fn compute_pool(&self) -> Option<&Arc<crate::compute::ComputePool>> {
366 self.compute_pool.as_ref()
367 }
368
369 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 pub fn shutdown_started_token(&self) -> CancellationToken {
384 self.shutdown_started.child_token()
385 }
386
387 pub fn shutdown(&self) {
389 self.mark_shutting_down();
390 tracing::info!("Runtime shutdown initiated");
391
392 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 let handle = self.primary();
400 handle.spawn(async move {
401 tracing::info!("Phase 1: Cancelling endpoint shutdown token");
403 endpoint_token.cancel();
404
405 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 tracing::info!("Phase 3: Connections to backend services will now be disconnected");
428 velo_response_service.close();
429 main_token.cancel();
430
431 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 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
454impl 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 return;
475 };
476 if tokio::runtime::Handle::try_current().is_ok() {
477 let tokio_runtime = unsafe { ManuallyDrop::take(md_runtime) };
479 tokio_runtime.shutdown_background();
480 } else {
481 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}