dynamo-runtime 1.0.2

Dynamo Runtime Library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

//! Compute pool implementation with tokio-rayon integration
//!
//! The `ComputePool` allows multiple async tasks to concurrently submit different
//! types of parallel work to a shared Rayon thread pool. This enables efficient
//! CPU utilization without manual thread management.
//!
//! # Concurrent Usage Example
//!
//! ```ignore
//! use std::sync::Arc;
//! use dynamo_runtime::compute::ComputePool;
//! use rayon::prelude::*;
//!
//! async fn concurrent_processing(pool: Arc<ComputePool>) {
//!     // Task 1: Using scope for dynamic task generation
//!     let task1 = tokio::spawn({
//!         let pool = pool.clone();
//!         async move {
//!             pool.execute_scoped(|scope| {
//!                 // Dynamically spawn tasks based on runtime conditions
//!                 for i in 0..100 {
//!                     scope.spawn(move |_| {
//!                         // CPU-intensive work
//!                         let mut sum = 0u64;
//!                         for j in 0..1000 {
//!                             sum += (i * j) as u64;
//!                         }
//!                         sum
//!                     });
//!                 }
//!             }).await
//!         }
//!     });
//!
//!     // Task 2: Using parallel iterators for batch processing
//!     let task2 = tokio::spawn({
//!         let pool = pool.clone();
//!         async move {
//!             let data: Vec<u32> = (0..10000).collect();
//!             pool.install(|| {
//!                 data.par_chunks(100)
//!                     .map(|chunk| chunk.iter().sum::<u32>())
//!                     .collect::<Vec<_>>()
//!             }).await
//!         }
//!     });
//!
//!     // Both tasks run concurrently, sharing the same thread pool
//!     let (result1, result2) = tokio::join!(task1, task2);
//! }
//! ```
//!
//! # Thread Pool Sharing
//!
//! The Rayon thread pool uses work-stealing to efficiently distribute work from
//! multiple concurrent sources:
//!
//! - Tasks from `scope.spawn()` are pushed to thread-local deques
//! - Parallel iterators distribute work across all threads
//! - Idle threads steal work from busy threads
//! - No coordination needed between different parallelization patterns

use super::{ComputeConfig, ComputeMetrics};
use anyhow::Result;
use async_trait::async_trait;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

/// A compute pool that manages CPU-intensive operations
#[derive(Clone)]
pub struct ComputePool {
    /// The underlying Rayon thread pool
    pool: Arc<rayon::ThreadPool>,

    /// Metrics for monitoring compute operations
    metrics: Arc<ComputeMetrics>,

    /// Configuration used to create this pool
    config: ComputeConfig,
}

impl std::fmt::Debug for ComputePool {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ComputePool")
            .field("num_threads", &self.pool.current_num_threads())
            .field("metrics", &self.metrics)
            .field("config", &self.config)
            .finish()
    }
}

impl ComputePool {
    /// Create a new compute pool with the given configuration
    pub fn new(config: ComputeConfig) -> Result<Self> {
        let pool = config.build_pool()?;
        let metrics = Arc::new(ComputeMetrics::new());

        Ok(Self {
            pool: Arc::new(pool),
            metrics,
            config,
        })
    }

    /// Create a compute pool with default configuration
    pub fn with_defaults() -> Result<Self> {
        Self::new(ComputeConfig::default())
    }

    /// Execute a synchronous computation on the thread pool
    ///
    /// This method is designed to be called from within `spawn_blocking` or other
    /// synchronous contexts. It has minimal overhead as it directly uses Rayon
    /// without the async bridge.
    ///
    /// # Example
    /// ```ignore
    /// # use dynamo_runtime::compute::ComputePool;
    /// # let pool = ComputePool::new(Default::default()).unwrap();
    /// tokio::task::spawn_blocking(move || {
    ///     pool.execute_sync(|| {
    ///         // CPU-intensive work
    ///         expensive_computation()
    ///     })
    /// });
    /// ```
    pub fn execute_sync<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R + Send,
        R: Send,
    {
        self.pool.install(f)
    }

