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

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

par.rs215 lines · 8.0 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(
43 OVERRIDE.load(Ordering::Relaxed),
44 std::env::var("MAPS_THREADS").ok().as_deref(),
45 )
46}
47
48/// The precedence rule, split out so it can be tested without mutating the
49/// process-wide override or the environment.
50fn resolve(override_n: usize, env: Option<&str>) -> usize {
51 if override_n > 0 {
52 return override_n;
53 }
54 if let Some(n) = env_threads(env) {
55 return n;
56 }
57 std::thread::available_parallelism()
58 .map(|n| n.get())
59 .unwrap_or(4)
60}
61
62/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it
63/// is usually exported once for a whole script run, and killing an eight-hour
64/// planet build over a typo in an environment variable serves nobody. Warned
65/// about once, because `threads()` is called once per parallel stage.
66fn env_threads(raw: Option<&str>) -> Option<usize> {
67 static WARNED: std::sync::Once = std::sync::Once::new();
68 let trimmed = raw?.trim();
69 match trimmed.parse::<usize>() {
70 Ok(n) if n > 0 => Some(n),
71 _ => {
72 WARNED.call_once(|| {
73 eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");
74 });
75 None
76 }
77 }
78}
79
80/// Parse a `--threads N` value. Shared by all three binaries so they reject the
81/// same things with the same message.
82pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {
83 value
84 .parse::<usize>()
85 .ok()
86 .filter(|n| *n > 0)
87 .ok_or_else(|| format!("--threads wants a positive count, not {value}"))
88}
89
90/// Our own rayon pool rather than the global one, so the cap above governs it.
91///
92/// Cached, and rebuilt only when the requested count changes. In production that
93/// happens once, because `--threads` is read before any work starts; the reason it
94/// is not a `OnceLock` is that the byte-identity tests build the same graph at
95/// several thread counts in one process, and a pool fixed on first use would make
96/// those tests assert nothing.
97///
98/// `map_chunks` above does not use this — it owns its own scoped threads and its
99/// own ordered merge. This is for the phases that are a plain sort or map, where
100/// rayon's work stealing is worth more than a hand-rolled split.
101fn pool() -> Arc<rayon::ThreadPool> {
102 static POOL: Mutex<Option<(usize, Arc<rayon::ThreadPool>)>> = Mutex::new(None);
103 let want = threads();
104 let mut cached = POOL.lock().expect("thread pool mutex");
105 if let Some((have, p)) = cached.as_ref() {
106 if *have == want {
107 return Arc::clone(p);
108 }
109 }
110 let built = Arc::new(build_pool(want).unwrap_or_else(|e| {
111 eprintln!("WARN: cannot start a {want}-thread pool ({e}); continuing on one thread");
112 build_pool(1).expect("a one-thread pool")
113 }));
114 *cached = Some((want, Arc::clone(&built)));
115 built
116}
117
118fn build_pool(n: usize) -> std::result::Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {
119 rayon::ThreadPoolBuilder::new()
120 .num_threads(n)
121 // As big as the main thread's, because that is where this work used to run.
122 // rayon workers otherwise get std's 2 MiB default, so parallelising a deep
123 // call path silently shrinks its stack by 4x.
124 .stack_size(8 * 1024 * 1024)
125 .thread_name(|i| format!("osm_ingest-{i}"))
126 .build()
127}
128
129/// Run `f` on the pool, so it sees our thread cap rather than rayon's global one.
130pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R {
131 pool().install(f)
132}
133
134/// Apply `f(chunk_start, chunk)` to every chunk of `chunk_len` items, returning
135/// the results in chunk order.
136pub fn map_chunks<T, R, F>(items: &[T], chunk_len: usize, f: F) -> Vec<R>
137where
138 T: Sync,
139 R: Send,
140 F: Fn(usize, &[T]) -> R + Sync,
141{
142 let chunk_len = chunk_len.max(1);
143 let n_chunks = items.len().div_ceil(chunk_len);
144 if n_chunks == 0 {
145 return Vec::new();
146 }
147 let slots: Mutex<Vec<Option<R>>> = Mutex::new((0..n_chunks).map(|_| None).collect());
148 let next = AtomicUsize::new(0);
149 let n_threads = threads().min(n_chunks);
150
151 std::thread::scope(|scope| {
152 for _ in 0..n_threads {
153 scope.spawn(|| loop {
154 let chunk = next.fetch_add(1, Ordering::Relaxed);
155 if chunk >= n_chunks {
156 break;
157 }
158 let start = chunk * chunk_len;
159 let end = ((chunk + 1) * chunk_len).min(items.len());
160 let result = f(start, &items[start..end]);
161 slots.lock().expect("chunk slot mutex")[chunk] = Some(result);
162 });
163 }
164 });
165
166 slots
167 .into_inner()
168 .expect("chunk slot mutex")
169 .into_iter()
170 .flatten()
171 .collect()
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[test]
179 fn results_come_back_in_chunk_order() {
180 let items: Vec<usize> = (0..1000).collect();
181 let out = map_chunks(&items, 7, |start, chunk| (start, chunk.iter().sum::<usize>()));
182 assert_eq!(out.len(), 1000usize.div_ceil(7));
183 assert!(out.windows(2).all(|w| w[0].0 < w[1].0));
184 assert_eq!(out.iter().map(|c| c.1).sum::<usize>(), items.iter().sum());
185 }
186
187 #[test]
188 fn parse_threads_rejects_zero_and_junk() {
189 assert_eq!(parse_threads("8"), Ok(8));
190 assert!(parse_threads("0").is_err());
191 assert!(parse_threads("-1").is_err());
192 assert!(parse_threads("many").is_err());
193 assert!(parse_threads("").is_err());
194 }
195
196 #[test]
197 fn the_flag_beats_the_env_beats_the_box() {
198 let box_threads = resolve(0, None);
199 assert_eq!(resolve(6, Some("2")), 6, "--threads wins");
200 assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");
201 assert_eq!(resolve(6, None), 6);
202 // Junk in the environment falls back to the box rather than failing, so a
203 // typo cannot silently serialise a long build.
204 for junk in ["0", "many", "", "-4"] {
205 assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");
206 }
207 assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");
208 }
209
210 #[test]
211 fn empty_input_produces_no_chunks() {
212 let out = map_chunks::<usize, usize, _>(&[], 8, |_, _| unreachable!());
213 assert!(out.is_empty());
214 }
215}