Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
main ▾

Modern-Apps.git / scripts / maps / osm_ingest / src / par.rs

par.rs254 lines · 9.7 KiBRaw
1//! Deterministic parallel map over contiguous chunks of a slice.
2//!
3//! Chunks are claimed dynamically (so a heavy chunk doesn't stall a core) but
4//! each chunk's result is stored at its own index, so merging the results in
5//! index order gives output that does not depend on thread scheduling. Every
6//! parallel stage in this crate is built on that property — it is what makes the
7//! tool reproducible, which the C++ generator it replaces was not.
8//!
9//! The pool size is capped by [`set_threads`] (`--threads`) or `MAPS_THREADS`,
10//! because the build scripts run several of these tools concurrently and an
11//! uncapped pool oversubscribes the box once they do.
12
13use std::sync::atomic::{AtomicUsize, Ordering};
14use std::sync::{Arc, Mutex};
15
16/// 0 means "not set"; any other value is an explicit cap from `--threads`.
17static OVERRIDE: AtomicUsize = AtomicUsize::new(0);
18
19/// Cap the pool for the rest of the process. Called once from `main` after
20/// argument parsing.
21///
22/// This exists because the build scripts fan out several of these tools at once.
23/// `available_parallelism()` reports the whole box to every one of them, so six
24/// concurrent layer builds would each claim 32 threads on a 32-core machine and
25/// finish slower than running in sequence. The cap has to be settable from
26/// outside the process, hence this and `MAPS_THREADS`.
27pub fn set_threads(n: usize) {
28 OVERRIDE.store(n.max(1), Ordering::Relaxed);
29}
30
31/// Drop the override again, so a test can leave the process as it found it.
32#[cfg(test)]
33pub fn clear_threads() {
34 OVERRIDE.store(0, Ordering::Relaxed);
35}
36
37/// Threads to use for one parallel stage.
38///
39/// `--threads` beats `MAPS_THREADS` beats the box. A single-process run sets
40/// neither and is therefore unchanged.
41pub fn threads() -> usize {
42 resolve(OVERRIDE.load(Ordering::Relaxed), std::env::var("MAPS_THREADS").ok().as_deref())
43}
44
45/// The precedence rule, split out so it can be tested without mutating the
46/// process-wide override or the environment.
47fn resolve(override_n: usize, env: Option<&str>) -> usize {
48 if override_n > 0 {
49 return override_n;
50 }
51 if let Some(n) = env_threads(env) {
52 return n;
53 }
54 std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4)
55}
56
57/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it
58/// is usually exported once for a whole script run, and killing an eight-hour
59/// planet build over a typo in an environment variable serves nobody. Warned
60/// about once, because `threads()` is called once per parallel stage.
61fn env_threads(raw: Option<&str>) -> Option<usize> {
62 static WARNED: std::sync::Once = std::sync::Once::new();
63 let trimmed = raw?.trim();
64 match trimmed.parse::<usize>() {
65 Ok(n) if n > 0 => Some(n),
66 _ => {
67 WARNED.call_once(|| {
68 eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");
69 });
70 None
71 }
72 }
73}
74
75/// Parse a `--threads N` value. Shared by all three binaries so they reject the
76/// same things with the same message.
77pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {
78 value
79 .parse::<usize>()
80 .ok()
81 .filter(|n| *n > 0)
82 .ok_or_else(|| format!("--threads wants a positive count, not {value}"))
83}
84
85/// Our own rayon pool rather than the global one, so the cap above governs it.
86///
87/// Cached, and rebuilt only when the requested count changes. In production that
88/// happens once, because `--threads` is read before any work starts; the reason it
89/// is not a `OnceLock` is that the byte-identity tests build the same graph at
90/// several thread counts in one process, and a pool fixed on first use would make
91/// those tests assert nothing.
92///
93/// `map_chunks` above does not use this — it owns its own scoped threads and its
94/// own ordered merge. This is for the phases that are a plain sort or map, where
95/// rayon's work stealing is worth more than a hand-rolled split.
96fn pool() -> Arc<rayon::ThreadPool> {
97 static POOL: Mutex<Option<(usize, Arc<rayon::ThreadPool>)>> = Mutex::new(None);
98 let want = threads();
99 let mut cached = POOL.lock().expect("thread pool mutex");
100 if let Some((have, p)) = cached.as_ref() {
101 if *have == want {
102 return Arc::clone(p);
103 }
104 }
105 let built = Arc::new(build_pool(want).unwrap_or_else(|e| {
106 eprintln!("WARN: cannot start a {want}-thread pool ({e}); continuing on one thread");
107 build_pool(1).expect("a one-thread pool")
108 }));
109 *cached = Some((want, Arc::clone(&built)));
110 built
111}
112
113fn build_pool(n: usize) -> std::result::Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {
114 rayon::ThreadPoolBuilder::new()
115 .num_threads(n)
116 // As big as the main thread's, because that is where this work used to run.
117 // rayon workers otherwise get std's 2 MiB default, so parallelising a deep
118 // call path silently shrinks its stack by 4x.
119 .stack_size(8 * 1024 * 1024)
120 .thread_name(|i| format!("osm_ingest-{i}"))
121 .build()
122}
123
124/// Run `f` on the pool, so it sees our thread cap rather than rayon's global one.
125pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R {
126 pool().install(f)
127}
128
129/// Run `f` asynchronously on the pool (fire and forget; report back through a
130/// channel). For pipelining work behind a serial stage.
131pub fn spawn(f: impl FnOnce() + Send + 'static) {
132 pool().spawn(f)
133}
134
135/// Apply `f(chunk_start, chunk)` to every chunk of `chunk_len` items, returning
136/// the results in chunk order.
137pub fn map_chunks<T, R, F>(items: &[T], chunk_len: usize, f: F) -> Vec<R>
138where
139 T: Sync,
140 R: Send,
141 F: Fn(usize, &[T]) -> R + Sync,
142{
143 let chunk_len = chunk_len.max(1);
144 let n_chunks = items.len().div_ceil(chunk_len);
145 if n_chunks == 0 {
146 return Vec::new();
147 }
148 let slots: Mutex<Vec<Option<R>>> = Mutex::new((0..n_chunks).map(|_| None).collect());
149 let next = AtomicUsize::new(0);
150 let n_threads = threads().min(n_chunks);
151
152 std::thread::scope(|scope| {
153 for _ in 0..n_threads {
154 scope.spawn(|| loop {
155 let chunk = next.fetch_add(1, Ordering::Relaxed);
156 if chunk >= n_chunks {
157 break;
158 }
159 let start = chunk * chunk_len;
160 let end = ((chunk + 1) * chunk_len).min(items.len());
161 let result = f(start, &items[start..end]);
162 slots.lock().expect("chunk slot mutex")[chunk] = Some(result);
163 });
164 }
165 });
166
167 slots.into_inner().expect("chunk slot mutex").into_iter().flatten().collect()
168}
169
170/// Apply `f(lo..hi)` to every fixed `chunk_len`-sized range of `0..n`,
171/// returning the results in range order. [`map_chunks`] over indices without
172/// materialising them: the deterministic shape for loops over billions of ids.
173pub fn map_ranges<R, F>(n: usize, chunk_len: usize, f: F) -> Vec<R>
174where
175 R: Send,
176 F: Fn(std::ops::Range<usize>) -> R + Sync,
177{
178 let chunk_len = chunk_len.max(1);
179 let starts: Vec<usize> = (0..n.div_ceil(chunk_len)).map(|c| c * chunk_len).collect();
180 map_chunks(&starts, 1, |_, s| f(s[0]..(s[0] + chunk_len).min(n)))
181}
182
183/// A raw pointer that may be shared across the pool, for scatters whose
184/// targets are provably distinct (a permutation, or slots claimed by an atomic
185/// cursor). Every use states why its writes cannot collide.
186#[derive(Clone, Copy)]
187pub struct SyncPtr<T>(pub *mut T);
188// SAFETY: only ever dereferenced at indices the caller has proven disjoint.
189unsafe impl<T: Send> Send for SyncPtr<T> {}
190unsafe impl<T: Send> Sync for SyncPtr<T> {}
191
192impl<T> SyncPtr<T> {
193 /// Write `v` at `i`.
194 ///
195 /// # Safety
196 /// `i` is in bounds of the allocation and no other thread reads or writes
197 /// index `i` concurrently.
198 #[inline]
199 pub unsafe fn write(self, i: usize, v: T) {
200 unsafe { self.0.add(i).write(v) }
201 }
202}
203
204#[cfg(test)]
205mod tests {
206 use super::*;
207
208 #[test]
209 fn results_come_back_in_chunk_order() {
210 let items: Vec<usize> = (0..1000).collect();
211 let out = map_chunks(&items, 7, |start, chunk| (start, chunk.iter().sum::<usize>()));
212 assert_eq!(out.len(), 1000usize.div_ceil(7));
213 assert!(out.windows(2).all(|w| w[0].0 < w[1].0));
214 assert_eq!(out.iter().map(|c| c.1).sum::<usize>(), items.iter().sum());
215 }
216
217 #[test]
218 fn parse_threads_rejects_zero_and_junk() {
219 assert_eq!(parse_threads("8"), Ok(8));
220 assert!(parse_threads("0").is_err());
221 assert!(parse_threads("-1").is_err());
222 assert!(parse_threads("many").is_err());
223 assert!(parse_threads("").is_err());
224 }
225
226 #[test]
227 fn the_flag_beats_the_env_beats_the_box() {
228 let box_threads = resolve(0, None);
229 assert_eq!(resolve(6, Some("2")), 6, "--threads wins");
230 assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");
231 assert_eq!(resolve(6, None), 6);
232 // Junk in the environment falls back to the box rather than failing, so a
233 // typo cannot silently serialise a long build.
234 for junk in ["0", "many", "", "-4"] {
235 assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");
236 }
237 assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");
238 }
239
240 #[test]
241 fn ranges_cover_everything_once_in_order() {
242 let out = map_ranges(1001, 64, |r| (r.start, r.end));
243 assert_eq!(out.first(), Some(&(0, 64)));
244 assert_eq!(out.last(), Some(&(960, 1001)));
245 assert!(out.windows(2).all(|w| w[0].1 == w[1].0));
246 assert!(map_ranges(0, 8, |r| r).is_empty());
247 }
248
249 #[test]
250 fn empty_input_produces_no_chunks() {
251 let out = map_chunks::<usize, usize, _>(&[], 8, |_, _| unreachable!());
252 assert!(out.is_empty());
253 }
254}