    /// Execute a compute task in the Rayon pool
    ///
    /// This bridges from async context to the Rayon thread pool,
    /// allowing CPU-intensive work to run without blocking Tokio workers.
    ///
    /// Note: This method has ~25μs overhead for small tasks due to the async
    /// channel communication. For very small computations (<100μs), consider
    /// running directly on Tokio or using `spawn_blocking` with `execute_sync`.
    pub async fn execute<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        self.metrics.record_task_start();
        let start = std::time::Instant::now();

        // Use tokio-rayon to bridge to the compute pool
        let pool = self.pool.clone();
        let result = tokio_rayon::spawn(move || pool.install(f)).await;

        self.metrics.record_task_completion(start.elapsed());
        Ok(result)
    }

    /// Execute a function with a Rayon scope
    ///
    /// This allows spawning multiple parallel tasks within the scope,
    /// with the guarantee that all tasks complete before returning.
    pub async fn execute_scoped<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&rayon::Scope) -> R + Send + 'static,
        R: Send + 'static,
    {
        self.metrics.record_task_start();
        let start = std::time::Instant::now();

        let pool = self.pool.clone();
        let result = tokio_rayon::spawn(move || {
            pool.install(|| {
                let mut result = None;
                rayon::scope(|s| {
                    result = Some(f(s));
                });
                result.unwrap()
            })
        })
        .await;

        self.metrics.record_task_completion(start.elapsed());
        Ok(result)
    }

    /// Execute a function with a FIFO scope
    ///
    /// Similar to execute_scoped, but tasks are prioritized in FIFO order
    /// rather than the default LIFO order.
    pub async fn execute_scoped_fifo<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce(&rayon::ScopeFifo) -> R + Send + 'static,
        R: Send + 'static,
    {
        self.metrics.record_task_start();
        let start = std::time::Instant::now();

        let pool = self.pool.clone();
        let result = tokio_rayon::spawn(move || {
            pool.install(|| {
                let mut result = None;
                rayon::scope_fifo(|s| {
                    result = Some(f(s));
                });
                result.unwrap()
            })
        })
        .await;

        self.metrics.record_task_completion(start.elapsed());
        Ok(result)
    }

    /// Join two computations in parallel
    pub async fn join<F1, F2, R1, R2>(&self, f1: F1, f2: F2) -> Result<(R1, R2)>
    where
        F1: FnOnce() -> R1 + Send + 'static,
        F2: FnOnce() -> R2 + Send + 'static,
        R1: Send + 'static,
        R2: Send + 'static,
    {
        self.execute(move || rayon::join(f1, f2)).await
    }

    /// Get metrics for this compute pool
    pub fn metrics(&self) -> &ComputeMetrics {
        &self.metrics
    }

    /// Get the number of threads in the pool
    pub fn num_threads(&self) -> usize {
        self.pool.current_num_threads()
    }

    /// Install this pool as the Rayon pool for the given closure
    ///
    /// This method is essential for using Rayon's parallel iterators (like `par_iter`,
    /// `par_chunks`, etc.) with this specific thread pool. Any parallel iterator
    /// operations within the closure will execute on this pool's threads.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use rayon::prelude::*;
    ///
    /// // Process data using parallel iterators
    /// let result = pool.install(|| {
    ///     data.par_chunks(100)
    ///         .map(|chunk| process_chunk(chunk))
    ///         .collect::<Vec<_>>()
    /// }).await?;
    /// ```
    ///
    /// # Concurrent Usage
    ///
    /// Multiple async tasks can call `install()` concurrently on the same pool.
    /// The Rayon work-stealing scheduler will efficiently distribute work from
    /// all concurrent operations:
    ///
    /// ```ignore
    /// // These can run concurrently without interference
    /// let task1 = pool.install(|| data1.par_iter().map(f1).collect());
    /// let task2 = pool.install(|| data2.par_chunks(50).map(f2).collect());
    /// ```
    pub async fn install<F, R>(&self, f: F) -> Result<R>
    where
        F: FnOnce() -> R + Send + 'static,
        R: Send + 'static,
    {
        let pool = self.pool.clone();
        self.metrics.record_task_start();
        let start = std::time::Instant::now();

        let result = tokio_rayon::spawn(move || pool.install(f)).await;

        self.metrics.record_task_completion(start.elapsed());
        Ok(result)
    }
}

