Skip to main content

nu_command/filters/
par_each.rs

1use super::utils::chain_error_with_input;
2use nu_engine::{ClosureEval, ClosureEvalOnce, command_prelude::*};
3use nu_protocol::{Signals, engine::Closure, shell_error::generic::GenericError};
4use rayon::prelude::*;
5use std::{
6    collections::HashMap,
7    sync::{
8        Arc, Mutex, OnceLock,
9        mpsc::{self, RecvTimeoutError},
10    },
11    time::Duration,
12};
13
14const STREAM_BUFFER_SIZE: usize = 64;
15const CTRL_C_CHECK_INTERVAL: Duration = Duration::from_millis(100);
16
17/// Cache of thread pools keyed by thread count.
18///
19/// Reuses an existing pool instead of spawning OS threads on every top-level `par-each`.
20/// Nested calls intentionally bypass this cache (see [`create_pool`]).
21///
22/// Key `0` means "default size" (`ThreadPoolBuilder::num_threads(0)` → logical CPUs).
23/// Distinct `-t` sizes are rare in practice, so the map is not bounded.
24///
25/// These pools are **dedicated to `par-each`**. We intentionally never use Rayon's
26/// process-wide global pool: other commands (`glob` with dc-glob, `ls`, …) also schedule
27/// work there, and sharing it with the streaming path can deadlock when pool workers
28/// block on channel receives while a producer waits for a free worker.
29static THREAD_POOLS: OnceLock<Mutex<HashMap<usize, Arc<rayon::ThreadPool>>>> = OnceLock::new();
30
31fn lock_pool_cache(
32    head: Span,
33) -> Result<std::sync::MutexGuard<'static, HashMap<usize, Arc<rayon::ThreadPool>>>, ShellError> {
34    let pools = THREAD_POOLS.get_or_init(|| Mutex::new(HashMap::new()));
35    pools.lock().map_err(|e| {
36        ShellError::Generic(GenericError::new(
37            "Error locking thread pool cache",
38            e.to_string(),
39            head,
40        ))
41    })
42}
43
44fn build_pool(num_threads: usize, head: Span) -> Result<Arc<rayon::ThreadPool>, ShellError> {
45    rayon::ThreadPoolBuilder::new()
46        .num_threads(num_threads)
47        .build()
48        .map(Arc::new)
49        .map_err(|e| {
50            ShellError::Generic(GenericError::new(
51                "Error creating thread pool",
52                e.to_string(),
53                head,
54            ))
55        })
56}
57
58/// Get or create a thread pool for this `par-each` invocation.
59///
60/// - Top-level: reuse a process-wide cached pool. `num_threads == 0` is the default
61///   size pool (still private to `par-each`, not Rayon's global pool).
62/// - **Nested** calls (already running on a Rayon worker): always build a **private,
63///   uncached** pool. Sharing the outer pool deadlocks because the streaming path
64///   blocks the caller on a channel while holding a worker of that same pool.
65///
66/// Pool construction for the cache path runs outside the cache lock so concurrent
67/// top-level callers are not blocked while OS threads are spawned. A second lookup
68/// after build handles races.
69fn create_pool(num_threads: usize, head: Span) -> Result<Arc<rayon::ThreadPool>, ShellError> {
70    // Nested: never share a pool with the outer `par-each` (or any other Rayon pool).
71    if rayon::current_thread_index().is_some() {
72        // `num_threads == 0` => Rayon default (logical CPU count), same as a fresh builder.
73        return build_pool(num_threads, head);
74    }
75
76    {
77        let pools = lock_pool_cache(head)?;
78        if let Some(pool) = pools.get(&num_threads) {
79            return Ok(pool.clone());
80        }
81    }
82
83    let built = build_pool(num_threads, head)?;
84
85    let mut pools = lock_pool_cache(head)?;
86    // Another caller may have inserted the same key while we were building.
87    Ok(pools.entry(num_threads).or_insert(built).clone())
88}
89
90#[derive(Clone)]
91pub struct ParEach;
92
93impl Command for ParEach {
94    fn name(&self) -> &str {
95        "par-each"
96    }
97
98    fn description(&self) -> &str {
99        "Run a closure on each row of the input list in parallel, creating a new list with the results."
100    }
101
102    fn extra_description(&self) -> &str {
103        " Uses a dedicated thread pool (reused across top-level calls; sized by --threads when set). Nested par-each calls use a private pool so they cannot deadlock on the outer pool."
104    }
105
106    fn signature(&self) -> nu_protocol::Signature {
107        Signature::build("par-each")
108            .input_output_types(vec![
109                (
110                    Type::List(Box::new(Type::Any)),
111                    Type::List(Box::new(Type::Any)),
112                ),
113                (Type::table(), Type::List(Box::new(Type::Any))),
114                (Type::Any, Type::Any),
115            ])
116            .named(
117                "threads",
118                SyntaxShape::Int,
119                "The number of threads to use.",
120                Some('t'),
121            )
122            .switch(
123                "keep-order",
124                "Keep sequence of output same as the order of input.",
125                Some('k'),
126            )
127            .required(
128                "closure",
129                SyntaxShape::Closure(Some(vec![SyntaxShape::Any])),
130                "The closure to run.",
131            )
132            .allow_variants_without_examples(true)
133            .category(Category::Filters)
134    }
135
136    fn examples(&self) -> Vec<Example<'_>> {
137        vec![
138            Example {
139                example: "[1 2 3] | par-each {|e| $e * 2 }",
140                description: "Multiplies each number. Note that the list will become arbitrarily disordered.",
141                result: None,
142            },
143            Example {
144                example: "[1 2 3] | par-each --keep-order {|e| $e * 2 }",
145                description: "Multiplies each number, keeping an original order.",
146                result: Some(Value::test_list(vec![
147                    Value::test_int(2),
148                    Value::test_int(4),
149                    Value::test_int(6),
150                ])),
151            },
152            Example {
153                example: "1..3 | enumerate | par-each {|p| update item ($p.item * 2)} | sort-by item | get item",
154                description: "Enumerate and sort-by can be used to reconstruct the original order.",
155                result: Some(Value::test_list(vec![
156                    Value::test_int(2),
157                    Value::test_int(4),
158                    Value::test_int(6),
159                ])),
160            },
161            Example {
162                example: "[foo bar baz] | par-each {|e| $e + '!' } | sort",
163                description: "Output can still be sorted afterward.",
164                result: Some(Value::test_list(vec![
165                    Value::test_string("bar!"),
166                    Value::test_string("baz!"),
167                    Value::test_string("foo!"),
168                ])),
169            },
170            Example {
171                example: r#"[1 2 3] | enumerate | par-each { |e| if $e.item == 2 { $"found 2 at ($e.index)!"} }"#,
172                description: "Iterate over each element, producing a list showing indexes of any 2s.",
173                result: Some(Value::test_list(vec![Value::test_string("found 2 at 1!")])),
174            },
175        ]
176    }
177
178    fn run(
179        &self,
180        engine_state: &EngineState,
181        stack: &mut Stack,
182        call: &Call,
183        input: PipelineData,
184    ) -> Result<PipelineData, ShellError> {
185        let head = call.head;
186        let closure: Closure = call.req(engine_state, stack, 0)?;
187        let threads: Option<usize> = call.get_flag(engine_state, stack, "threads")?;
188        let max_threads = threads.unwrap_or(0);
189        let keep_order = call.has_flag(engine_state, stack, "keep-order")?;
190        let signals = engine_state.signals().clone();
191
192        if matches!(&input, PipelineData::Value(Value::Custom { val, .. }, _) if val.type_name() == "matrix")
193        {
194            return Err(ShellError::Generic(
195                nu_protocol::shell_error::generic::GenericError::new(
196                    "Unsupported type",
197                    "Use `matrix map` for element-wise operations.",
198                    call.head,
199                ),
200            ));
201        }
202
203        let mut input = input.into_stream_or_original(engine_state);
204        let metadata = input.take_metadata();
205
206        // A helper function sorts the output if needed
207        let apply_order = |mut vec: Vec<(usize, Value)>| {
208            if keep_order {
209                // Runs under Rayon (dedicated pool via install).
210                // There are no identical indexes, so unstable sorting can be used.
211                vec.par_sort_unstable_by_key(|(index, _)| *index);
212            }
213
214            vec.into_iter().map(|(_, val)| val)
215        };
216
217        match input {
218            PipelineData::Empty => Ok(PipelineData::empty()),
219            PipelineData::Value(value, ..) => {
220                let span = value.span();
221                match value {
222                    Value::List { vals, .. } => {
223                        let pool = create_pool(max_threads, head)?;
224                        if keep_order {
225                            Ok(pool.install(|| {
226                                let par_iter = vals.into_owned().into_par_iter().enumerate();
227                                let mapped =
228                                    parallel_closure_map(engine_state, stack, &closure, par_iter);
229                                apply_order(mapped.collect())
230                                    .into_pipeline_data(span, signals.clone())
231                            }))
232                        } else {
233                            let par_iter = vals.into_owned().into_par_iter();
234                            Ok(stream_parallel_values(
235                                engine_state,
236                                stack,
237                                closure.clone(),
238                                pool,
239                                span,
240                                signals.clone(),
241                                par_iter,
242                            ))
243                        }
244                    }
245                    Value::Range { val, .. } => {
246                        let pool = create_pool(max_threads, head)?;
247                        if keep_order {
248                            Ok(pool.install(|| {
249                                let par_iter = val
250                                    .into_range_iter(span, signals.clone())
251                                    .enumerate()
252                                    .par_bridge();
253                                let mapped =
254                                    parallel_closure_map(engine_state, stack, &closure, par_iter);
255                                apply_order(mapped.collect())
256                                    .into_pipeline_data(span, signals.clone())
257                            }))
258                        } else {
259                            let par_iter = val.into_range_iter(span, signals.clone()).par_bridge();
260                            Ok(stream_parallel_values(
261                                engine_state,
262                                stack,
263                                closure.clone(),
264                                pool,
265                                span,
266                                signals.clone(),
267                                par_iter,
268                            ))
269                        }
270                    }
271                    // This match allows non-iterables to be accepted,
272                    // which is currently considered undesirable (Nov 2022).
273                    value => {
274                        ClosureEvalOnce::new(engine_state, stack, closure).run_with_value(value)
275                    }
276                }
277            }
278            PipelineData::ListStream(stream, ..) => {
279                let pool = create_pool(max_threads, head)?;
280                if keep_order {
281                    Ok(pool.install(|| {
282                        let par_iter = stream.into_iter().enumerate().par_bridge();
283                        let mapped = parallel_closure_map(engine_state, stack, &closure, par_iter);
284                        apply_order(mapped.collect()).into_pipeline_data(head, signals.clone())
285                    }))
286                } else {
287                    let par_iter = stream.into_iter().par_bridge();
288                    Ok(stream_parallel_values(
289                        engine_state,
290                        stack,
291                        closure.clone(),
292                        pool,
293                        head,
294                        signals.clone(),
295                        par_iter,
296                    ))
297                }
298            }
299            PipelineData::ByteStream(stream, ..) => {
300                if let Some(chunks) = stream.chunks() {
301                    let pool = create_pool(max_threads, head)?;
302                    if keep_order {
303                        Ok(pool.install(|| {
304                            let par_iter = chunks
305                                .enumerate()
306                                .map(move |(idx, val)| {
307                                    (idx, val.unwrap_or_else(|err| Value::error(err, head)))
308                                })
309                                .par_bridge();
310                            let mapped =
311                                parallel_closure_map(engine_state, stack, &closure, par_iter);
312                            apply_order(mapped.collect()).into_pipeline_data(head, signals.clone())
313                        }))
314                    } else {
315                        let par_iter = chunks
316                            .map(move |val| val.unwrap_or_else(|err| Value::error(err, head)))
317                            .par_bridge();
318                        Ok(stream_parallel_values(
319                            engine_state,
320                            stack,
321                            closure.clone(),
322                            pool,
323                            head,
324                            signals.clone(),
325                            par_iter,
326                        ))
327                    }
328                } else {
329                    Ok(PipelineData::empty())
330                }
331            }
332        }
333        .and_then(|x| x.filter(|v| !v.is_nothing(), engine_state.signals()))
334        .map(|data| data.set_metadata(metadata))
335    }
336}
337
338fn stream_parallel_values(
339    engine_state: &EngineState,
340    stack: &Stack,
341    closure: Closure,
342    pool: Arc<rayon::ThreadPool>,
343    span: Span,
344    signals: Signals,
345    input: impl ParallelIterator<Item = Value> + 'static,
346) -> PipelineData {
347    let (tx, rx) = mpsc::sync_channel(STREAM_BUFFER_SIZE);
348    let worker_engine_state = engine_state.clone();
349    // Only clone the captured variables, not the entire stack.
350    // This avoids deep-copying all in-scope variables that the closure does not reference.
351    let worker_stack = stack.captures_to_stack(closure.captures.clone());
352    let worker_signals = signals.clone();
353
354    // Spawn on the dedicated pool (not `rayon::spawn`, which always uses the global
355    // pool). ParallelIterator work then also runs on this pool because the task
356    // executes on one of its workers.
357    pool.spawn(move || {
358        let map_signals = worker_signals.clone();
359        let send_signals = worker_signals.clone();
360
361        let _ = input
362            .map_init(
363                move || ClosureEval::new(&worker_engine_state, &worker_stack, closure.clone()),
364                move |closure_eval, value| {
365                    if map_signals.interrupted() {
366                        return Err(());
367                    }
368
369                    let value = run_closure_on_value(closure_eval, value);
370
371                    if map_signals.interrupted() {
372                        Err(())
373                    } else {
374                        Ok(value)
375                    }
376                },
377            )
378            .try_for_each(move |value| match value {
379                Ok(value) => {
380                    if send_signals.interrupted() {
381                        Err(())
382                    } else {
383                        tx.send(value).map_err(|_| ())
384                    }
385                }
386                Err(()) => Err(()),
387            });
388    });
389
390    ReceiverIter::new(rx, signals).into_pipeline_data(span, Signals::empty())
391}
392
393// Polls channel reads so Ctrl+C can stop blocked receives promptly.
394struct ReceiverIter {
395    receiver: mpsc::Receiver<Value>,
396    signals: Signals,
397}
398
399impl ReceiverIter {
400    fn new(receiver: mpsc::Receiver<Value>, signals: Signals) -> Self {
401        Self { receiver, signals }
402    }
403}
404
405impl Iterator for ReceiverIter {
406    type Item = Value;
407
408    fn next(&mut self) -> Option<Self::Item> {
409        loop {
410            if self.signals.interrupted() {
411                return None;
412            }
413
414            match self.receiver.recv_timeout(CTRL_C_CHECK_INTERVAL) {
415                Ok(value) => return Some(value),
416                Err(RecvTimeoutError::Timeout) => {}
417                Err(RecvTimeoutError::Disconnected) => return None,
418            }
419        }
420    }
421}
422
423fn run_closure_on_value(closure_eval: &mut ClosureEval, value: Value) -> Value {
424    let span = value.span();
425    let is_error = value.is_error();
426
427    closure_eval
428        .run_with_value(value)
429        .and_then(|data| data.into_value(span))
430        .unwrap_or_else(|err| Value::error(chain_error_with_input(err, is_error, span), span))
431}
432
433fn parallel_closure_map(
434    engine_state: &EngineState,
435    stack: &mut Stack,
436    closure: &Closure,
437    input: impl ParallelIterator<Item = (usize, Value)>,
438) -> impl ParallelIterator<Item = (usize, Value)> {
439    input.map_init(
440        move || ClosureEval::new(engine_state, stack, closure.clone()),
441        |closure_eval, (index, value)| {
442            let value = run_closure_on_value(closure_eval, value);
443
444            (index, value)
445        },
446    )
447}
448
449#[cfg(test)]
450mod test {
451    use super::*;
452
453    #[test]
454    fn test_examples() -> nu_test_support::Result {
455        nu_test_support::test().examples(ParEach)
456    }
457}