Skip to main content

ncp_engine/
worker.rs

1use std::cell::UnsafeCell;
2use std::sync::Arc;
3use std::sync::atomic::{self, AtomicBool};
4
5use ncp_matcher::Config;
6use parking_lot::Mutex;
7use rayon::{ThreadPool, prelude::*};
8
9use crate::par_sort::par_quicksort;
10use crate::pattern::{self, MultiPattern};
11use crate::{Match, boxcar};
12
13/// Configuration which influences the match list.
14pub struct MatchListConfig {
15    /// Whether the matcher should sort results by score after matching.
16    pub sort_results: bool,
17    /// Whether the matcher should reverse the order of the input.
18    pub reverse_items: bool,
19}
20
21impl Default for MatchListConfig {
22    fn default() -> Self {
23        Self::DEFAULT
24    }
25}
26
27impl MatchListConfig {
28    /// The default value, implemented as a constant since the Default trait is not const.
29    pub const DEFAULT: Self = Self {
30        sort_results: true,
31        reverse_items: false,
32    };
33}
34
35struct Matchers(Box<[UnsafeCell<ncp_matcher::Matcher>]>);
36
37impl Matchers {
38    // this is not a true mut from ref, we use a cell here
39    #[allow(clippy::mut_from_ref)]
40    unsafe fn get(&self) -> &mut ncp_matcher::Matcher {
41        unsafe { &mut *self.0[rayon::current_thread_index().unwrap()].get() }
42    }
43}
44
45unsafe impl Sync for Matchers {}
46unsafe impl Send for Matchers {}
47
48pub(crate) struct Worker<T> {
49    pub(crate) running: bool,
50    matchers: Matchers,
51    pub(crate) matches: Vec<Match>,
52    pub(crate) pattern: MultiPattern,
53    pub(crate) sort_results: bool,
54    pub(crate) reverse_items: bool,
55    pub(crate) needs_rescore: bool,
56    pub(crate) needs_sort: bool,
57    pub(crate) canceled: Arc<AtomicBool>,
58    pub(crate) was_canceled: bool,
59    pub(crate) last_snapshot: u32,
60    pub(crate) items: Arc<boxcar::Vec<T>>,
61    in_flight: Vec<u32>,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
65pub(crate) enum RunOutcome {
66    Completed,
67    Canceled,
68}
69
70impl<T: Sync + Send + 'static> Worker<T> {
71    pub(crate) fn item_count(&self) -> u32 {
72        self.last_snapshot - self.in_flight.len() as u32
73    }
74    pub(crate) fn update_config(&mut self, config: Config) {
75        for matcher in self.matchers.0.iter_mut() {
76            matcher.get_mut().config = config.clone();
77        }
78        self.needs_rescore = true;
79    }
80    pub(crate) fn sort_results(&mut self, sort_results: bool) {
81        if self.sort_results != sort_results {
82            self.sort_results = sort_results;
83            self.needs_sort = true;
84        }
85    }
86    pub(crate) fn reverse_items(&mut self, reverse_items: bool) {
87        if self.reverse_items != reverse_items {
88            self.reverse_items = reverse_items;
89            self.needs_sort = true;
90        }
91    }
92
93    pub(crate) fn new(
94        worker_threads: Option<usize>,
95        config: Config,
96        cols: u32,
97        match_config: MatchListConfig,
98    ) -> (ThreadPool, Self) {
99        let worker_threads = worker_threads.unwrap_or_else(|| {
100            std::thread::available_parallelism().map_or(4, std::num::NonZero::get)
101        });
102        let pool = rayon::ThreadPoolBuilder::new()
103            .thread_name(|i| format!("nucleo worker {i}"))
104            .num_threads(worker_threads)
105            .build()
106            .expect("creating threadpool failed");
107        let matchers = (0..worker_threads)
108            .map(|_| UnsafeCell::new(ncp_matcher::Matcher::new(config.clone())))
109            .collect();
110        let worker = Self {
111            running: false,
112            matchers: Matchers(matchers),
113            last_snapshot: 0,
114            matches: Vec::new(),
115            // just a placeholder
116            pattern: MultiPattern::new(cols as usize),
117            sort_results: match_config.sort_results,
118            reverse_items: match_config.reverse_items,
119            needs_rescore: false,
120            needs_sort: false,
121            canceled: Arc::new(AtomicBool::new(false)),
122            was_canceled: false,
123            items: Arc::new(boxcar::Vec::with_capacity(2 * 1024, cols)),
124            in_flight: Vec::with_capacity(64),
125        };
126        (pool, worker)
127    }
128
129    unsafe fn process_new_items(&mut self) -> usize {
130        unsafe {
131            let matchers = &self.matchers;
132            let pattern = &self.pattern;
133            self.matches.reserve(self.in_flight.len());
134            self.in_flight.retain(|&idx| {
135                let Some(item) = self.items.get(idx) else {
136                    return true;
137                };
138                if let Some(score) = pattern.score(item.matcher_columns, matchers.get()) {
139                    self.matches.push(Match { score, idx });
140                };
141                false
142            });
143            let new_snapshot = self.items.par_snapshot(self.last_snapshot);
144            if new_snapshot.end() == self.last_snapshot {
145                return 0;
146            }
147            let end = new_snapshot.end();
148            let start = self.matches.len();
149            let len = new_snapshot.len();
150            self.matches.reserve(len);
151            let in_flight = Mutex::new(&mut self.in_flight);
152            let items = new_snapshot.map(|(idx, item)| {
153                let Some(item) = item else {
154                    in_flight.lock().push(idx);
155                    return Match {
156                        score: 0,
157                        idx: u32::MAX,
158                    };
159                };
160                if self.canceled.load(atomic::Ordering::Relaxed) {
161                    // Retain unprocessed indices for the next query update.
162                    return Match { score: 0, idx };
163                }
164                let Some(score) = pattern.score(item.matcher_columns, matchers.get()) else {
165                    return Match {
166                        score: 0,
167                        idx: u32::MAX,
168                    };
169                };
170                Match { score, idx }
171            });
172            // Initialize disjoint output slots once while reducing local counts.
173            let unmatched = items
174                .zip_eq(self.matches.spare_capacity_mut()[..len].par_iter_mut())
175                .map(|(match_, slot)| {
176                    slot.write(match_);
177                    usize::from(match_.idx == u32::MAX)
178                })
179                .sum::<usize>();
180            // SAFETY: The indexed zip writes every one of the `len` reserved
181            // slots, even after cancellation. The reduction joins all writers
182            // before exposing those entries. A panic leaves the length unchanged.
183            self.matches.set_len(start + len);
184            self.last_snapshot = end;
185            unmatched
186        }
187    }
188
189    fn remove_in_flight_matches(&mut self) {
190        // in-flight indices are collected by parallel workers, so insertion
191        // order is not deterministic
192        self.in_flight.sort_unstable();
193        self.in_flight.retain(|&i| self.items.get(i).is_none());
194
195        let mut in_flight = self.in_flight.iter().copied().peekable();
196        self.matches.retain(|match_| {
197            if in_flight.peek().copied() == Some(match_.idx) {
198                in_flight.next();
199                false
200            } else {
201                true
202            }
203        });
204    }
205
206    unsafe fn process_new_items_trivial(&mut self) {
207        unsafe {
208            let new_snapshot = self.items.snapshot(self.last_snapshot);
209            if new_snapshot.end() != self.last_snapshot {
210                let end = new_snapshot.end();
211                let items = new_snapshot.filter_map(|(idx, item)| {
212                    if item.is_none() {
213                        self.in_flight.push(idx);
214                        return None;
215                    };
216                    Some(Match { score: 0, idx })
217                });
218                self.matches.extend(items);
219                self.last_snapshot = end;
220            }
221        }
222    }
223
224    pub(crate) unsafe fn run(
225        &mut self,
226        pattern_status: pattern::Status,
227        cleared: bool,
228    ) -> RunOutcome {
229        unsafe {
230            self.running = true;
231            self.was_canceled = false;
232
233            if cleared {
234                self.last_snapshot = 0;
235                self.in_flight.clear();
236                self.matches.clear();
237            }
238
239            // TODO: be smarter around reusing past results for rescoring
240            if self.pattern.is_empty() {
241                self.reset_matches();
242                self.process_new_items_trivial();
243                if self.reverse_items {
244                    self.matches.reverse();
245                }
246                return RunOutcome::Completed;
247            }
248
249            if pattern_status == pattern::Status::Rescore {
250                self.reset_matches();
251            }
252
253            let unmatched = if pattern_status != pattern::Status::Unchanged
254                && !self.matches.is_empty()
255            {
256                self.process_new_items_trivial();
257                let matchers = &self.matchers;
258                let pattern = &self.pattern;
259                self.matches
260                    .par_iter_mut()
261                    .take_any_while(|_| !self.canceled.load(atomic::Ordering::Relaxed))
262                    .map(|match_| {
263                        if match_.idx == u32::MAX {
264                            debug_assert_eq!(match_.score, 0);
265                            return 1;
266                        }
267                        // safety: in-flight items are never added to the matches
268                        let item = self.items.get_unchecked(match_.idx);
269                        if let Some(score) = pattern.score(item.matcher_columns, matchers.get()) {
270                            match_.score = score;
271                            0
272                        } else {
273                            match_.score = 0;
274                            match_.idx = u32::MAX;
275                            1
276                        }
277                    })
278                    .sum::<usize>()
279            } else {
280                self.process_new_items()
281            };
282
283            let canceled = self.sort_matches();
284            if canceled {
285                self.was_canceled = true;
286                RunOutcome::Canceled
287            } else {
288                self.matches.truncate(self.matches.len() - unmatched);
289                RunOutcome::Completed
290            }
291        }
292    }
293
294    unsafe fn sort_matches(&mut self) -> bool {
295        unsafe {
296            if self.sort_results {
297                par_quicksort(
298                    &mut self.matches,
299                    |match1, match2| {
300                        if match1.score != match2.score {
301                            return match1.score > match2.score;
302                        }
303                        if match1.idx == u32::MAX {
304                            return false;
305                        }
306                        if match2.idx == u32::MAX {
307                            return true;
308                        }
309                        // the tie breaker is comparatively rarely needed so we keep it
310                        // in a branch especially because we need to access the items
311                        // array here which involves some pointer chasing
312                        let item1 = self.items.get_unchecked(match1.idx);
313                        let item2 = &self.items.get_unchecked(match2.idx);
314                        let len1: u32 = item1
315                            .matcher_columns
316                            .iter()
317                            .map(|haystack| haystack.len() as u32)
318                            .sum();
319                        let len2 = item2
320                            .matcher_columns
321                            .iter()
322                            .map(|haystack| haystack.len() as u32)
323                            .sum();
324                        if len1 == len2 {
325                            if self.reverse_items {
326                                match2.idx < match1.idx
327                            } else {
328                                match1.idx < match2.idx
329                            }
330                        } else {
331                            len1 < len2
332                        }
333                    },
334                    &self.canceled,
335                )
336            } else {
337                par_quicksort(
338                    &mut self.matches,
339                    |match1, match2| {
340                        if match1.idx == u32::MAX {
341                            return false;
342                        }
343                        if match2.idx == u32::MAX {
344                            return true;
345                        }
346                        if self.reverse_items {
347                            match2.idx < match1.idx
348                        } else {
349                            match1.idx < match2.idx
350                        }
351                    },
352                    &self.canceled,
353                )
354            }
355        }
356    }
357
358    fn reset_matches(&mut self) {
359        self.matches.clear();
360        self.matches
361            .extend((0..self.last_snapshot).map(|idx| Match { score: 0, idx }));
362        // there are usually only very few in flight items (one for each writer)
363        self.remove_in_flight_matches();
364    }
365}