/// A handle to a compute task that's currently running
pub struct ComputeHandle<T> {
    inner: Pin<Box<dyn Future<Output = T> + Send>>,
}

impl<T> ComputeHandle<T> {
    /// Create a new compute handle from a future
    pub(crate) fn new<F>(future: F) -> Self
    where
        F: Future<Output = T> + Send + 'static,
    {
        Self {
            inner: Box::pin(future),
        }
    }
}

impl<T> Future for ComputeHandle<T> {
    type Output = T;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.as_mut().poll(cx)
    }
}

/// Extension trait for ComputePool with additional patterns
#[async_trait]
pub trait ComputePoolExt {
    /// Process items in parallel batches
    async fn parallel_batch<T, F, R>(
        &self,
        items: Vec<T>,
        batch_size: usize,
        f: F,
    ) -> Result<Vec<R>>
    where
        T: Send + Sync + 'static,
        F: Fn(&[T]) -> Vec<R> + Send + Sync + 'static,
        R: Send + 'static;

    /// Map over items in parallel using Rayon's par_iter
    async fn parallel_map<T, F, R>(&self, items: Vec<T>, f: F) -> Result<Vec<R>>
    where
        T: Send + Sync + 'static,
        F: Fn(T) -> R + Send + Sync + 'static,
        R: Send + 'static;
}

#[async_trait]
impl ComputePoolExt for ComputePool {
    async fn parallel_batch<T, F, R>(
        &self,
        items: Vec<T>,
        batch_size: usize,
        f: F,
    ) -> Result<Vec<R>>
    where
        T: Send + Sync + 'static,
        F: Fn(&[T]) -> Vec<R> + Send + Sync + 'static,
        R: Send + 'static,
    {
        use rayon::prelude::*;

        self.install(move || items.par_chunks(batch_size).flat_map(f).collect())
            .await
    }

    async fn parallel_map<T, F, R>(&self, items: Vec<T>, f: F) -> Result<Vec<R>>
    where
        T: Send + Sync + 'static,
        F: Fn(T) -> R + Send + Sync + 'static,
        R: Send + 'static,
    {
        use rayon::prelude::*;

        self.install(move || items.into_par_iter().map(f).collect())
            .await
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use parking_lot::Mutex;

    #[tokio::test]
    async fn test_compute_pool_execute() {
        let pool = ComputePool::with_defaults().unwrap();

        let result = pool
            .execute(|| {
                // Simulate CPU-intensive work
                let mut sum = 0u64;
                for i in 0..1000 {
                    sum += i;
                }
                sum
            })
            .await
            .unwrap();

        assert_eq!(result, 499500);
    }

    #[tokio::test]
    async fn test_compute_pool_join() {
        let pool = ComputePool::with_defaults().unwrap();

        let (a, b) = pool.join(|| 2 + 2, || 3 * 3).await.unwrap();

        assert_eq!(a, 4);
        assert_eq!(b, 9);
    }

    #[tokio::test]
    async fn test_compute_pool_execute_sync() {
        let pool = Arc::new(ComputePool::with_defaults().unwrap());

        // Test using execute_sync from spawn_blocking
        let pool_clone = pool.clone();
        let result = tokio::task::spawn_blocking(move || {
            pool_clone.execute_sync(|| {
                let mut sum = 0u64;
                for i in 0..1000 {
                    sum += i;
                }
                sum
            })
        })
        .await
        .unwrap();

        assert_eq!(result, 499500);
    }

    #[tokio::test]
    async fn test_compute_pool_scoped() {
        use std::sync::mpsc;

        let pool = ComputePool::with_defaults().unwrap();

        let mut result = pool
            .execute_scoped(|scope| {
                let (tx, rx) = mpsc::channel();

                for i in 0..4 {
                    let tx = tx.clone();
                    scope.spawn(move |_| {
                        tx.send((i, i * 2)).unwrap();
                    });
                }

                drop(tx); // Close sender so receiver can finish

                let mut results = vec![0; 4];
                for (i, val) in rx {
                    results[i] = val;
                }
                results
            })
            .await
            .unwrap();

        // Results may be in any order due to parallel execution
        result.sort();
        assert_eq!(result, vec![0, 2, 4, 6]);
    }
}