Skip to main content

near_async/
thread_pool.rs

1use crate::futures::AsyncComputationSpawner;
2use near_o11y::metrics::{IntGaugeVec, try_create_int_gauge_vec};
3use parking_lot::{Condvar, Mutex};
4use std::collections::VecDeque;
5use std::sync::{Arc, LazyLock};
6use std::time::Duration;
7#[cfg(unix)]
8use thread_priority::{
9    RealtimeThreadSchedulePolicy, ThreadBuilder, ThreadPriority, ThreadSchedulePolicy,
10};
11
12pub type Job = Box<dyn FnOnce() + Send + 'static>;
13
14/// Ordering discipline for a [`ThreadPool`]'s pending jobs. The default
15/// [`FifoQueue`] keeps first-in-first-out order.
16pub trait JobQueue: Default + Send + 'static {
17    fn push(&mut self, job: Job);
18    fn pop(&mut self) -> Option<Job>;
19    fn len(&self) -> usize;
20    fn is_empty(&self) -> bool {
21        self.len() == 0
22    }
23}
24
25/// First-in-first-out job queue.
26#[derive(Default)]
27pub struct FifoQueue(VecDeque<Job>);
28
29impl JobQueue for FifoQueue {
30    fn push(&mut self, job: Job) {
31        self.0.push_back(job);
32    }
33    fn pop(&mut self) -> Option<Job> {
34        self.0.pop_front()
35    }
36    fn len(&self) -> usize {
37        self.0.len()
38    }
39}
40
41static THREAD_POOL_NUM_THREADS: LazyLock<IntGaugeVec> = LazyLock::new(|| {
42    try_create_int_gauge_vec(
43        "near_thread_pool_num_threads",
44        "current number of threads in the thread pool",
45        &["pool_name"],
46    )
47    .unwrap()
48});
49
50static THREAD_POOL_MAX_NUM_THREADS: LazyLock<IntGaugeVec> = LazyLock::new(|| {
51    try_create_int_gauge_vec(
52        "near_thread_pool_max_num_threads",
53        "maximum observed number of threads in the thread pool",
54        &["pool_name"],
55    )
56    .unwrap()
57});
58
59static THREAD_POOL_QUEUE_SIZE: LazyLock<IntGaugeVec> = LazyLock::new(|| {
60    try_create_int_gauge_vec(
61        "near_thread_pool_queue_size",
62        "thread pool job queue size",
63        &["pool_name"],
64    )
65    .unwrap()
66});
67
68/// OS thread pool for spawning computation tasks.
69///
70/// The pool enforces a hard limit on the number of threads. If all threads are
71/// busy and the limit is reached, the job execution will be queued until a thread
72/// becomes available. Idle threads are kept for `idle_timeout` to be potentially
73/// reused for new tasks. All threads in the pool are spawned under round-robin
74/// realtime policy (`SCHED_RR`) with a configured `priority`. Realtime threads
75/// **always** take precedence over threads using normal policy (`SCHED_OTHER`),
76/// so `priority` applies **only among other realtime threads**.
77///
78/// Workers are plain OS threads — they do **not** participate in rayon's
79/// work-stealing scheduler. This is important when spawned tasks may trigger
80/// rayon-based parallel work internally (e.g. wasmtime's parallel compilation):
81/// since the workers are not rayon threads, nested `rayon::join()` calls fall
82/// through to the global rayon pool instead of the worker's pool, avoiding
83/// deadlocks from recursive work-stealing.
84pub struct ThreadPool<Q: JobQueue = FifoQueue> {
85    name: &'static str,
86    /// Thread priority in [0; 99] range. Only used on unix for SCHED_RR policy.
87    #[cfg(unix)]
88    priority: u8,
89    idle_timeout: Duration,
90    thread_limit: usize,
91    state: Arc<ThreadPoolState<Q>>,
92}
93
94impl<Q: JobQueue> std::fmt::Debug for ThreadPool<Q> {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.debug_struct("ThreadPool").field("name", &self.name).finish()
97    }
98}
99
100struct ThreadPoolStateInner<Q: JobQueue> {
101    name: &'static str,
102    queue: Q,
103    total_threads: usize,
104    idle_threads: usize,
105    shutdown: bool,
106}
107
108impl<Q: JobQueue> ThreadPoolStateInner<Q> {
109    fn new(name: &'static str) -> Self {
110        Self { name, queue: Q::default(), total_threads: 0, idle_threads: 0, shutdown: false }
111    }
112
113    fn enqueue(&mut self, job: Job) {
114        self.queue.push(job);
115        self.update_queue_metrics();
116    }
117
118    fn dequeue(&mut self) -> Option<Job> {
119        let ret = self.queue.pop();
120        if ret.is_some() {
121            self.update_queue_metrics();
122        }
123        ret
124    }
125
126    fn inc_idle_threads(&mut self) {
127        self.idle_threads += 1;
128    }
129
130    fn dec_idle_threads(&mut self) {
131        self.idle_threads -= 1;
132    }
133
134    fn inc_total_threads(&mut self) {
135        self.total_threads += 1;
136        self.update_total_threads_metrics();
137    }
138
139    fn dec_total_threads(&mut self) {
140        self.total_threads -= 1;
141        self.update_total_threads_metrics();
142    }
143
144    fn update_queue_metrics(&self) {
145        THREAD_POOL_QUEUE_SIZE.with_label_values(&[self.name]).set(self.queue.len() as i64);
146    }
147
148    fn update_total_threads_metrics(&self) {
149        THREAD_POOL_NUM_THREADS.with_label_values(&[self.name]).set(self.total_threads as i64);
150        let max_num_threads = THREAD_POOL_MAX_NUM_THREADS.with_label_values(&[self.name]);
151        if self.total_threads > max_num_threads.get() as usize {
152            max_num_threads.set(self.total_threads as i64);
153        }
154    }
155}
156
157struct ThreadPoolState<Q: JobQueue> {
158    inner: Mutex<ThreadPoolStateInner<Q>>,
159    /// Signaled when new task is added to the queue or on shutdown.
160    condvar: Condvar,
161}
162
163impl<Q: JobQueue> Drop for ThreadPool<Q> {
164    fn drop(&mut self) {
165        self.state.inner.lock().shutdown = true;
166        self.state.condvar.notify_all();
167    }
168}
169
170impl ThreadPool<FifoQueue> {
171    /// Create a new thread pool. Panics if priority is out of [0; 99] range.
172    pub fn new(name: &'static str, idle_timeout: Duration, limit: usize, priority: u8) -> Self {
173        assert!(priority <= 99, "priority out of range");
174        Self {
175            name,
176            #[cfg(unix)]
177            priority,
178            idle_timeout,
179            thread_limit: limit,
180            state: Arc::new(ThreadPoolState {
181                inner: Mutex::new(ThreadPoolStateInner::new(name)),
182                condvar: Condvar::new(),
183            }),
184        }
185    }
186}
187
188impl<Q: JobQueue> ThreadPool<Q> {
189    /// Spawn a new task to be run on the pool. It will re-use existing idle threads
190    /// if possible, or spawn a new thread (up to the configured limit).
191    /// If at the thread limit and no idle threads are available, the job will be
192    /// queued until a thread becomes available. The caller thread is never blocked.
193    pub fn spawn_boxed(&self, job: Job) {
194        let mut state_guard = self.state.inner.lock();
195        state_guard.enqueue(job);
196        if state_guard.idle_threads > 0 {
197            self.state.condvar.notify_one();
198            return;
199        }
200        if state_guard.total_threads < self.thread_limit {
201            state_guard.inc_total_threads();
202            drop(state_guard);
203            self.spawn_thread();
204        } else {
205            tracing::trace!(
206                target: "near_async::thread_pool",
207                pool = self.name,
208                limit = self.thread_limit,
209                queue_size = state_guard.queue.len(),
210                "job execution is delayed, thread pool is at capacity"
211            );
212        }
213    }
214
215    fn spawn_thread(&self) {
216        let name = self.name;
217        let idle_timeout = self.idle_timeout;
218        let state = self.state.clone();
219        #[cfg(unix)]
220        {
221            let priority: ThreadPriority = self.priority.try_into().expect("priority out of range");
222            ThreadBuilder::default()
223                .name(name)
224                .policy(ThreadSchedulePolicy::Realtime(RealtimeThreadSchedulePolicy::RoundRobin))
225                .priority(priority)
226                .spawn(move |res| {
227                    if let Err(err) = res {
228                        tracing::debug!(
229                            target: "near_async::thread_pool",
230                            pool = name,
231                            err = %err,
232                            "set scheduler policy failed"
233                        );
234                    };
235                    run_worker(state, idle_timeout)
236                })
237                .expect("failed to spawn thread");
238        }
239        #[cfg(not(unix))]
240        {
241            std::thread::Builder::new()
242                .name(name.to_string())
243                .spawn(move || run_worker(state, idle_timeout))
244                .expect("failed to spawn thread");
245        }
246    }
247
248    #[cfg(test)]
249    fn state(&self) -> &Arc<ThreadPoolState<Q>> {
250        &self.state
251    }
252}
253
254impl<Q: JobQueue> AsyncComputationSpawner for ThreadPool<Q> {
255    fn spawn_boxed(&self, _name: &str, job: Box<dyn FnOnce() + Send>) {
256        self.spawn_boxed(job)
257    }
258}
259
260struct ThreadCountGuard<Q: JobQueue>(Arc<ThreadPoolState<Q>>);
261
262impl<Q: JobQueue> Drop for ThreadCountGuard<Q> {
263    fn drop(&mut self) {
264        self.0.inner.lock().dec_total_threads();
265    }
266}
267
268/// Start a worker thread. It will then pick up jobs from the queue one at a time in
269/// a loop. The thread will terminate if it's idle for `idle_timeout` or when
270/// shutdown is triggered via `shutdown` flag.
271fn run_worker<Q: JobQueue>(state: Arc<ThreadPoolState<Q>>, idle_timeout: Duration) {
272    // `_thread_count_guard` must be declared before `state_guard` so that
273    // the mutex lock is dropped first during unwinding (reverse declaration
274    // order), avoiding deadlock when the guard acquires the lock in its Drop.
275    let _thread_count_guard = ThreadCountGuard(state.clone());
276    let mut state_guard = state.inner.lock();
277    loop {
278        if state_guard.shutdown {
279            tracing::trace!(
280                target: "near_async::thread_pool",
281                pool = state_guard.name,
282                "terminate thread at shutdown"
283            );
284            break;
285        }
286        if let Some(job) = state_guard.dequeue() {
287            drop(state_guard);
288            job();
289            state_guard = state.inner.lock();
290        } else {
291            state_guard.inc_idle_threads();
292            let timeout_res = state.condvar.wait_for(&mut state_guard, idle_timeout);
293            state_guard.dec_idle_threads();
294            // Note on queue check on timeout:
295            // If an idle thread's `wait_for` times out concurrently with `spawn_boxed` enqueueing a job and
296            // calling `notify_one()` (which saw `idle_threads > 0` and thus didn't spawn a new thread), the job
297            // can be orphaned in the queue. So we need to make sure the queue is empty before exiting the thread.
298            if timeout_res.timed_out() && state_guard.queue.is_empty() {
299                tracing::trace!(
300                    target: "near_async::thread_pool",
301                    pool = state_guard.name,
302                    "terminate idle thread"
303                );
304                break;
305            }
306        }
307    }
308}
309
310// ---------------------------------------------------------------------------
311// Named pool instances.
312// ---------------------------------------------------------------------------
313
314// SCHED_RR priorities (higher preempts lower)
315/// Contract compilation and pipelining
316const PRIORITY_CONTRACT_COMPILATION: u8 = 55;
317/// Chunk application, incl. witness validation.
318const PRIORITY_APPLY_CHUNKS: u8 = 50;
319/// Validation/forwarding of partial encoded witnesses
320const PRIORITY_PARTIAL_WITNESS_VALIDATION: u8 = 70;
321/// Witness creation
322const PRIORITY_WITNESS_CREATION: u8 = 70;
323/// Background compiled-contract-runtime maintenance: cache warming for
324/// upcoming protocol upgrades, on-disk cache atime refresh, etc.
325const PRIORITY_BACKGROUND_RUNTIME_TASKS: u8 = 10;
326
327/// Shared thread pool for contract compilation and pipelining.
328pub fn contract_compilation_pool() -> &'static Arc<ThreadPool> {
329    static POOL: std::sync::OnceLock<Arc<ThreadPool>> = std::sync::OnceLock::new();
330    POOL.get_or_init(|| {
331        let thread_limit = std::thread::available_parallelism().map_or(4, |n| n.get());
332        Arc::new(ThreadPool::new(
333            "contract_compilation",
334            Duration::from_hours(1),
335            thread_limit,
336            PRIORITY_CONTRACT_COMPILATION,
337        ))
338    })
339}
340
341/// Shared pool for low-priority, fire-and-forget contract-runtime maintenance.
342/// Runs at the low (realtime) priority.
343pub fn background_runtime_tasks() -> &'static Arc<ThreadPool> {
344    static POOL: std::sync::OnceLock<Arc<ThreadPool>> = std::sync::OnceLock::new();
345    POOL.get_or_init(|| {
346        Arc::new(ThreadPool::new(
347            "background_runtime_tasks",
348            Duration::from_secs(60),
349            1,
350            PRIORITY_BACKGROUND_RUNTIME_TASKS,
351        ))
352    })
353}
354
355/// Async computation spawner to be used for chunk applying tasks.
356#[derive(Default)]
357pub enum ApplyChunksSpawner {
358    /// Use a pool of OS-based high priority threads, limited by the number of shards.
359    #[default]
360    Default,
361    /// Use a custom spawner, e.g. rayon.
362    Custom(Arc<dyn AsyncComputationSpawner>),
363}
364
365impl ApplyChunksSpawner {
366    /// Get the custom spawner, or create the default spawner with the given thread limit.
367    pub fn into_spawner(self, thread_limit: usize) -> Arc<dyn AsyncComputationSpawner> {
368        match self {
369            ApplyChunksSpawner::Default => Arc::new(ThreadPool::new(
370                "apply_chunks",
371                Duration::from_secs(30),
372                thread_limit,
373                PRIORITY_APPLY_CHUNKS,
374            )),
375            ApplyChunksSpawner::Custom(spawner) => spawner,
376        }
377    }
378}
379
380/// High-priority thread pool for validating partial chunk witnesses.
381pub struct PartialWitnessValidationThreadPool(ThreadPool);
382
383impl PartialWitnessValidationThreadPool {
384    pub fn new() -> Self {
385        Self(ThreadPool::new(
386            "partial_witness_validation",
387            Duration::from_secs(30),
388            96,
389            PRIORITY_PARTIAL_WITNESS_VALIDATION,
390        ))
391    }
392}
393
394impl AsyncComputationSpawner for PartialWitnessValidationThreadPool {
395    fn spawn_boxed(&self, _name: &str, job: Box<dyn FnOnce() + Send>) {
396        self.0.spawn_boxed(job)
397    }
398}
399
400/// High-priority thread pool for creating chunk witnesses.
401pub struct WitnessCreationThreadPool(ThreadPool);
402
403impl WitnessCreationThreadPool {
404    pub fn new() -> Self {
405        Self(ThreadPool::new(
406            "witness_creation",
407            Duration::from_secs(30),
408            6,
409            PRIORITY_WITNESS_CREATION,
410        ))
411    }
412}
413
414impl AsyncComputationSpawner for WitnessCreationThreadPool {
415    fn spawn_boxed(&self, _name: &str, job: Box<dyn FnOnce() + Send>) {
416        self.0.spawn_boxed(job)
417    }
418}
419
420#[cfg(test)]
421mod tests {
422    use super::*;
423    use std::sync::mpsc;
424    use std::thread::{self, ThreadId};
425    use std::time::Instant;
426
427    const POOL_NAME: &str = "test_pool";
428    const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(2);
429    const DEFAULT_LIMIT: usize = 2;
430    const DEFAULT_PRIORITY: u8 = 50;
431
432    #[derive(Debug)]
433    struct JobExecutionOutcome {
434        thread_id: ThreadId,
435    }
436
437    struct JobHandle {
438        scheduled_receiver: mpsc::Receiver<()>,
439        start_sender: mpsc::Sender<()>,
440        done_receiver: mpsc::Receiver<JobExecutionOutcome>,
441    }
442
443    impl JobHandle {
444        fn start_execution(self) -> mpsc::Receiver<JobExecutionOutcome> {
445            self.start_sender.send(()).unwrap();
446            self.done_receiver
447        }
448
449        fn wait_scheduled(&self) {
450            self.scheduled_receiver.recv().unwrap();
451        }
452
453        fn wait_executed(self) -> JobExecutionOutcome {
454            self.start_execution().recv().unwrap()
455        }
456    }
457
458    fn create_job() -> (Job, JobHandle) {
459        let (scheduled_sender, scheduled_receiver) = mpsc::channel();
460        let (start_sender, start_receiver) = mpsc::channel();
461        let (done_sender, done_receiver) = mpsc::channel();
462        let job = Box::new(move || {
463            let _ = scheduled_sender.send(());
464            if start_receiver.recv().is_err() {
465                return;
466            };
467            let thread_id = thread::current().id();
468            let outcome = JobExecutionOutcome { thread_id };
469            let _ = done_sender.send(outcome);
470        });
471        let start_trigger = JobHandle { scheduled_receiver, start_sender, done_receiver };
472        (job, start_trigger)
473    }
474
475    fn execute_job(pool: &ThreadPool) -> JobExecutionOutcome {
476        let (job, handle) = create_job();
477        pool.spawn_boxed(job);
478        handle.wait_executed()
479    }
480
481    /// Waits for condition to become true, polling with short yields.
482    /// Panics with the given message if timeout is reached.
483    fn wait_for(condition: impl Fn() -> bool, msg: &str) {
484        const WAIT_TIMEOUT: Duration = Duration::from_secs(1);
485        let start = Instant::now();
486        while !condition() {
487            if start.elapsed() > WAIT_TIMEOUT {
488                panic!("timeout waiting for {}", msg);
489            }
490            thread::yield_now();
491        }
492    }
493
494    #[test]
495    #[should_panic(expected = "priority out of range")]
496    fn invalid_priority() {
497        ThreadPool::new(POOL_NAME, DEFAULT_IDLE_TIMEOUT, DEFAULT_LIMIT, 100);
498    }
499
500    #[test]
501    fn single_job() {
502        let pool =
503            ThreadPool::new(POOL_NAME, DEFAULT_IDLE_TIMEOUT, DEFAULT_LIMIT, DEFAULT_PRIORITY);
504        execute_job(&pool);
505    }
506
507    #[test]
508    fn thread_reuse() {
509        let limit = 2;
510        let pool = ThreadPool::new(POOL_NAME, DEFAULT_IDLE_TIMEOUT, limit, DEFAULT_PRIORITY);
511
512        let outcome1 = execute_job(&pool);
513        wait_for(|| pool.state().inner.lock().idle_threads == 1, "thread to become idle");
514        let outcome2 = execute_job(&pool);
515
516        assert_eq!(outcome1.thread_id, outcome2.thread_id);
517    }
518
519    #[test]
520    fn concurrent_execution() {
521        let limit = 2;
522        let pool = ThreadPool::new(POOL_NAME, DEFAULT_IDLE_TIMEOUT, limit, DEFAULT_PRIORITY);
523
524        let (job1, handle1) = create_job();
525        pool.spawn_boxed(job1);
526        handle1.wait_scheduled();
527        let (job2, handle2) = create_job();
528        pool.spawn_boxed(job2);
529        handle2.wait_scheduled();
530
531        let outcome1 = handle1.wait_executed();
532        let outcome2 = handle2.wait_executed();
533
534        assert_ne!(outcome1.thread_id, outcome2.thread_id);
535    }
536
537    #[test]
538    fn idle_timeout() {
539        let idle_timeout = Duration::ZERO;
540        let pool = ThreadPool::new(POOL_NAME, idle_timeout, DEFAULT_LIMIT, DEFAULT_PRIORITY);
541
542        let outcome1 = execute_job(&pool);
543        wait_for(|| pool.state().inner.lock().total_threads == 0, "thread shutdown");
544        let outcome2 = execute_job(&pool);
545
546        assert_ne!(outcome1.thread_id, outcome2.thread_id);
547    }
548
549    #[test]
550    fn thread_limit_enforced() {
551        let limit = 1;
552        let pool = ThreadPool::new(POOL_NAME, DEFAULT_IDLE_TIMEOUT, limit, DEFAULT_PRIORITY);
553
554        let (job1, handle1) = create_job();
555        pool.spawn_boxed(job1);
556        handle1.wait_scheduled();
557
558        let (job2, handle2) = create_job();
559        pool.spawn_boxed(job2);
560
561        assert_eq!(pool.state().inner.lock().total_threads, 1);
562        assert_eq!(pool.state().inner.lock().queue.len(), 1);
563
564        let outcome1 = handle1.wait_executed();
565        let outcome2 = handle2.wait_executed();
566        assert_eq!(outcome1.thread_id, outcome2.thread_id);
567    }
568
569    #[test]
570    fn drop_shuts_down_threads() {
571        let idle_timeout = Duration::from_secs(1000);
572        let pool = ThreadPool::new(POOL_NAME, idle_timeout, DEFAULT_LIMIT, DEFAULT_PRIORITY);
573
574        execute_job(&pool);
575
576        let state = pool.state().clone();
577        wait_for(|| state.inner.lock().idle_threads == 1, "thread to become idle");
578
579        drop(pool);
580
581        wait_for(|| state.inner.lock().total_threads == 0, "threads to shut down after drop");
582    }
583}