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

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

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