Modern Apps git

← Modern-Apps.git

maps: cap the ingest thread pool with --threads and MAPS_THREADS

Commit
9d759d134daaed61e53b98fdebc8e8774782aff7
Author
vayun-mathur <[email protected]>
When
2026-08-26 01:31 UTC (3 months ago)
Parents
d7313db

Diff

scripts/maps/build_all.ps1
diff --git a/scripts/maps/build_all.ps1 b/scripts/maps/build_all.ps1index ecb4bd7d1d..7e66b2346f 100644--- a/scripts/maps/build_all.ps1+++ b/scripts/maps/build_all.ps1@@ -198,7 +198,9 @@ if (Test-Stage "graph") {         $graphArgs = @($Pbf, "--out", $OutDir)         if ($WithinWayChains) { $graphArgs += "--within-way-chains" }         if ($Rounds -gt 0)    { $graphArgs += @("--rounds", "$Rounds") }-        if ($SpillDir)        { $graphArgs += @("--spill-dir", $SpillDir) }+        # One subdirectory per stage, matching the "roads" one the tiles stage uses+        # below, so the two spills stay separately measurable and deletable.+        if ($SpillDir)        { $graphArgs += @("--spill-dir", (Join-Path $SpillDir "graph")) }         Invoke-Step "cargo" (@("run", "--release", "--quiet", "--manifest-path", $OsmManifest,             "--bin", "road_graph", "--") + $graphArgs)         Set-Stamp "graph"
scripts/maps/build_all.sh
diff --git a/scripts/maps/build_all.sh b/scripts/maps/build_all.shindex 6bfc0e0d80..affed97f06 100644--- a/scripts/maps/build_all.sh+++ b/scripts/maps/build_all.sh@@ -315,7 +315,13 @@ if want_stage graph; then         GRAPH_ARGS=("$PBF" --out "$OUT_DIR")         [[ "$WITHIN_WAY_CHAINS" == "1" ]] && GRAPH_ARGS+=(--within-way-chains)         [[ -n "$ROUNDS" ]] && GRAPH_ARGS+=(--rounds "$ROUNDS")-        [[ -n "$SPILL_DIR" ]] && GRAPH_ARGS+=(--spill-dir "$SPILL_DIR")+        # Its own subdirectory, mirroring the "$SPILL_DIR/roads" the tiles stage+        # hands the roads tiler below. Not a correctness fix -- chains.rs already+        # namespaces its two files under chain_spill/, so the graph and the tiler+        # never actually collided -- but once the two stages overlap, one+        # subdirectory per stage is what makes their scratch separately+        # measurable and separately deletable.+        [[ -n "$SPILL_DIR" ]] && GRAPH_ARGS+=(--spill-dir "$SPILL_DIR/graph")         # Gated deliberately: road_graph truncates its outputs as it writes, so a         # failure here must not fall through to the manifest or the publish.         run cargo run --release --quiet --manifest-path "$HERE/osm_ingest/Cargo.toml" \
scripts/maps/osm_ingest/src/bin/osm_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/osm_extract.rs b/scripts/maps/osm_ingest/src/bin/osm_extract.rsindex a48c405313..a4c361f046 100644--- a/scripts/maps/osm_ingest/src/bin/osm_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/osm_extract.rs@@ -7,7 +7,8 @@  use std::process::ExitCode; -const USAGE: &str = "Usage: osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX]";+const USAGE: &str =+    "Usage: osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX] [--threads N]";  fn main() -> ExitCode {     let argv: Vec<String> = std::env::args().skip(1).collect();@@ -23,6 +24,10 @@ fn main() -> ExitCode {         }     }; +    if let Some(n) = args.threads {+        osm_ingest::par::set_threads(n);+    }+     let options = osm_ingest::extract::Options {         layer: args.layer,         bbox: args.bbox,
scripts/maps/osm_ingest/src/bin/poi_extract.rs
diff --git a/scripts/maps/osm_ingest/src/bin/poi_extract.rs b/scripts/maps/osm_ingest/src/bin/poi_extract.rsindex f83e0d05a3..a09227a5bf 100644--- a/scripts/maps/osm_ingest/src/bin/poi_extract.rs+++ b/scripts/maps/osm_ingest/src/bin/poi_extract.rs@@ -6,7 +6,7 @@ use std::process::ExitCode;  const USAGE: &str = "Usage: poi_extract IN.osm.pbf --geojson FILE --names FILE \-                     --index FILE [--attrs FILE]";+                     --index FILE [--attrs FILE] [--threads N]";  fn main() -> ExitCode {     let argv: Vec<String> = std::env::args().skip(1).collect();@@ -18,6 +18,10 @@ fn main() -> ExitCode {         }     }; +    if let Some(n) = args.threads {+        osm_ingest::par::set_threads(n);+    }+     let started = std::time::Instant::now();     match osm_ingest::poi_build::build(         &args.input,
scripts/maps/osm_ingest/src/bin/road_graph.rs
diff --git a/scripts/maps/osm_ingest/src/bin/road_graph.rs b/scripts/maps/osm_ingest/src/bin/road_graph.rsindex 08618a6346..35f8f003a7 100644--- a/scripts/maps/osm_ingest/src/bin/road_graph.rs+++ b/scripts/maps/osm_ingest/src/bin/road_graph.rs@@ -6,8 +6,8 @@ use std::process::ExitCode;  const USAGE: &str = "Usage: road_graph IN.osm.pbf [--out DIR] [--within-way-chains] \-                     [--rounds N] [--spill-dir DIR] [--spill-pts-dir DIR] [--stats]   \-                     (default --out map_data, --rounds 1)";+                     [--rounds N] [--spill-dir DIR] [--spill-pts-dir DIR] [--threads N] \+                     [--stats] (default --out map_data, --rounds 1)";  /// Print what a narrower `edges.bin` record would cost on this extract. ///
scripts/maps/osm_ingest/src/extract.rs
diff --git a/scripts/maps/osm_ingest/src/extract.rs b/scripts/maps/osm_ingest/src/extract.rsindex 7a3cfe3189..956550e2f8 100644--- a/scripts/maps/osm_ingest/src/extract.rs+++ b/scripts/maps/osm_ingest/src/extract.rs@@ -1193,18 +1193,21 @@ pub struct Args {     pub out: PathBuf,     pub layer: Layer,     pub bbox: Option<BBox>,+    /// `None` leaves the pool at whatever `par::threads()` decides.+    pub threads: Option<usize>, } -/// `osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX]`+/// `osm_extract IN.osm.pbf --layer NAME --out FILE [--bbox BOX] [--threads N]` pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {     let mut input: Option<PathBuf> = None;     let mut out: Option<PathBuf> = None;     let mut layer: Option<Layer> = None;     let mut bbox: Option<BBox> = None;+    let mut threads: Option<usize> = None;     let mut i = 0;     while i < args.len() {         match args[i].as_str() {-            flag @ ("--out" | "--layer" | "--bbox") => {+            flag @ ("--out" | "--layer" | "--bbox" | "--threads") => {                 i += 1;                 let value = args                     .get(i)@@ -1213,6 +1216,7 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {                 match flag {                     "--out" => out = Some(PathBuf::from(value)),                     "--layer" => layer = Some(Layer::parse(value)?),+                    "--threads" => threads = Some(crate::par::parse_threads(value)?),                     _ => bbox = Some(BBox::parse(value).map_err(|e| e.0)?),                 }             }@@ -1231,6 +1235,7 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {         out: out.ok_or_else(|| "--out is required".to_string())?,         layer: layer.ok_or_else(|| "--layer is required".to_string())?,         bbox,+        threads,     }) } @@ -1309,6 +1314,32 @@ mod tests {         assert_eq!(run("a"), run("b"));     } +    /// The point of `--threads`: it must change only how fast the work happens.+    /// Counts that do not divide the chunk count are the interesting ones.+    #[test]+    fn the_thread_cap_changes_no_bytes() {+        let (pbf_path, dir) = testpbf::write_layers_sample("extract_threads");+        let run = |n: usize| {+            crate::par::set_threads(n);+            let out = dir.join(format!("safety.t{n}.geojsonseq"));+            build(+                &pbf_path,+                &out,+                &Options {+                    layer: Layer::Safety,+                    bbox: None,+                },+            )+            .unwrap();+            std::fs::read(out).unwrap()+        };+        let serial = run(1);+        for n in [2, 3, 7, 32] {+            assert_eq!(serial, run(n), "{n} threads perturbed the output");+        }+        crate::par::clear_threads();+    }+     #[test]     fn a_bbox_that_excludes_everything_yields_an_empty_layer() {         let (pbf_path, dir) = testpbf::write_layers_sample("extract_bbox");@@ -1726,4 +1757,28 @@ mod tests {         ])         .is_err());     }++    #[test]+    fn threads_is_optional_and_must_be_positive() {+        let base: Vec<String> = vec![+            "in.pbf".into(),+            "--layer".into(),+            "safety".into(),+            "--out".into(),+            "o".into(),+        ];+        assert_eq!(parse_args(&base).unwrap().threads, None);++        let mut with = base.clone();+        with.extend(["--threads".to_string(), "6".to_string()]);+        assert_eq!(parse_args(&with).unwrap().threads, Some(6));++        let mut zero = base.clone();+        zero.extend(["--threads".to_string(), "0".to_string()]);+        assert!(parse_args(&zero).is_err());++        let mut bare = base;+        bare.push("--threads".into());+        assert!(parse_args(&bare).is_err());+    } }
scripts/maps/osm_ingest/src/graph_build.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build.rs b/scripts/maps/osm_ingest/src/graph_build.rsindex 01efea5645..6f1c06f2d9 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -512,6 +512,8 @@ pub struct Options {     pub spill_pts_dir: Option<PathBuf>,     /// Print the [`Census`] report after the build. Changes no output file.     pub stats: bool,+    /// Cap on the parallel pool. `None` leaves it to [`crate::par::threads`].+    pub threads: Option<usize>, }  impl Options {@@ -525,6 +527,9 @@ pub fn build(input: &Path, out_dir: &Path) -> Result<Stats> { }  pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> {+    if let Some(n) = opts.threads {+        crate::par::set_threads(n);+    }     std::fs::create_dir_all(out_dir)         .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?; @@ -2279,6 +2284,13 @@ pub fn parse_args(             }             "--within-way-chains" => opts.within_way_chains = true,             "--stats" => opts.stats = true,+            "--threads" => {+                i += 1;+                let n = args+                    .get(i)+                    .ok_or_else(|| "--threads needs a count".to_string())?;+                opts.threads = Some(crate::par::parse_threads(n)?);+            }             "--spill-dir" => {                 i += 1;                 let dir = args@@ -4126,6 +4138,13 @@ mod tests {         assert!(parse_args(&["a".into(), "--rounds".into(), "0".into()]).is_err());         assert!(parse_args(&["a".into(), "--rounds".into(), "many".into()]).is_err());         assert!(parse_args(&["a".into(), "--rounds".into()]).is_err());+        let (_, _, opts) = parse_args(&["c.pbf".into()]).unwrap();+        assert!(opts.threads.is_none(), "the pool defaults to the box");+        let (_, _, opts) =+            parse_args(&["c.pbf".into(), "--threads".into(), "4".into()]).unwrap();+        assert_eq!(opts.threads, Some(4));+        assert!(parse_args(&["a".into(), "--threads".into(), "0".into()]).is_err());+        assert!(parse_args(&["a".into(), "--threads".into()]).is_err());         assert!(parse_args(&[]).is_err());         assert!(parse_args(&["a".into(), "b".into()]).is_err());         assert!(parse_args(&["--wat".into()]).is_err());
scripts/maps/osm_ingest/src/par.rs
diff --git a/scripts/maps/osm_ingest/src/par.rs b/scripts/maps/osm_ingest/src/par.rsindex 9d086ce269..3c06a99a18 100644--- a/scripts/maps/osm_ingest/src/par.rs+++ b/scripts/maps/osm_ingest/src/par.rs@@ -5,16 +5,88 @@ //! index order gives output that does not depend on thread scheduling. Every //! parallel stage in this crate is built on that property — it is what makes the //! tool reproducible, which the C++ generator it replaces was not.+//!+//! The pool size is capped by [`set_threads`] (`--threads`) or `MAPS_THREADS`,+//! because the build scripts run several of these tools concurrently and an+//! uncapped pool oversubscribes the box once they do.  use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex; +/// 0 means "not set"; any other value is an explicit cap from `--threads`.+static OVERRIDE: AtomicUsize = AtomicUsize::new(0);++/// Cap the pool for the rest of the process. Called once from `main` after+/// argument parsing.+///+/// This exists because the build scripts fan out several of these tools at once.+/// `available_parallelism()` reports the whole box to every one of them, so six+/// concurrent layer builds would each claim 32 threads on a 32-core machine and+/// finish slower than running in sequence. The cap has to be settable from+/// outside the process, hence this and `MAPS_THREADS`.+pub fn set_threads(n: usize) {+    OVERRIDE.store(n.max(1), Ordering::Relaxed);+}++/// Drop the override again, so a test can leave the process as it found it.+#[cfg(test)]+pub fn clear_threads() {+    OVERRIDE.store(0, Ordering::Relaxed);+}++/// Threads to use for one parallel stage.+///+/// `--threads` beats `MAPS_THREADS` beats the box. A single-process run sets+/// neither and is therefore unchanged. pub fn threads() -> usize {+    resolve(+        OVERRIDE.load(Ordering::Relaxed),+        std::env::var("MAPS_THREADS").ok().as_deref(),+    )+}++/// The precedence rule, split out so it can be tested without mutating the+/// process-wide override or the environment.+fn resolve(override_n: usize, env: Option<&str>) -> usize {+    if override_n > 0 {+        return override_n;+    }+    if let Some(n) = env_threads(env) {+        return n;+    }     std::thread::available_parallelism()         .map(|n| n.get())         .unwrap_or(4) } +/// A malformed or non-positive `MAPS_THREADS` is ignored rather than fatal: it+/// is usually exported once for a whole script run, and killing an eight-hour+/// planet build over a typo in an environment variable serves nobody. Warned+/// about once, because `threads()` is called once per parallel stage.+fn env_threads(raw: Option<&str>) -> Option<usize> {+    static WARNED: std::sync::Once = std::sync::Once::new();+    let trimmed = raw?.trim();+    match trimmed.parse::<usize>() {+        Ok(n) if n > 0 => Some(n),+        _ => {+            WARNED.call_once(|| {+                eprintln!("WARNING: ignoring MAPS_THREADS='{trimmed}' (wants a positive count)");+            });+            None+        }+    }+}++/// Parse a `--threads N` value. Shared by all three binaries so they reject the+/// same things with the same message.+pub fn parse_threads(value: &str) -> std::result::Result<usize, String> {+    value+        .parse::<usize>()+        .ok()+        .filter(|n| *n > 0)+        .ok_or_else(|| format!("--threads wants a positive count, not {value}"))+}+ /// Apply `f(chunk_start, chunk)` to every chunk of `chunk_len` items, returning /// the results in chunk order. pub fn map_chunks<T, R, F>(items: &[T], chunk_len: usize, f: F) -> Vec<R>@@ -68,6 +140,29 @@ mod tests {         assert_eq!(out.iter().map(|c| c.1).sum::<usize>(), items.iter().sum());     } +    #[test]+    fn parse_threads_rejects_zero_and_junk() {+        assert_eq!(parse_threads("8"), Ok(8));+        assert!(parse_threads("0").is_err());+        assert!(parse_threads("-1").is_err());+        assert!(parse_threads("many").is_err());+        assert!(parse_threads("").is_err());+    }++    #[test]+    fn the_flag_beats_the_env_beats_the_box() {+        let box_threads = resolve(0, None);+        assert_eq!(resolve(6, Some("2")), 6, "--threads wins");+        assert_eq!(resolve(0, Some("2")), 2, "MAPS_THREADS wins over the box");+        assert_eq!(resolve(6, None), 6);+        // Junk in the environment falls back to the box rather than failing, so a+        // typo cannot silently serialise a long build.+        for junk in ["0", "many", "", "-4"] {+            assert_eq!(resolve(0, Some(junk)), box_threads, "MAPS_THREADS={junk}");+        }+        assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated");+    }+     #[test]     fn empty_input_produces_no_chunks() {         let out = map_chunks::<usize, usize, _>(&[], 8, |_, _| unreachable!());
scripts/maps/osm_ingest/src/poi_build.rs
diff --git a/scripts/maps/osm_ingest/src/poi_build.rs b/scripts/maps/osm_ingest/src/poi_build.rsindex eb0058ad6f..a3156f0b96 100644--- a/scripts/maps/osm_ingest/src/poi_build.rs+++ b/scripts/maps/osm_ingest/src/poi_build.rs@@ -568,10 +568,12 @@ pub struct Args {     pub attrs: PathBuf,     pub spatial: PathBuf,     pub name_index: PathBuf,+    /// `None` leaves the pool at whatever `par::threads()` decides.+    pub threads: Option<usize>, }  /// `poi_extract IN.osm.pbf --geojson FILE --names FILE --index FILE [--attrs FILE]`-/// `[--spatial FILE] [--name-index FILE]`+/// `[--spatial FILE] [--name-index FILE] [--threads N]` /// /// The optional outputs default to their conventional names beside `--index`, so a /// caller that predates any of them keeps working and still emits them. Making them@@ -584,9 +586,17 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {     let mut attrs: Option<PathBuf> = None;     let mut spatial: Option<PathBuf> = None;     let mut name_index: Option<PathBuf> = None;+    let mut threads: Option<usize> = None;     let mut i = 0;     while i < args.len() {         match args[i].as_str() {+            "--threads" => {+                i += 1;+                let value = args+                    .get(i)+                    .ok_or_else(|| "--threads needs a value".to_string())?;+                threads = Some(crate::par::parse_threads(value)?);+            }             flag @ ("--geojson" | "--names" | "--index" | "--attrs" | "--spatial"             | "--name-index") => {                 let flag = flag.to_string();@@ -631,6 +641,7 @@ pub fn parse_args(args: &[String]) -> std::result::Result<Args, String> {         attrs,         spatial,         name_index,+        threads,     }) } @@ -911,10 +922,35 @@ mod tests {         // Defaulted beside the index, so a caller written before the sidecar existed         // still emits one rather than silently skipping it.         assert_eq!(ok.attrs, PathBuf::from("out/poi_attrs.bin"));+        assert!(ok.threads.is_none(), "the pool defaults to the box");         assert!(parse_args(&["in.pbf".into()]).is_err());         assert!(parse_args(&["in.pbf".into(), "--geojson".into()]).is_err());     } +    #[test]+    fn threads_must_be_positive() {+        let base: Vec<String> = vec![+            "in.pbf".into(),+            "--geojson".into(),+            "g".into(),+            "--names".into(),+            "n".into(),+            "--index".into(),+            "i".into(),+        ];+        let mut with = base.clone();+        with.extend(["--threads".to_string(), "3".to_string()]);+        assert_eq!(parse_args(&with).unwrap().threads, Some(3));++        let mut zero = base.clone();+        zero.extend(["--threads".to_string(), "0".to_string()]);+        assert!(parse_args(&zero).is_err());++        let mut bare = base;+        bare.push("--threads".into());+        assert!(parse_args(&bare).is_err());+    }+     #[test]     fn an_explicit_attrs_path_overrides_the_default() {         let ok = parse_args(&[