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

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

par.rs251 lines · 11.0 KiBRaw
1//! The thread budget, and the pool every parallel stage in this crate runs on.
2//!
3//! Sized the same way `osm_ingest::par` sizes its pool, and deliberately so: the
4//! build scripts fan out several of these tools at once, and
5//! `available_parallelism()` reports the whole box to every one of them. Six
6//! concurrent layer builds each claiming 32 threads on a 32-core machine finish
7//! slower than running in sequence, so the cap has to be settable from outside
8//! the process. Hence `--threads` and `MAPS_THREADS`, spelled identically in both
9//! crates so one `MAPS_THREADS` export governs a whole build.
10//!
11//! Parallelism here never changes an output byte. Every stage either collects
12//! results into a slot indexed by input position, or writes them in a
13//! sequentially-folded second pass; see [`crate::pyramid::build_archive_to`].
14
15use std::sync::atomic::{AtomicUsize, Ordering};
16use std::sync::{Arc, Mutex};
17
18/// 0 means "not set"; any other value is an explicit cap from `--threads`.
19static OVERRIDE: AtomicUsize = AtomicUsize::new(0);
20
21/// Cap the pool for the rest of the process. Called from `main` after argument
22/// parsing.
23pub fn set_threads(n: usize) {
24 OVERRIDE.store(n.max(1), Ordering::Relaxed);
25}
26
27/// Drop the override again, so a test can leave the process as it found it.
28#[cfg(test)]
29pub fn clear_threads() {
30 OVERRIDE.store(0, Ordering::Relaxed);
31}
32
33/// Threads to use. `--threads` beats `MAPS_THREADS` beats the box.
34pub fn threads() -> usize {
35 resolve(
36 OVERRIDE.load(Ordering::Relaxed),
37 std::env::var("MAPS_THREADS").ok().as_deref(),
38 )
39}
40
41/// The precedence rule, split out so it can be tested without mutating the
42/// process-wide override or the environment.
43fn resolve(override_n: usize, env: Option<&str>) -> usize {
44 if override_n > 0 {
45 return override_n;
46 }
47 if let Some(n) = env_threads(env) {
48 return n;
49 }
50 std::thread::available_parallelism()
51 .map(|n| n.get())
52 .unwrap_or(4)
53}
54
55/// The most workers a phase that dislikes them should use — **not currently applied**.
56///
57/// Left as a documented dead end rather than deleted, because the measurement is real and the next
58/// person to look at thread counts should start from it rather than repeat it.
59///
60/// Tiling one us-west z13 archive four times from the same feature spill, back to back in one command
61/// so the machine state is shared, on a 64-thread box:
62///
63/// | threads | map | merge | encode | append |
64/// |---------|------|-------|--------|--------|
65/// | 64 | 87.5 | 9.4 | 42.0 | 5.2 |
66/// | 32 | 80.1 | 6.6 | 26.3 | 2.6 |
67/// | 16 | 76.5 | 5.4 | 29.0 | 2.0 |
68/// | 8 | 74.7 | 4.4 | 29.3 | 1.5 |
69///
70/// Encode looks 37% faster at 32 than at 64, every phase looks better with fewer workers, and all four
71/// archives were byte-identical.
72///
73/// # Why it is not applied
74///
75/// Neither a global cap nor an encode-only pool survived a full z14 build. This box produced 610.1,
76/// 631.0, 563.4 and 786.0 second us-west z14 builds that all wrote the **same archive bytes** — ±20%
77/// of wall clock, several times the effect being chased, because other work shares the machine. The
78/// z13 table above is internally consistent only because its four runs were consecutive; comparing it
79/// against a z14 run measured an hour later compares machine load, not code.
80///
81/// Validating this needs an A/B where both arms run back to back on an otherwise idle box, ideally
82/// interleaved and repeated. `--threads` and `MAPS_THREADS` are how to do that; see also
83/// [`min_task_len`], which documents the same anti-scaling from the scheduling side and *is* applied,
84/// because a synthetic benchmark could isolate it.
85#[allow(dead_code)]
86const NARROW_THREADS_UNVALIDATED: usize = 32;
87
88/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it is
89/// usually exported once for a whole script run, and killing an eight-hour planet
90/// build over a typo in an environment variable serves nobody.
91fn env_threads(raw: Option<&str>) -> Option<usize> {
92 static WARNED: std::sync::Once = std::sync::Once::new();
93 let trimmed = raw?.trim();
94 match trimmed.parse::<usize>() {
95 Ok(n) if n > 0 => Some(n),
96 _ => {
97 WARNED.call_once(|| {
98 eprintln!("WARN: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");
99 });
100 None
101 }
102 }
103}
104
105/// Parse a `--threads N` value.
106pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {
107 value
108 .parse::<usize>()
109 .ok()
110 .filter(|n| *n > 0)
111 .ok_or_else(|| format!("--threads wants a positive count, not {value}"))
112}
113
114/// Our own pool rather than rayon's global one, so the cap applies even when
115/// something else in the process has already initialised the global.
116///
117/// Cached, and rebuilt only when the requested count changes. In production that
118/// happens once, because `--threads` is read before any tiling starts; the reason
119/// it is not a `OnceLock` is that the byte-identity tests build the same archive at
120/// 1, 2, 3 and 32 threads in one process, and a pool fixed on first use would make
121/// that test assert nothing.
122///
123/// If rayon refuses to build a pool — which in practice means the OS would not give
124/// us threads — fall back to a single-threaded one rather than failing the build:
125/// every caller is a `map` whose serial execution is correct, just slower.
126fn pool() -> Arc<rayon::ThreadPool> {
127 static POOL: Mutex<Option<(usize, Arc<rayon::ThreadPool>)>> = Mutex::new(None);
128 let want = threads();
129 let mut cached = POOL.lock().expect("thread pool mutex");
130 if let Some((have, p)) = cached.as_ref() {
131 if *have == want {
132 return Arc::clone(p);
133 }
134 }
135 let built = Arc::new(build_pool(want).unwrap_or_else(|e| {
136 eprintln!("WARN: cannot start a {want}-thread pool ({e}); continuing on one thread");
137 build_pool(1).expect("a one-thread pool")
138 }));
139 *cached = Some((want, Arc::clone(&built)));
140 built
141}
142
143fn build_pool(n: usize) -> std::result::Result<rayon::ThreadPool, rayon::ThreadPoolBuildError> {
144 rayon::ThreadPoolBuilder::new()
145 .num_threads(n)
146 // As big as the main thread's, because that is where this work used to run.
147 // rayon workers otherwise get std's 2 MiB default, so parallelising a deep
148 // call path silently shrinks its stack by 4x -- and the failure mode is an
149 // abort partway through a planet build, not an error. 8 MiB matches what the
150 // Rust toolchain gives `main` on Windows.
151 .stack_size(8 * 1024 * 1024)
152 .thread_name(|i| format!("tile_build-{i}"))
153 .build()
154}
155
156/// Run `f` on the pool, so it sees our thread cap rather than rayon's global one.
157pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R {
158 pool().install(f)
159}
160
161/// How many items to hand the pool at once.
162///
163/// The tilers map over items whose results are held until the batch is written, so
164/// the batch size is what bounds that memory. It has to be large enough to keep
165/// every core fed — a batch of `threads` items means one task each and a barrier
166/// after every one — while still holding only a bounded number of results. Encoded
167/// tile bodies and spill records are kilobytes each, so a few thousand is a few MB:
168/// measured peak RSS moves by ~12% between 1 and 32 threads, not by 32x.
169pub fn batch_len() -> usize {
170 threads().saturating_mul(64).max(512)
171}
172
173/// The smallest number of items worth handing one worker, for a map of `items`.
174///
175/// One tile's encode is tens of microseconds. Handed to rayon one at a time, the
176/// work-stealing and spinning cost more than the work: measured on 200k synthetic
177/// roads at z14, the encode pass went 4.15s at one thread to 1.81s at four and then
178/// back UP to 3.51s at 32, purely on scheduling overhead. Batching several items into
179/// each task amortises that away.
180///
181/// But it MUST scale with the input, and a fixed floor was a serious bug. A constant
182/// 16 meant rayon refused to split any map of fewer than 32 items — and the tile
183/// encode pass maps over one BUCKET's tile groups, of which California z11 has only
184/// ~7 (1,899 tiles over 256 buckets). The whole pass therefore ran on one thread:
185/// 86.7s of wall clock for 92s of CPU, an effective parallelism of 1.06 on a 64-core
186/// box, while z16 with ~3,500 groups per bucket parallelised fine and hid it.
187///
188/// So: aim for a few tasks per thread, and never fewer tasks than there are items.
189pub fn min_task_len(items: usize) -> usize {
190 let want_tasks = threads().saturating_mul(4).max(1);
191 (items / want_tasks).max(1)
192}
193
194/// A target number of encode tasks for a batch split by cost rather than by count.
195///
196/// The same "a few tasks per thread" aim as [`min_task_len`], but the encode pass groups tiles by
197/// cumulative geometry cost — one dense city tile outweighs a thousand rural ones — so it needs a
198/// task *count* to divide the total cost by, not a minimum run length. [`min_task_len`]'s contiguous
199/// runs cannot isolate that heavy tile; cost-based groups make it its own task, which is what keeps
200/// one dense tile from stranding a whole task's worth of cores while it finishes alone.
201pub fn encode_task_count() -> usize {
202 threads().saturating_mul(4).max(1)
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn parse_threads_rejects_zero_and_junk() {
211 assert_eq!(parse_threads("8"), Ok(8));
212 assert!(parse_threads("0").is_err());
213 assert!(parse_threads("-1").is_err());
214 assert!(parse_threads("many").is_err());
215 assert!(parse_threads("").is_err());
216 }
217
218 #[test]
219 fn the_flag_beats_the_env_beats_the_box() {
220 let box_threads = resolve(0, None);
221 assert_eq!(resolve(6, Some("2")), 6, "--threads wins");
222 assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");
223 assert_eq!(resolve(6, None), 6);
224 for junk in ["0", "many", "", "-4"] {
225 assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");
226 }
227 assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");
228 }
229
230 /// A batch has to hold enough tasks to keep the pool busy, and a small map must
231 /// still be split at all — the bug this guards is a floor so high that a map of
232 /// one bucket's ~7 tile groups became a single task on a 64-core box.
233 #[test]
234 fn a_small_map_is_still_split_across_the_pool() {
235 for n in [1usize, 2, 3, 32, 64] {
236 set_threads(n);
237 assert_eq!(min_task_len(7), 1, "{n} threads: 7 items must give 7 tasks");
238 assert_eq!(min_task_len(0), 1, "an empty map must not divide by zero");
239 let big = 100_000;
240 let tasks = big / min_task_len(big);
241 assert!(
242 tasks >= n * 2,
243 "{n} threads: {tasks} task(s) for {big} items is not enough to fill \
244 the pool"
245 );
246 let tasks_small = 7 / min_task_len(7);
247 assert!(tasks_small >= 1.min(n));
248 }
249 clear_threads();
250 }
251}