Modern Apps git

← Modern-Apps.git

maps: transit_shapes scales past one core, 380 s -> 27 s on a planet (#perf)

Commit
cecc07525f5592eb47f4190d482ae5de342b2bcd
Author
Vayun Mathur <[email protected]>
When
2026-11-10 20:39 UTC (25 days ago)
Parents
9cabb91
What: transit_shapes --pack world.transit, the basemap transit layer,
now keeps the box busy end to end. Output is byte-identical to the
frozen baseline and across --threads 1/8/192.

Root cause: a planet run showed 193 threads and exactly 100% CPU. The
rayon pool was idle; the orchestrating thread spent 297 of 380 s in
the cover-gate fold (walk every surviving line, ask the colour/mode
covers whether it is already drawn or over-crowded, add it), which is
order-dependent and ran one line at a time over ~52 k lines. The rest
was the corridor pass: 50 s interning per-sample memberships one sample
at a time, 18 s of corridor cut dominated by nearest() walking every
segment of a reference per probe, 13 s of probe/grid prep, and 4 s
reading the whole 4.4 GB pack to use 300 MB of it.

How (each step exact, not approximate):
- Fold: dedup by (hash, colour) is settled first - it depends only on
  the key sequence. The gates then run in speculative windows of 64
  lines: every line is walked and judged in parallel against the covers
  as they stand at the window start, then resolved in order. Both gates
  only grow as samples are appended, and a query reads only the 3x3
  cells around a sample, so a speculated `false` is re-asked against
  the live cover only beside a cell gained since speculation
  (Covered::mark / changed_near); everything else is the sequential
  answer. Adds stay sequential and in order. A window of 1 is the old
  loop; a new test pins windows 2..64 to it byte for byte (and fails if
  the re-ask is removed).
- Covered: buckets hold the drawn samples inline with their tag, one
  per cell per service (the old `filled` set folded into the bucket),
  64 shards so a long line's add fills them in parallel, and a
  multiply-xorshift hasher (nothing iterates either map). Per-line
  re-asks and the crowd gate go wide for long lines.
- Interning: each probe range interns locally in first-seen order and
  the ranges are merged in order, which reproduces the global
  first-seen ids exactly; probe ranges are fixed 256 Ki-sample units
  claimed first-come instead of one equal share per thread; the probe
  reads the three cells of a grid column as one contiguous range.
- nearest()/within(): references carry 32-segment block bounds (lat
  gap, and lon gap times the block's smallest per-segment cos_lat,
  less 1 cm slack). The block with the lowest floor seeds an upper
  bound; blocks whose floor exceeds it are skipped; the rest are walked
  in order as before, so the first minimal segment is unchanged. A
  test checks distance and along bit-for-bit against the full walk.
- Corridor cut runs on the pool (one candidate per task, largest
  first); placements per run and the snap search go wide.
- --pack reads only STRINGS, FEEDS and RAIL_LINES
  (Reader::open_sections); RAIL_LINES decode and Line building are
  parallel; output lines are formatted in parallel and written through
  an 8 MiB buffer.
- --threads N (anywhere on the command line) and MAPS_THREADS now size
  every pool via gtfs_ingest::par::threads(); before, the tool always
  used the whole box.

Verified on world.transit (91,476 shapes, 239,381 lines out):
- sha256 d392606fed8c8fd36d2102a2849ea9e0f5cc3dea2d7d79dadd5a31d248d95f8f
  for baseline-bin/transit_shapes and for this build at --threads 192,
  8, 1 and MAPS_THREADS=8; summary line identical.
- Wall: 380.5 s (473% CPU, 28.7 GB RSS) -> 26.6 s (8400% CPU,
  15.3 GB RSS). Stages before -> after: parse-feeds incl. fold
  296.8 -> 17.3, corridor-probe 12.8 -> 7.1, corridor-spans 50.6 -> 0.3,
  corridor-order 0.9 -> 0.7, corridor-cut 18.5 -> 0.8, write 0.9 -> 0.3.
  8 threads: 128 s; 1 thread: 914 s at 18.3 GB.
- cargo test --release -p gtfs_ingest: all pass (85 lib + 15 bin incl.
  the two new tests).

Diff

scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rsindex 8951b44816..978a30ba5b 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes.rs@@ -84,7 +84,40 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Mutex;  fn main() -> ExitCode {-    let args: Vec<String> = std::env::args().collect();+    let mut args: Vec<String> = std::env::args().collect();+    // `--threads N` anywhere, taken out before the positional parse. It and `MAPS_THREADS`+    // size every pool this tool runs; neither changes a byte of the output.+    if let Some(at) = args.iter().position(|a| a == "--threads") {+        let Some(value) = args.get(at + 1).cloned() else {+            eprintln!("ERROR: transit_shapes: --threads requires a count");+            return ExitCode::from(2);+        };+        match gtfs_ingest::par::parse_threads(&value) {+            Ok(n) => gtfs_ingest::par::set_threads(n),+            Err(e) => {+                eprintln!("ERROR: transit_shapes: {e}");+                return ExitCode::from(2);+            }+        }+        args.drain(at..at + 2);+    }+    // One pool for every rayon call in the run, sized by the thread budget rather than by+    // the whole box, so `--threads` / `MAPS_THREADS` govern the parallel sorts and maps too.+    let pool = match rayon::ThreadPoolBuilder::new()+        .num_threads(gtfs_ingest::par::threads())+        .thread_name(|i| format!("transit_shapes-{i}"))+        .build()+    {+        Ok(p) => p,+        Err(e) => {+            eprintln!("ERROR: transit_shapes: cannot start the thread pool: {e}");+            return ExitCode::FAILURE;+        }+    };+    pool.install(|| run_main(args))+}++fn run_main(args: Vec<String>) -> ExitCode {     if args.len() >= 2 && (args[1] == "-h" || args[1] == "--help") {         usage();         return ExitCode::SUCCESS;
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rsindex 2a902a3467..0a98929ff6 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra.rs@@ -384,3 +384,59 @@ fn a_route_with_no_usable_shape_is_counted_and_drawn_nothing() {      let _ = std::fs::remove_dir_all(&root); }++/// The cover gates resolve a window of lines speculated in parallel; a window of one line is+/// the sequential fold exactly, and every other window must reproduce it byte for byte. The+/// set is built to make the windows disagree if anything were stale: many routes republishing+/// one track a few metres apart (the colour gate), uncoloured copies (the mode gate), five or+/// more colours over one stretch (the crowd gate), short-turns, and lines long enough to take+/// the wide per-line and sharded-add paths.+#[test]+fn the_speculative_window_changes_no_byte() {+    let root = std::env::temp_dir().join(format!("gtfs_shapes_window_{}", std::process::id()));+    let _ = std::fs::remove_dir_all(&root);+    std::fs::create_dir_all(&root).unwrap();+    let colours = ["0054A5", "E31E24", "00A651", "", "FFC20E", "8E44AD", "", "0054A5"];+    let mut routes = String::from("route_id,route_short_name,route_type,route_color\n");+    let mut trips = String::from("route_id,trip_id,shape_id\n");+    let mut shapes = String::from("shape_id,shape_pt_lat,shape_pt_lon,shape_pt_sequence\n");+    let mut x = 0x2545_F491_4F6C_DD1Du64;+    let mut next = move || {+        x ^= x << 13;+        x ^= x >> 7;+        x ^= x << 17;+        x+    };+    for r in 0..60u64 {+        let colour = colours[(next() % colours.len() as u64) as usize];+        let route_type = [1, 1, 0, 2][(next() % 4) as usize];+        routes.push_str(&format!("R{r},L{},{route_type},{colour}\n", r % 9));+        trips.push_str(&format!("R{r},T{r},S{r}\n"));+        // Up to ~1.1 degrees (~120 km) of one north-south trunk, starting anywhere along its+        // first half, offset sideways by 0-40 m, with a kink partway.+        let start = 37.0 + (next() % 500) as f64 * 1e-3;+        let length = [0.02, 0.1, 0.5, 1.1][(next() % 4) as usize];+        let lon = -122.0 + (next() % 40) as f64 * 1e-5;+        let kink = (next() % 3) as f64 * 1e-4;+        let points = [(start, lon), (start + length * 0.4, lon + kink), (start + length, lon)];+        for (seq, (lat, lon)) in points.iter().enumerate() {+            shapes.push_str(&format!("S{r},{lat:.7},{lon:.7},{}\n", seq + 1));+        }+    }+    std::fs::write(root.join("routes.txt"), routes).unwrap();+    std::fs::write(root.join("trips.txt"), trips).unwrap();+    std::fs::write(root.join("shapes.txt"), shapes).unwrap();+    let specs: Vec<FeedSpec> = vec![("trunk".to_string(), root.clone(), String::new())];++    let render = |window: usize| -> String {+        let out = root.join(format!("w{window}.geojsonseq"));+        super::extra2::run_windowed(&out, super::extra2::Inputs::Feeds(&specs), None, window).unwrap();+        std::fs::read_to_string(&out).unwrap()+    };+    let sequential = render(1);+    assert!(sequential.lines().count() > 3, "the set must keep several lines: {sequential}");+    for window in [2, 3, 7, 16, 64] {+        assert_eq!(render(window), sequential, "window {window}");+    }+    let _ = std::fs::remove_dir_all(&root);+}
scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rsindex 194c3ed231..528aee4707 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_extra2.rs@@ -22,11 +22,19 @@ pub(crate) fn run(out_path: &Path, specs: &[FeedSpec]) -> Result<(), String> { /// corridor stages inside [`expand_corridor_spans`], then `write-output` over /// the sort and file write, and emits the `TIMING` line before the human /// summary. `None` skips every tick, which is what the tests drive via [`run`].-pub(crate) fn run_with_timer(+pub(crate) fn run_with_timer(out_path: &Path, inputs: Inputs<'_>, timer: Option<PhaseTimer>) -> Result<(), String> {+    run_windowed(out_path, inputs, timer, FOLD_WINDOW)+}++/// [`run_with_timer`] with the cover gates' speculative window as a parameter, so a test can+/// pin that the window changes nothing: a window of one line is the sequential fold exactly.+pub(crate) fn run_windowed(     out_path: &Path,     inputs: Inputs<'_>,     mut timer: Option<PhaseTimer>,+    fold_window: usize, ) -> Result<(), String> {+    let fold_window = fold_window.max(1);     let mut seen: HashSet<(u64, u32)> = HashSet::new();     let mut lines: Vec<Line> = Vec::new();     // Track already drawn, per colour and per mode. Two of one colour must never draw as@@ -63,7 +71,7 @@ pub(crate) fn run_with_timer(         t.switch("parse-feeds");     }     let parse_start = Instant::now();-    let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);+    let threads = gtfs_ingest::par::threads();     let chunk_size = threads.saturating_mul(2).max(1);      let total = match inputs {@@ -97,67 +105,123 @@ pub(crate) fn run_with_timer(         }          // The dedup key is a content hash of the geometry, so it is order-independent and every-        // line's can be computed in parallel. Only the `seen.insert` below stays sequential —-        // it is what decides, in feed order, which duplicate of a shared alignment survives.+        // line's can be computed in parallel.         let keys: Vec<(u64, u32)> = chunk_lines             .par_iter()             .map(|line| (polyline_hash(&line.points), line.color))             .collect(); +        // Across feeds as well as within one, so an alignment published by both a city feed and+        // the regional feed that merges it draws once.+        //+        // Keyed on the colour too, which the hash alone was not: two services running the same+        // track are routinely published against one `shape_id`, and dropping one of them because+        // its geometry had been seen is how a corridor loses a line. This is only the fast path+        // for the subtraction below, which would reach the same answer the slow way.+        //+        // Settled for the whole chunk before any cover gate runs: every line reaches+        // `seen.insert` whatever the gates later decide about it, so which lines survive it is a+        // function of the key sequence alone, and decides which duplicate survives, in feed+        // order, exactly as the interleaved loop did.+        let mut survivors: Vec<Line> = Vec::with_capacity(chunk_lines.len());         for (line, key) in chunk_lines.into_iter().zip(keys) {-            // Across feeds as well as within one, so an alignment published by both a city-            // feed and the regional feed that merges it draws once.-            //-            // Keyed on the colour too, which the hash alone was not: two services running-            // the same track are routinely published against one `shape_id`, and dropping-            // one of them because its geometry had been seen is how a corridor loses a-            // line. This is only the fast path for the subtraction below, which would reach-            // the same answer the slow way.-            if !seen.insert(key) {+            if seen.insert(key) {+                survivors.push(line);+            } else {                 deduped += 1;-                continue;             }-            // Walked once here: `covered_fraction`, `crowd_reaches` and the two `add`s-            // below each used to re-walk `line.points` and allocate a fresh sample vector.-            // The samples depend only on the geometry, so one walk feeds all four.-            let walked = bundle::walk(&line.points);-            let mode_cover = by_mode.entry(line.mode).or_default();-            let redundant = if line.fallback {-                mode_cover.covered_fraction_walked(&walked) >= MOSTLY_DRAWN-            } else {-                by_color-                    .entry((line.mode, line.color))-                    .or_default()-                    .covered_fraction_walked(&walked)-                    >= MOSTLY_DRAWN-            };-            if redundant {-                merged += 1;-                continue;+        }++        // The cover gates. They are order-dependent — each line is judged against everything+        // accepted before it — and this loop used to be the whole run: 293 of a planet's 380 s,+        // on one core, walking and probing ~52 k lines one after another.+        //+        // Now speculative, and still exact. A window of lines is walked and judged in parallel+        // against the covers as they stand at the window's start, then resolved in order. A+        // speculated per-sample answer can only be stale where a line accepted earlier in the+        // same window appended samples to a cell that answer read (`Covered::changed_near`+        // against the cover's mark at speculation time), and a `true` is never stale, since both+        // gates only grow as samples are appended. So resolution re-asks the live cover only for+        // the samples that answered `false` beside such a cell — usually none, since a colour's+        // cover changes only when a line of that colour was accepted earlier in the window.+        // Every other answer is the one the sequential loop would have computed. Adds stay+        // sequential and in order, so the covers evolve exactly as before, and the window size+        // decides how much is re-asked, never what is decided.+        let mut rest = survivors.into_iter();+        loop {+            let window: Vec<Line> = rest.by_ref().take(fold_window).collect();+            if window.is_empty() {+                break;             }-            // The gates above are colour-scoped, deliberately: two services sharing a track-            // are two real services and both should draw. On a planet that stops being true.-            // One alignment is republished by a city feed, the regional feed containing it and-            // a national feed on top, each with its own `route_color` and often its own-            // `route_type`, so each reads as a distinct service and claims its own lane. That-            // is what makes one railway render as fifteen jagged parallel lines.-            //-            // A ceiling rather than a ban, so the two-services-on-one-track case the tests-            // pin still works. Above it the track is already saying everything it can.-            //-            // Intercity lines are exempt: at country zoom they are the only transit drawn, so-            // losing one to a crowded shared corridor (the Northeast Corridor carries a dozen-            // commuter services) would cut a gap in the national network.-            if !line.intercity && mode_cover.crowd_reaches_walked(&walked, MAX_SERVICES_PER_TRACK) {-                crowded += 1;-                continue;+            let specs: Vec<Speculated> =+                window.par_iter().map(|line| speculate(line, &by_color, &by_mode)).collect();+            // Freed off this thread: each line's samples were allocated on a worker, and handing+            // a few hundred MB back to other threads' arenas one line at a time was a fifth of+            // this loop.+            let mut spent: Vec<(Vec<bundle::Walked>, Vec<bundle::Cell>, Vec<u32>)> = Vec::with_capacity(window.len());+            for (line, spec) in window.into_iter().zip(specs) {+                let Speculated { walked, cells, drawn, uncovered, redundant, crowd, gate_mark, mode_mark } = spec;+                let spent_len = spent.len();+                spent.push((walked, cells, uncovered));+                let (walked, cells, uncovered) = {+                    let (w, c, u) = &spent[spent_len];+                    (w.as_slice(), c.as_slice(), u.as_slice())+                };+                let gate = if line.fallback { by_mode.get(line.mode) } else { by_color.get(&(line.mode, line.color)) };+                let redundant = redundant+                    || gate.is_some_and(|g| {+                        if g.mark() == gate_mark {+                            return false;+                        }+                        recount_reaches(g, gate_mark, walked, cells, drawn, uncovered)+                    });+                if redundant {+                    merged += 1;+                    continue;+                }+                // The gates above are colour-scoped, deliberately: two services sharing a track+                // are two real services and both should draw. On a planet that stops being true.+                // One alignment is republished by a city feed, the regional feed containing it+                // and a national feed on top, each with its own `route_color` and often its own+                // `route_type`, so each reads as a distinct service and claims its own lane. That+                // is what makes one railway render as fifteen jagged parallel lines.+                //+                // A ceiling rather than a ban, so the two-services-on-one-track case the tests+                // pin still works. Above it the track is already saying everything it can.+                //+                // Intercity lines are exempt: at country zoom they are the only transit drawn, so+                // losing one to a crowded shared corridor (the Northeast Corridor carries a dozen+                // commuter services) would cut a gap in the national network.+                if !line.intercity {+                    // Speculated for every non-intercity line speculation did not find redundant,+                    // which is every line that can reach here.+                    let over = crowd.expect("crowd speculated")+                        || by_mode.get(line.mode).is_some_and(|m| {+                            m.mark() != mode_mark && recrowd_reaches(m, mode_mark, walked, cells)+                        });+                    if over {+                        crowded += 1;+                        continue;+                    }+                }+                let mode_cover = by_mode.entry(line.mode).or_default();+                let color_cover = by_color.entry((line.mode, line.color)).or_default();+                rayon::join(+                    || mode_cover.add_tagged_walked_in(walked, cells, line.color),+                    || color_cover.add_tagged_walked_in(walked, cells, 0),+                );+                if line.fallback {+                    fell_back += 1;+                }+                lines.push(line);             }-            mode_cover.add_tagged_walked(&walked, line.color);-            by_color.entry((line.mode, line.color)).or_default().add_walked(&walked);-            if line.fallback {-                fell_back += 1;+            // On a one-thread pool a spawned job would only run once this thread goes idle -+            // at the end of the run - so every window's samples would pile up until then.+            if rayon::current_num_threads() > 1 {+                rayon::spawn(move || drop(spent));+            } else {+                drop(spent);             }-            lines.push(line);         }     }     eprintln!();@@ -187,36 +251,15 @@ pub(crate) fn run_with_timer(      let file = std::fs::File::create(out_path)         .map_err(|e| format!("cannot write {}: {e}", out_path.display()))?;-    let mut out = BufWriter::new(file);-    let mut buf: Vec<u8> = Vec::new();-    for line in &lines {-        buf.clear();-        buf.extend_from_slice(-            b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"LineString\",\"coordinates\":[",-        );-        for (i, (lat, lon)) in line.points.iter().enumerate() {-            if i > 0 {-                buf.push(b',');-            }-            write!(buf, "[{:.7},{:.7}]", *lon as f64 * 1e-7, *lat as f64 * 1e-7)-                .map_err(io_err)?;+    // Large sequential writes: the output disk compresses per extent.+    let mut out = BufWriter::with_capacity(8 << 20, file);+    // Each line's JSON depends on that line alone, so blocks of lines are formatted wide and+    // written in order.+    for block in lines.chunks(4096) {+        let texts: Vec<Result<Vec<u8>, String>> = block.par_iter().map(feature_json).collect();+        for text in texts {+            out.write_all(&text?).map_err(io_err)?;         }-        write!(-            buf,-            "]}},\"properties\":{{\"color\":\"{:06X}\",\"mode\":\"{}\",\"ordinal\":{},\-             \"lanes\":{},\"taper\":{},{}\"route\":\"",-            intercity::drawn_color(line.color, line.intercity, fallback_color(line.mode)),-            line.mode,-            line.ordinal,-            line.lanes,-            line.taper,-            // Only when set, so every other line is written exactly as before.-            if line.intercity { "\"intercity\":1," } else { "" },-        )-        .map_err(io_err)?;-        json_escape(line.route.as_bytes(), &mut buf);-        buf.extend_from_slice(b"\"}}\n");-        out.write_all(&buf).map_err(io_err)?;     }     out.flush().map_err(io_err)?; @@ -240,6 +283,34 @@ pub(crate) fn run_with_timer(     Ok(()) } +/// One output line: a GeoJSON `Feature` and its newline.+fn feature_json(line: &Line) -> Result<Vec<u8>, String> {+    let mut buf: Vec<u8> = Vec::with_capacity(64 + line.points.len() * 26);+    buf.extend_from_slice(b"{\"type\":\"Feature\",\"geometry\":{\"type\":\"LineString\",\"coordinates\":[");+    for (i, (lat, lon)) in line.points.iter().enumerate() {+        if i > 0 {+            buf.push(b',');+        }+        write!(buf, "[{:.7},{:.7}]", *lon as f64 * 1e-7, *lat as f64 * 1e-7).map_err(io_err)?;+    }+    write!(+        buf,+        "]}},\"properties\":{{\"color\":\"{:06X}\",\"mode\":\"{}\",\"ordinal\":{},\+         \"lanes\":{},\"taper\":{},{}\"route\":\"",+        intercity::drawn_color(line.color, line.intercity, fallback_color(line.mode)),+        line.mode,+        line.ordinal,+        line.lanes,+        line.taper,+        // Only when set, so every other line is written exactly as before.+        if line.intercity { "\"intercity\":1," } else { "" },+    )+    .map_err(io_err)?;+    json_escape(line.route.as_bytes(), &mut buf);+    buf.extend_from_slice(b"\"}}\n");+    Ok(buf)+}+ /// Parse one chunk of feeds on `threads` workers, back in spec order, so the fold sees exactly /// the sequence a sequential read would give it. fn parse_chunk(chunk: &[FeedSpec], threads: usize) -> Vec<(usize, Result<FeedLines, String>)> {@@ -293,3 +364,145 @@ fn fmt_dur(secs: f64) -> String {         format!("{}h{:02}m", s / 3600, (s % 3600) / 60)     } }++/// Lines per speculative window of the cover gates. Decides only how much is re-asked at+/// resolution, never what is decided. Measured on the world pack at 192 threads: 16 lines+/// spent 12 s in window barriers, 128 spent 8 s re-asking, 64 balanced the two (~17 s for the+/// whole fold, against 293 s sequential).+const FOLD_WINDOW: usize = 64;++/// The fewest drawn samples out of `len` for which `drawn as f64 / len as f64 >=+/// MOSTLY_DRAWN` — the gate's own arithmetic, solved for the count, so comparing a count+/// against it decides exactly what the division would.+fn drawn_needed(len: usize) -> usize {+    let at = |d: usize| d as f64 / len as f64 >= MOSTLY_DRAWN;+    let mut d = ((MOSTLY_DRAWN * len as f64).floor() as usize).min(len);+    while d > 0 && at(d - 1) {+        d -= 1;+    }+    while !at(d) {+        d += 1;+    }+    d+}++/// Samples below which a per-line pass stays on the calling thread: under it a fork-join+/// costs more than it saves. Changes no answer.+const PAR_SAMPLES: usize = 4096;++/// One line judged against the covers as they stood at its window's start.+struct Speculated {+    walked: Vec<bundle::Walked>,+    /// `bundle::sample_cell` of every walked sample.+    cells: Vec<bundle::Cell>,+    /// Samples already drawn in the gating cover.+    drawn: usize,+    /// The rest, by index into `walked`: the only answers resolution may have to revise.+    uncovered: Vec<u32>,+    redundant: bool,+    /// The crowd gate's answer, for a line that can reach it (not redundant, not intercity).+    crowd: Option<bool>,+    /// `Covered::mark` of the gating cover and of the mode's cover when this ran (0 for a+    /// cover not created yet, which answered as an empty one).+    gate_mark: u32,+    mode_mark: u32,+}++fn speculate(+    line: &Line,+    by_color: &BTreeMap<(&'static str, u32), bundle::Covered>,+    by_mode: &BTreeMap<&'static str, bundle::Covered>,+) -> Speculated {+    let walked = bundle::walk(&line.points);+    let cells: Vec<bundle::Cell> = walked.iter().map(bundle::sample_cell).collect();+    // Exactly the cover the sequential gate reads: the mode's for a line on its mode's+    // fallback colour, the colour's otherwise. A cover not created yet is an empty one.+    let gate = if line.fallback { by_mode.get(line.mode) } else { by_color.get(&(line.mode, line.color)) };+    let mode = by_mode.get(line.mode);+    let uncovered: Vec<u32> = match gate {+        None => (0..walked.len() as u32).collect(),+        Some(g) => {+            let scan = |lo: usize, hi: usize| -> Vec<u32> {+                (lo..hi).filter(|&k| !g.covers_sample_in(cells[k], &walked[k])).map(|k| k as u32).collect()+            };+            if walked.len() < PAR_SAMPLES {+                scan(0, walked.len())+            } else {+                let starts: Vec<usize> = (0..walked.len()).step_by(PAR_SAMPLES).collect();+                let parts: Vec<Vec<u32>> =+                    starts.par_iter().map(|&lo| scan(lo, (lo + PAR_SAMPLES).min(walked.len()))).collect();+                parts.concat()+            }+        }+    };+    let drawn = walked.len() - uncovered.len();+    // `covered_fraction_walked`'s arithmetic, including 0 for a line too short to walk.+    let redundant = !walked.is_empty() && drawn as f64 / walked.len() as f64 >= MOSTLY_DRAWN;+    let crowd = (!redundant && !line.intercity).then(|| {+        mode.is_some_and(|m| {+            let at = |k: usize| m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new());+            if walked.len() < PAR_SAMPLES {+                (0..walked.len()).any(at)+            } else {+                (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)+            }+        })+    });+    Speculated {+        walked,+        cells,+        drawn,+        uncovered,+        redundant,+        crowd,+        gate_mark: gate.map_or(0, bundle::Covered::mark),+        mode_mark: mode.map_or(0, bundle::Covered::mark),+    }+}++/// The redundancy gate re-decided against the live cover `g`: the speculated `drawn`, plus+/// every speculated-uncovered sample that is now covered — which only a sample beside a cell+/// `g` has gained since `mark` can be. Whether the count reaches the threshold is all that+/// matters, so a small line stops as soon as that is settled either way.+fn recount_reaches(+    g: &bundle::Covered,+    mark: u32,+    walked: &[bundle::Walked],+    cells: &[bundle::Cell],+    drawn: usize,+    uncovered: &[u32],+) -> bool {+    let need = drawn_needed(walked.len());+    let now_covered = |k: u32| {+        let k = k as usize;+        g.changed_near(cells[k], mark) && g.covers_sample_in(cells[k], &walked[k])+    };+    if uncovered.len() >= PAR_SAMPLES {+        return drawn + uncovered.par_iter().with_min_len(PAR_SAMPLES / 4).filter(|&&k| now_covered(k)).count() >= need;+    }+    let (mut drawn, mut left) = (drawn, uncovered.len());+    for &k in uncovered {+        if drawn >= need || drawn + left < need {+            break;+        }+        left -= 1;+        if now_covered(k) {+            drawn += 1;+        }+    }+    drawn >= need+}++/// The crowd gate re-decided against the live mode cover `m`, where the speculated answer+/// was `false`: only a sample beside a cell `m` has gained since `mark` can have changed.+fn recrowd_reaches(m: &bundle::Covered, mark: u32, walked: &[bundle::Walked], cells: &[bundle::Cell]) -> bool {+    let at = |k: usize| {+        m.changed_near(cells[k], mark)+            && m.crowd_reaches_in(cells[k], &walked[k], MAX_SERVICES_PER_TRACK, &mut Vec::new())+    };+    if walked.len() < PAR_SAMPLES {+        (0..walked.len()).any(at)+    } else {+        (0..walked.len()).into_par_iter().with_min_len(PAR_SAMPLES / 4).any(at)+    }+}
scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rsindex 7d8ab8f8fc..5a55cbab31 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_shapes_pack.rs@@ -7,10 +7,16 @@  use super::*; use gtfs_ingest::reader::Reader;+use rayon::prelude::*;  /// Every RAIL_LINES entry as a candidate line, in pack order. pub(crate) fn pack_lines(path: &Path) -> Result<FeedLines, String> {-    let pack = Reader::open(path)?;+    // Only what this reads: the RAIL_LINES records, the feed table and the string pool their+    // names live in — about 300 MB of a 4.4 GB world pack.+    let pack = Reader::open_sections(+        path,+        &[gtfs_ingest::reader::SEC_STRINGS, gtfs_ingest::reader::SEC_FEEDS, gtfs_ingest::reader::SEC_RAIL_LINES],+    )?;     let Some(recs) = pack.rail_lines() else {         return Err(format!(             "{} is a v{} pack with no RAIL_LINES section; rebuild it with scripts/maps/build_world_transit.ps1",@@ -20,27 +26,35 @@ pub(crate) fn pack_lines(path: &Path) -> Result<FeedLines, String> {     };     let feeds: Vec<String> = (0..pack.feed_count()).map(|f| pack.feed_name(f)).collect();     let mut out = FeedLines::default();-    for rec in recs {-        let Some(mode) = mode_of(rec.route_type) else {-            return Err(format!("RAIL_LINES carries route_type {}, which is not rail", rec.route_type));-        };-        let (color, fallback) = match rec.color {-            0 => (fallback_color(mode), true),-            c => (c, false),-        };+    // Built wide (the intercity test walks every line), then taken in pack order, so the first+    // bad record is still the one reported.+    let built: Vec<Result<Line, String>> = recs+        .into_par_iter()+        .map(|rec| {+            let Some(mode) = mode_of(rec.route_type) else {+                return Err(format!("RAIL_LINES carries route_type {}, which is not rail", rec.route_type));+            };+            let (color, fallback) = match rec.color {+                0 => (fallback_color(mode), true),+                c => (c, false),+            };+            Ok(Line {+                intercity: intercity::is_intercity(intercity::is_long_distance_type(rec.route_type), &rec.points),+                points: rec.points,+                color,+                mode,+                fallback,+                route: rec.name,+                route_key: format!("{}\u{0}{}", feeds[rec.feed_idx as usize], rec.route_id),+                ordinal: 0,+                lanes: 1,+                taper: 255,+            })+        })+        .collect();+    for line in built {+        out.lines.push(line?);         out.shapes_read += 1;-        out.lines.push(Line {-            intercity: intercity::is_intercity(intercity::is_long_distance_type(rec.route_type), &rec.points),-            points: rec.points,-            color,-            mode,-            fallback,-            route: rec.name,-            route_key: format!("{}\u{0}{}", feeds[rec.feed_idx as usize], rec.route_id),-            ordinal: 0,-            lanes: 1,-            taper: 255,-        });     }     Ok(out) }
scripts/maps/gtfs_ingest/src/bundle.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle.rs b/scripts/maps/gtfs_ingest/src/bundle.rsindex 53103feda9..9f3ba01248 100644--- a/scripts/maps/gtfs_ingest/src/bundle.rs+++ b/scripts/maps/gtfs_ingest/src/bundle.rs@@ -242,47 +242,70 @@ pub fn assign_with_timer(     // Flat `(values, ends)` buffers rather than `Vec<Vec<u32>>`: 287 million heap allocations     // is its own kind of slow, and the whole point of interning is not to hold that many     // vectors at once.-    let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);-    let span = samples.len().div_ceil(threads.max(1)).max(1);+    let threads = crate::par::threads();+    // Fixed-size ranges claimed first-come, not one range per thread: sample density is wildly+    // uneven (a European trunk holds dozens of routes per cell, a desert line one), and with+    // equal shares the thread that drew the dense ranges finished long after the rest.+    const PROBE_RANGE: usize = 1 << 18;+    let ranges = samples.len().div_ceil(PROBE_RANGE);+    let next_range = AtomicUsize::new(0);     let probed = AtomicUsize::new(0);-    let parts: Mutex<Vec<(usize, Vec<u32>, Vec<u32>)>> = Mutex::new(Vec::new());+    // Per range: its samples as local set ids, plus its distinct sets in the order it first saw+    // them, flat (`values`, `ends`).+    let parts: Mutex<Vec<(usize, Vec<u32>, Vec<u32>, Vec<u32>)>> = Mutex::new(Vec::new());     {         let grid = &grid;         let samples = &samples;         let parts = &parts;         let probed = &probed;+        let next_range = &next_range;         let total = samples.len();         std::thread::scope(|scope| {-            for t in 0..threads {-                let lo = t * span;-                if lo >= total {-                    break;-                }-                let hi = ((t + 1) * span).min(total);+            for _ in 0..threads.min(ranges) {                 scope.spawn(move || {                     // Per thread, so the stamp trick in `routes_near` needs no sharing: a                     // stamp only has to be unique against this thread's own array.                     let mut seen: Vec<u32> = vec![0; route_count];                     let mut stamp: u32 = 0;                     let mut near: Vec<u32> = Vec::new();-                    let mut values: Vec<u32> = Vec::new();-                    let mut ends: Vec<u32> = Vec::with_capacity(hi - lo);-                    for (i, sample) in samples[lo..hi].iter().enumerate() {-                        stamp += 1;-                        grid.routes_near(samples, sample, &mut near, &mut seen, stamp);-                        values.extend_from_slice(&near);-                        ends.push(values.len() as u32);-                        // Batched, because an atomic per probe would cost more than the probe.-                        if i % 65_536 == 0 {-                            let n = probed.fetch_add(65_536, AtomicOrdering::Relaxed) + 65_536;-                            eprint!(-                                "\r{:<28} [{:>3}%] {total} sample(s)",-                                "Corridor probe",-                                (n * 100 / total.max(1)).min(100)-                            );+                    let mut done: Vec<(usize, Vec<u32>, Vec<u32>, Vec<u32>)> = Vec::new();+                    loop {+                        let r = next_range.fetch_add(1, AtomicOrdering::Relaxed);+                        if r >= ranges {+                            break;                         }+                        let (lo, hi) = (r * PROBE_RANGE, ((r + 1) * PROBE_RANGE).min(total));+                        // Interned locally, in first-seen order within this range; see the+                        // merge below for why that composes into the global first-seen ids+                        // exactly.+                        let mut local: std::collections::HashMap<Vec<u32>, u32> = std::collections::HashMap::new();+                        let mut ids: Vec<u32> = Vec::with_capacity(hi - lo);+                        let mut values: Vec<u32> = Vec::new();+                        let mut ends: Vec<u32> = Vec::new();+                        for sample in &samples[lo..hi] {+                            stamp += 1;+                            grid.routes_near(samples, sample, &mut near, &mut seen, stamp);+                            let id = match local.get(near.as_slice()) {+                                Some(&id) => id,+                                None => {+                                    let id = ends.len() as u32;+                                    values.extend_from_slice(&near);+                                    ends.push(values.len() as u32);+                                    local.insert(near.clone(), id);+                                    id+                                }+                            };+                            ids.push(id);+                        }+                        done.push((r, ids, values, ends));+                        let n = probed.fetch_add(hi - lo, AtomicOrdering::Relaxed) + (hi - lo);+                        eprint!(+                            "\r{:<28} [{:>3}%] {total} sample(s)",+                            "Corridor probe",+                            (n * 100 / total.max(1)).min(100)+                        );                     }-                    parts.lock().expect("probe pool").push((t, values, ends));+                    parts.lock().expect("probe pool").extend(done);                 });             }         });@@ -291,10 +314,18 @@ pub fn assign_with_timer(     // The runs cutting below is spans work, not probe work.     tick(&mut timer, "corridor-spans"); -    // Back in sample order, then interned sequentially: first-seen order is what fixes the ids.+    // Back in sample order, then each range's local ids mapped onto global ones. The global id+    // of a set is its rank in first-seen order over the whole sample sequence. A set first+    // occurs globally in the earliest range holding it, at that range's own first occurrence of+    // it, so walking the ranges in order and each range's distinct sets in its local first-seen+    // order meets every set's first global occurrence in global order — the ids come out exactly+    // as the sample-by-sample interning assigned them, at one map lookup per distinct set per+    // range instead of one per sample (287 M on a world set, ~50 s on one core).     let mut parts = parts.into_inner().expect("probe pool");-    parts.sort_unstable_by_key(|(t, _, _)| *t);-    for (_, values, ends) in &parts {+    parts.sort_unstable_by_key(|(t, _, _, _)| *t);+    let mut remaps: Vec<Vec<u32>> = Vec::with_capacity(parts.len());+    for (_, _, values, ends) in &parts {+        let mut remap = Vec::with_capacity(ends.len());         let mut start = 0usize;         for &end in ends {             let near = &values[start..end as usize];@@ -308,8 +339,17 @@ pub fn assign_with_timer(                     id                 }             };-            per_sample.push(id);+            remap.push(id);         }+        remaps.push(remap);+    }+    let mapped: Vec<Vec<u32>> = parts+        .par_iter()+        .zip(remaps.par_iter())+        .map(|((_, ids, _, _), remap)| ids.iter().map(|&l| remap[l as usize]).collect())+        .collect();+    for ids in mapped {+        per_sample.extend_from_slice(&ids);     }     drop(parts); @@ -318,10 +358,10 @@ pub fn assign_with_timer(     // last one is its end. Summing the chords between probes instead would fall short of     // that wherever the alignment curves, and the drift accumulates over a route's length     // until the last run is cut short of the line's own end.-    let own_cum: Vec<Vec<f64>> = candidates.iter().map(|c| cumulative(c.points)).collect();+    let own_cum: Vec<Vec<f64>> = candidates.par_iter().map(|c| cumulative(c.points)).collect();     let probe_cum: Vec<Vec<f64>> = blocks-        .iter()-        .zip(&own_cum)+        .par_iter()+        .zip(own_cum.par_iter())         .map(|(block, own)| {             let total = own.last().copied().unwrap_or(0.0);             let count = block.len();@@ -332,8 +372,8 @@ pub fn assign_with_timer(         .collect();      let runs: Vec<Vec<Run>> = blocks-        .iter()-        .zip(&probe_cum)+        .par_iter()+        .zip(probe_cum.par_iter())         .map(|(block, cum)| cut_runs(&per_sample[block.clone()], cum))         .collect(); @@ -391,57 +431,31 @@ pub fn assign_with_timer(         o.sort_unstable_by_key(|&i| std::cmp::Reverse(runs[i].len()));         o     };-    let cut_next = AtomicUsize::new(0);+    // On the run's own pool rather than on scoped threads, so the one transcontinental line+    // that used to grind alone at the end can split its own placements across the idle+    // workers (see `spans_of`). One candidate per task, so dispatch stays first-come in the+    // largest-first order above.     let cut_done = AtomicUsize::new(0);-    let cut_parts: Mutex<Vec<(usize, Vec<Span>)>> = Mutex::new(Vec::with_capacity(total));-    {-        let corridors = &corridors;-        let cut_parts = &cut_parts;-        let cut_done = &cut_done;-        let cut_next = &cut_next;-        let samples = &samples;-        let runs = &runs;-        let blocks = &blocks;-        let probe_cum = &probe_cum;-        let own_cum = &own_cum;-        let order = &order;-        std::thread::scope(|scope| {-            for _ in 0..threads.min(total.max(1)) {-                scope.spawn(move || {-                    let mut local: Vec<(usize, Vec<Span>)> = Vec::new();-                    loop {-                        let slot = cut_next.fetch_add(1, AtomicOrdering::Relaxed);-                        if slot >= total {-                            break;-                        }-                        let at = order[slot];-                        local.push((-                            at,-                            spans_of(-                                &candidates[at],-                                &runs[at],-                                &samples[blocks[at].clone()],-                                &probe_cum[at],-                                &own_cum[at],-                                corridors,-                            ),-                        ));-                        let n = cut_done.fetch_add(1, AtomicOrdering::Relaxed) + 1;-                        if n % 64 == 0 {-                            eprint!(-                                "\r{:<28} [{:>3}%] {total} line(s)",-                                "Corridor cut",-                                n * 100 / total.max(1)-                            );-                        }-                    }-                    cut_parts.lock().expect("cut pool").extend(local);-                });+    let mut cut_parts: Vec<(usize, Vec<Span>)> = order+        .par_iter()+        .with_max_len(1)+        .map(|&at| {+            let spans = spans_of(+                &candidates[at],+                &runs[at],+                &samples[blocks[at].clone()],+                &probe_cum[at],+                &own_cum[at],+                &corridors,+            );+            let n = cut_done.fetch_add(1, AtomicOrdering::Relaxed) + 1;+            if n % 64 == 0 {+                eprint!("\r{:<28} [{:>3}%] {total} line(s)", "Corridor cut", n * 100 / total.max(1));             }-        });-    }+            (at, spans)+        })+        .collect();     eprintln!("\r{:<28} [100%] {total} line(s)", "Corridor cut");-    let mut cut_parts = cut_parts.into_inner().expect("cut pool");     cut_parts.sort_unstable_by_key(|(at, _)| *at);     cut_parts.into_iter().map(|(_, spans)| spans).collect() }@@ -474,6 +488,16 @@ struct Corridor {     /// The corridor's distinct colours, ordered across it: the first is the left-hand side of     /// the reference's direction of travel, which is the side [`Span::ordinal`] zero draws on.     colours: Vec<u32>,+    /// Bounds over runs of [`SEG_BLOCK`] consecutive segments of `points`, so [`nearest`] can+    /// skip the ones that cannot hold the answer. Derived from `points`.+    blocks: Vec<SegBlock>,+}++impl Corridor {+    fn new(points: Vec<(i32, i32)>, cum: Vec<f64>, colours: Vec<u32>) -> Corridor {+        let blocks = seg_blocks(&points);+        Corridor { points, cum, colours, blocks }+    } }  /// Cut a candidate's samples into runs of constant membership, then smooth away the ones too
scripts/maps/gtfs_ingest/src/bundle_part1.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part1.rs b/scripts/maps/gtfs_ingest/src/bundle_part1.rsindex 916b218ea2..1447dbbf48 100644--- a/scripts/maps/gtfs_ingest/src/bundle_part1.rs+++ b/scripts/maps/gtfs_ingest/src/bundle_part1.rs@@ -89,7 +89,7 @@ fn corridors_of(     // the output is byte-identical however the threads interleave.     let entries: Vec<(u32, Vec<(usize, f64, f64)>)> = members.into_iter().collect();     let total = entries.len();-    let threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);+    let threads = crate::par::threads();     let next = AtomicUsize::new(0);     let finished = AtomicUsize::new(0);     let collected: Mutex<Vec<(u32, Corridor)>> = Mutex::new(Vec::with_capacity(total));@@ -174,7 +174,7 @@ fn one_corridor(                 .expect("a corridor has at least one member");             let points = canonical(candidates[pick].points);             let cum = cumulative(&points);-            let reference = Corridor { points, cum, colours: Vec::new() };+            let reference = Corridor::new(points, cum, Vec::new());              // Where each member sits across the corridor, averaged over the colour: two             // routes of one colour share a lane, so they share one place in the order.
scripts/maps/gtfs_ingest/src/bundle_part2.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part2.rs b/scripts/maps/gtfs_ingest/src/bundle_part2.rsindex 9490f9f15e..68a200cc10 100644--- a/scripts/maps/gtfs_ingest/src/bundle_part2.rs+++ b/scripts/maps/gtfs_ingest/src/bundle_part2.rs@@ -1,3 +1,7 @@+/// Run length, in samples, from which the snap search in [`spans_of`] goes wide. Changes no+/// answer.+const PAR_SNAP: usize = 64;+ /// One candidate's spans, in its own order of travel. fn spans_of(     candidate: &Candidate,@@ -14,8 +18,9 @@ fn spans_of(         return whole();     } +    // Per run independent, and collected in run order.     let placements: Vec<Option<Placement>> = runs-        .iter()+        .par_iter()         .map(|run| {             let corridor = corridors.get(&run.set)?;             let a = distance_along(corridor, samples[run.from].point);@@ -26,10 +31,19 @@ fn spans_of(             if hi - lo < SAMPLE_M {                 return None;             }-            let near = |at: usize| nearest(corridor, samples[at].point).0 <= SNAP_M;-            let snap = (run.from..=run.to).find(|&at| near(at)).map(|first| {-                (first, (first..=run.to).rev().find(|&at| near(at)).unwrap_or(first))-            });+            let near = |at: usize| within(corridor, samples[at].point, SNAP_M);+            // Each probe is a walk of the whole reference, so a long run on a long corridor is+            // the single most expensive thing in the cut. `find_first` / `find_last` are the+            // sequential first and last match exactly, just searched wide.+            let snap = if run.to - run.from < PAR_SNAP {+                (run.from..=run.to).find(|&at| near(at)).map(|first| {+                    (first, (first..=run.to).rev().find(|&at| near(at)).unwrap_or(first))+                })+            } else {+                (run.from..run.to + 1).into_par_iter().with_min_len(8).find_first(|&at| near(at)).map(|first| {+                    (first, (first..run.to + 1).into_par_iter().with_min_len(8).find_last(|&at| near(at)).unwrap_or(first))+                })+            };             Some(Placement { corridor, forward, lo, hi, snap })         })         .collect();@@ -266,19 +280,120 @@ fn distance_along(corridor: &Corridor, p: (i32, i32)) -> f64 {     nearest(corridor, p).1 } +/// Segments per [`SegBlock`].+const SEG_BLOCK: usize = 32;++/// Slack, in metres, taken off every [`SegBlock::lower_bound`]: far above the nanometres of+/// rounding [`project`] can introduce at planetary coordinates, far below anything a skip+/// could save.+const BOUND_SLACK_M: f64 = 0.01;++/// The extent of a run of consecutive reference segments, in the terms [`project`] measures in.+struct SegBlock {+    lat_lo: i32,+    lat_hi: i32,+    lon_lo: i32,+    lon_hi: i32,+    /// The smallest of the run's per-segment `cos_lat`s, computed exactly as [`project`] does.+    cos_min: f64,+}++impl SegBlock {+    /// A floor under [`project`]'s distance from `p` to any segment of the run.+    ///+    /// `project` measures in metres north (`lat × k`, the same for every segment) and metres+    /// east scaled by the segment's own `cos_lat`. The closest point of a segment lies inside+    /// the segment's box, so its northing is at least the latitude gap from `p` to the run's+    /// box away, and its easting at least the longitude gap times the smallest `cos_lat` in the+    /// run. Less the slack, so the floor holds through rounding.+    fn lower_bound(&self, p: (i32, i32)) -> f64 {+        let k = 1e-7 * 111_320.0;+        let (lat, lon) = (p.0 as f64, p.1 as f64);+        let gy = (self.lat_lo as f64 - lat).max(lat - self.lat_hi as f64).max(0.0) * k;+        let gx = (self.lon_lo as f64 - lon).max(lon - self.lon_hi as f64).max(0.0) * k * self.cos_min.max(0.0);+        (gx * gx + gy * gy).sqrt() - BOUND_SLACK_M+    }+}++fn seg_blocks(points: &[(i32, i32)]) -> Vec<SegBlock> {+    let segs = points.len().saturating_sub(1);+    (0..segs.div_ceil(SEG_BLOCK))+        .map(|b| {+            let (lo, hi) = (b * SEG_BLOCK, ((b + 1) * SEG_BLOCK).min(segs));+            let run = &points[lo..=hi];+            let cos_min = (lo..hi)+                .map(|at| ((points[at].0 as f64 + points[at + 1].0 as f64) * 0.5 * 1e-7).to_radians().cos())+                .fold(f64::INFINITY, f64::min);+            SegBlock {+                lat_lo: run.iter().map(|q| q.0).min().expect("two points"),+                lat_hi: run.iter().map(|q| q.0).max().expect("two points"),+                lon_lo: run.iter().map(|q| q.1).min().expect("two points"),+                lon_hi: run.iter().map(|q| q.1).max().expect("two points"),+                cos_min,+            }+        })+        .collect()+}++/// The segments of block `b` of a polyline with `segs` segments.+fn block_segs(b: usize, segs: usize) -> std::ops::Range<usize> {+    b * SEG_BLOCK..((b + 1) * SEG_BLOCK).min(segs)+}+ /// The nearest point on a corridor's reference to `p`, as `(distance to it, distance along)`.+///+/// The first segment, in reference order, at the smallest [`project`] distance — what a walk+/// of every segment keeping strict improvements returns, which is what this used to be. That+/// walk was most of the corridor cut on a world set: one per probe, over references of tens of+/// thousands of points. Now the block with the lowest floor is measured first; its best+/// distance bounds the answer from above, every block whose floor is over that bound is+/// skipped — it cannot hold the minimum, nor tie it — and the rest are walked in reference+/// order exactly as before. fn nearest(corridor: &Corridor, p: (i32, i32)) -> (f64, f64) {     let (points, cum) = (&corridor.points, &corridor.cum);+    let segs = points.len().saturating_sub(1);+    let blocks = &corridor.blocks;+    let mut bound = f64::INFINITY;+    if blocks.len() > 2 {+        let mut seed = (f64::INFINITY, 0usize);+        for (b, block) in blocks.iter().enumerate() {+            let lb = block.lower_bound(p);+            if lb < seed.0 {+                seed = (lb, b);+            }+        }+        for at in block_segs(seed.1, segs) {+            let offset = project(p, points[at], points[at + 1], 0.0).1;+            if offset < bound {+                bound = offset;+            }+        }+    }     let mut best = (f64::INFINITY, 0.0f64);-    for at in 0..points.len().saturating_sub(1) {-        let (t, offset) = project(p, points[at], points[at + 1], 0.0);-        if offset < best.0 {-            best = (offset, cum[at] + t * (cum[at + 1] - cum[at]));+    for (b, block) in blocks.iter().enumerate() {+        if block.lower_bound(p) > bound {+            continue;+        }+        for at in block_segs(b, segs) {+            let (t, offset) = project(p, points[at], points[at + 1], 0.0);+            if offset < best.0 {+                best = (offset, cum[at] + t * (cum[at + 1] - cum[at]));+            }         }     }     best } +/// `nearest(corridor, p).0 <= radius`, deciding as soon as any segment is that close and+/// skipping every block whose floor is already further.+fn within(corridor: &Corridor, p: (i32, i32), radius: f64) -> bool {+    let (points, segs) = (&corridor.points, corridor.points.len().saturating_sub(1));+    corridor.blocks.iter().enumerate().any(|(b, block)| {+        block.lower_bound(p) <= radius+            && block_segs(b, segs).any(|at| project(p, points[at], points[at + 1], 0.0).1 <= radius)+    })+}+ /// How far to the side of a corridor's reference `p` lies, in metres, signed positive to the /// right of the reference's direction of travel. ///@@ -395,17 +510,62 @@ const NEIGHBOURHOOD: [(i32, i32); 9] = /// The lookup is a `HashMap` of cells rather than the sorted vector the rest of this module /// uses. Nothing iterates it — the answer is a boolean about one point — so it cannot leak an /// order into the output.-#[derive(Default)] pub struct Covered {-    points: Vec<((i32, i32), f64, f64)>,-    cells: std::collections::HashMap<Cell, Vec<u32>>,-    /// Which service drew each sample, parallel to `points`. See [`Covered::crowd`].-    tags: Vec<u32>,-    /// The `(cell, tag)` pairs already holding a representative. One sample per cell per-    /// service is enough for [`covers`](Covered::covers) and [`tags_over`](Covered::tags_over):+    /// Every drawn sample, bucketed by its cell.+    ///+    /// **One representative per cell per service**: a bucket holds at most one sample of each+    /// tag. That is enough for [`covers`](Covered::covers) and [`tags_over`](Covered::tags_over):     /// both ask whether *any* sample of a service is within a corridor of a point, and every     /// sample of one service in one cell answers that identically. Keeping only the first turns     /// a cell's occupancy from overlap depth — a trunk republished by a dozen feeds is a dozen     /// sample runs in the same cells — into distinct services, which is what those gates read.-    filled: std::collections::HashSet<(Cell, u32)>,+    /// It also makes "is this service already in this cell" a scan of a handful of entries in a+    /// bucket already being looked up, rather than a second set of `(cell, tag)` pairs.+    ///+    /// Split into [`COVER_SHARDS`] maps by [`shard_of`], so a long line's add fills them all+    /// at once. A pure partition: every cell lives in exactly one shard, and each shard sees its+    /// cells' samples in line order, so every bucket ends up holding exactly what one map would.+    cells: Vec<std::collections::HashMap<Cell, Bucket, CellHash>>,+    /// How many `add` calls this cover has taken; see [`Covered::mark`].+    adds: u32,+}++impl Default for Covered {+    fn default() -> Self {+        Covered { cells: (0..COVER_SHARDS).map(|_| Default::default()).collect(), adds: 0 }+    }+}++/// Shards per [`Covered`]. Changes no answer; only how wide an add can go.+const COVER_SHARDS: usize = 64;++/// The shard holding `cell`. Mixed independently of [`CellHasher`], so the cells of one shard+/// still spread over its own table.+fn shard_of((x, y): Cell) -> usize {+    let h = (x as u32).wrapping_mul(0x9E37_79B1) ^ (y as u32).wrapping_mul(0x85EB_CA77);+    (h.wrapping_mul(0xC2B2_AE35) >> 26) as usize % COVER_SHARDS+}++/// One cell's representatives, in the order they were added.+struct Bucket {+    /// The `adds` count of the last add that appended here.+    added: u32,+    /// Inline, because most buckets — every bucket of a colour's cover — hold exactly one.+    first: Drawn,+    rest: Vec<Drawn>,+}++impl Bucket {+    fn iter(&self) -> impl Iterator<Item = &Drawn> {+        std::iter::once(&self.first).chain(self.rest.iter())+    }+}++/// One drawn sample and the service that drew it.+#[derive(Clone, Copy)]+struct Drawn {+    point: (i32, i32),+    ux: f64,+    uy: f64,+    tag: u32, }
scripts/maps/gtfs_ingest/src/bundle_part3.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part3.rs b/scripts/maps/gtfs_ingest/src/bundle_part3.rsindex ab0f359eb8..409b864e53 100644--- a/scripts/maps/gtfs_ingest/src/bundle_part3.rs+++ b/scripts/maps/gtfs_ingest/src/bundle_part3.rs@@ -17,19 +17,59 @@ impl Covered {     /// [`add_tagged`](Self::add_tagged) over samples already walked by [`walk`], so a caller     /// running several gates over one line walks it once and shares the result.     pub fn add_tagged_walked(&mut self, walked: &[Walked], tag: u32) {-        for &sample in walked {-            let cell = cell_of(sample.0);-            // One representative per cell per service: a second sample of the same service in-            // the same cell cannot change any `covers`/`tags_over` answer, and dropping it is-            // what stops a heavily-republished trunk's buckets growing with the feed count.-            if !self.filled.insert((cell, tag)) {-                continue;+        let cells: Vec<Cell> = walked.iter().map(sample_cell).collect();+        self.add_tagged_walked_in(walked, &cells, tag);+    }++    /// [`add_tagged_walked`](Self::add_tagged_walked) with each sample's [`sample_cell`]+    /// already computed, parallel to `walked`.+    pub fn add_tagged_walked_in(&mut self, walked: &[Walked], cells: &[Cell], tag: u32) {+        debug_assert_eq!(walked.len(), cells.len());+        self.adds += 1;+        let now = self.adds;+        // A run of samples in one cell — about four per 40 m cell at 10 m spacing — needs one+        // bucket probe, not four: after the first, the cell holds a sample of `tag` whichever+        // way that probe went, so every later one would be dropped anyway. The same holds for+        // any repeat of a cell within one add, which is why each shard may also skip its own+        // consecutive repeats below.+        let mut firsts: Vec<u32> = Vec::with_capacity(walked.len() / 3 + 1);+        let mut prev: Option<Cell> = None;+        for (k, &cell) in cells.iter().enumerate() {+            if prev != Some(cell) {+                firsts.push(k as u32);+                prev = Some(cell);+            }+        }+        if firsts.len() < 2048 {+            for k in firsts {+                let cell = cells[k as usize];+                insert(&mut self.cells[shard_of(cell)], cell, walked[k as usize], tag, now);             }-            let at = self.points.len() as u32;-            self.cells.entry(cell).or_default().push(at);-            self.points.push(sample);-            self.tags.push(tag);+            return;+        }+        // Counting sort by shard, stable, so each shard takes its samples in line order.+        let mut starts = [0usize; COVER_SHARDS + 1];+        for &k in &firsts {+            starts[shard_of(cells[k as usize]) + 1] += 1;         }+        for i in 0..COVER_SHARDS {+            starts[i + 1] += starts[i];+        }+        let mut fill = starts;+        let mut order = vec![0u32; firsts.len()];+        for &k in &firsts {+            let s = shard_of(cells[k as usize]);+            order[fill[s]] = k;+            fill[s] += 1;+        }+        // A few thousand inserts per task: each fork wakes sleeping workers, and on a line of a+        // few thousand cells waking all of them costs more than the inserts.+        let tasks = (firsts.len() / 2048).clamp(1, COVER_SHARDS);+        self.cells.par_iter_mut().enumerate().with_min_len(COVER_SHARDS.div_ceil(tasks)).for_each(|(s, map)| {+            for &k in &order[starts[s]..starts[s + 1]] {+                insert(map, cells[k as usize], walked[k as usize], tag, now);+            }+        });     }      /// The most distinct services already drawn over any one metre of `line`.@@ -88,16 +128,19 @@ impl Covered {     ///     /// Stops once `limit` distinct services have been found, since no caller needs more.     fn tags_over(&self, point: (i32, i32), ux: f64, uy: f64, out: &mut Vec<u32>, limit: usize) {-        let (cx, cy) = cell_of(point);+        self.tags_over_in(cell_of(point), point, ux, uy, out, limit);+    }++    /// [`tags_over`](Self::tags_over) with `cell_of(point)` already known.+    fn tags_over_in(&self, (cx, cy): Cell, point: (i32, i32), ux: f64, uy: f64, out: &mut Vec<u32>, limit: usize) {         for (dx, dy) in NEIGHBOURHOOD {-            let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else { continue };-            for &i in bucket {-                let (other, oux, ouy) = self.points[i as usize];-                if (ux * oux + uy * ouy).abs() < COS_FOLD {+            let Some(bucket) = self.bucket((cx + dx, cy + dy)) else { continue };+            for d in bucket.iter() {+                if (ux * d.ux + uy * d.uy).abs() < COS_FOLD {                     continue;                 }-                if distance_m(point, other) <= CORRIDOR_M {-                    let tag = self.tags[i as usize];+                if distance_m(point, d.point) <= CORRIDOR_M {+                    let tag = d.tag;                     if !out.contains(&tag) {                         out.push(tag);                         if out.len() >= limit {@@ -151,21 +194,132 @@ impl Covered {     /// every sample of every line it draws, and a trunk alignment republished by a dozen feeds is     /// a dozen overlapping sample runs in the same cells.     fn covers(&self, point: (i32, i32), ux: f64, uy: f64) -> bool {-        let (cx, cy) = cell_of(point);+        self.covers_in(cell_of(point), point, ux, uy)+    }++    /// [`covers`](Self::covers) with `cell_of(point)` already known.+    fn covers_in(&self, (cx, cy): Cell, point: (i32, i32), ux: f64, uy: f64) -> bool {         for (dx, dy) in NEIGHBOURHOOD {-            let Some(bucket) = self.cells.get(&(cx + dx, cy + dy)) else { continue };-            for &i in bucket {-                let (other, oux, ouy) = self.points[i as usize];-                if (ux * oux + uy * ouy).abs() < COS_FOLD {+            let Some(bucket) = self.bucket((cx + dx, cy + dy)) else { continue };+            for d in bucket.iter() {+                if (ux * d.ux + uy * d.uy).abs() < COS_FOLD {                     continue;                 }-                if distance_m(point, other) <= CORRIDOR_M {+                if distance_m(point, d.point) <= CORRIDOR_M {                     return true;                 }             }         }         false     }++    /// Is this one walked sample, in `cell` (its [`sample_cell`]), already drawn? The+    /// per-sample half of [`covered_fraction_walked`](Self::covered_fraction_walked), for a+    /// caller that keeps the per-sample answers (see [`sample_cell`] for why that is sound).+    pub fn covers_sample_in(&self, cell: Cell, sample: &Walked) -> bool {+        self.covers_in(cell, sample.0, sample.1, sample.2)+    }++    /// Do at least `limit` distinct services already run over this one sample, in `cell`? The+    /// per-sample half of [`crowd_reaches_walked`](Self::crowd_reaches_walked): that is+    /// exactly "any sample of the line answers true here". `scratch` is reused between calls.+    pub fn crowd_reaches_in(&self, cell: Cell, sample: &Walked, limit: usize, scratch: &mut Vec<u32>) -> bool {+        if limit == 0 {+            return true;+        }+        scratch.clear();+        self.tags_over_in(cell, sample.0, sample.1, sample.2, scratch, limit);+        scratch.len() >= limit+    }++    fn bucket(&self, cell: Cell) -> Option<&Bucket> {+        self.cells[shard_of(cell)].get(&cell)+    }++    /// A mark to pass to [`changed_near`](Self::changed_near) later: how many adds this cover+    /// has taken so far.+    pub fn mark(&self) -> u32 {+        self.adds+    }++    /// Has any sample been added, since `mark` was taken, to a cell a query at `cell` reads?+    ///+    /// Each bucket records the last add that appended to it, so this is the nine bucket probes+    /// a query makes anyway, without the scan. When it is `false`, every+    /// [`covers_sample_in`](Self::covers_sample_in) / [`crowd_reaches_in`](Self::crowd_reaches_in)+    /// answer at `cell` is exactly what it was at `mark`.+    pub fn changed_near(&self, (cx, cy): Cell, mark: u32) -> bool {+        if self.adds == mark {+            return false;+        }+        NEIGHBOURHOOD+            .iter()+            .any(|(dx, dy)| self.bucket((cx + dx, cy + dy)).is_some_and(|b| b.added > mark))+    }+}++/// A multiply-xorshift hasher for the cover's cell maps, probed nine times per query.+///+/// SipHash's flood resistance buys nothing on our own grid coordinates, and nothing iterates+/// either map — every answer is a boolean or a count about one point — so the hasher cannot+/// leak an order into the output.+#[derive(Default, Clone, Copy)]+pub struct CellHasher(u64);++impl std::hash::Hasher for CellHasher {+    fn write(&mut self, bytes: &[u8]) {+        for &b in bytes {+            self.write_u64(u64::from(b));+        }+    }+    fn write_i32(&mut self, v: i32) {+        self.write_u64(u64::from(v as u32));+    }+    fn write_u32(&mut self, v: u32) {+        self.write_u64(u64::from(v));+    }+    fn write_u64(&mut self, v: u64) {+        self.0 = (self.0.rotate_left(26) ^ v).wrapping_mul(0x9E37_79B9_7F4A_7C15);+    }+    fn finish(&self) -> u64 {+        self.0 ^ (self.0 >> 29)+    }+}++/// `BuildHasher` for [`CellHasher`].+pub type CellHash = std::hash::BuildHasherDefault<CellHasher>;++/// Add one sample of `tag` to `cell`'s bucket in `map`, unless the cell already holds one.+fn insert(map: &mut std::collections::HashMap<Cell, Bucket, CellHash>, cell: Cell, (point, ux, uy): Walked, tag: u32, now: u32) {+    let drawn = Drawn { point, ux, uy, tag };+    match map.entry(cell) {+        std::collections::hash_map::Entry::Occupied(mut e) => {+            let bucket = e.get_mut();+            // One representative per cell per service: a second sample of the same service in+            // the same cell cannot change any `covers`/`tags_over` answer, and dropping it is+            // what stops a heavily-republished trunk's buckets growing with the feed count.+            if bucket.iter().any(|d| d.tag == tag) {+                return;+            }+            bucket.rest.push(drawn);+            bucket.added = now;+        }+        std::collections::hash_map::Entry::Vacant(e) => {+            e.insert(Bucket { added: now, first: drawn, rest: Vec::new() });+        }+    }+}++/// The grid cell a walked sample falls in.+///+/// What makes per-sample answers reusable across [`Covered::add`]s: both+/// [`Covered::covers_sample`] and [`Covered::crowd_reaches_at`] read only the 3 x 3 block of+/// cells around this one, and adding a line only ever *appends* samples to the cells its own+/// samples fall in. So an answer computed before some adds is still exact after them unless+/// one of those adds touched that 3 x 3 block — and a `true` stays `true` regardless, since+/// both answers can only grow as samples are appended.+pub fn sample_cell(sample: &Walked) -> Cell {+    cell_of(sample.0) }  /// Every candidate's samples, flat, with the range each candidate's own block occupies.@@ -183,17 +337,19 @@ fn sample_all(candidates: &[Candidate]) -> (Vec<Sample>, Vec<Range<usize>>) {                 .collect()         })         .collect();-    let mut out = Vec::with_capacity(per.iter().map(Vec::len).sum());     let mut blocks = Vec::with_capacity(candidates.len());-    for samples in per {-        let start = out.len();-        out.extend(samples);-        blocks.push(start..out.len());+    let mut start = 0usize;+    for samples in &per {+        blocks.push(start..start + samples.len());+        start += samples.len();     }+    // Concatenated wide too — ~9 GB of samples on a world set. `collect` keeps order.+    let out: Vec<Sample> = per.into_par_iter().flatten_iter().collect();     (out, blocks) } -type Cell = (i32, i32);+/// A grid cell, `(x, y)` in [`CELL_M`] units.+pub type Cell = (i32, i32);  /// The cell a point falls in. Square in metres rather than in degrees, so a cell near the /// pole is not a sliver: longitude is scaled by the cosine of its own latitude.@@ -205,12 +361,6 @@ fn cell_of(point: (i32, i32)) -> Cell {     (x.floor() as i32, y.floor() as i32) } -fn bucket<T: Copy>(grid: &[(Cell, T)], key: Cell) -> &[(Cell, T)] {-    let lo = grid.partition_point(|(k, _)| *k < key);-    let hi = grid.partition_point(|(k, _)| *k <= key);-    &grid[lo..hi]-}- /// A sorted flat `(cell, sample)` vector, as [`crate::index`]'s transfer grid is. struct Grid {     entries: Vec<(Cell, u32)>,@@ -219,7 +369,7 @@ struct Grid { impl Grid {     fn build(samples: &[Sample]) -> Grid {         let mut entries: Vec<(Cell, u32)> =-            samples.iter().enumerate().map(|(i, s)| (cell_of(s.point), i as u32)).collect();+            samples.par_iter().enumerate().map(|(i, s)| (cell_of(s.point), i as u32)).collect();         entries.par_sort_unstable();         Grid { entries }     }@@ -253,19 +403,23 @@ impl Grid {         seen[at.route as usize] = stamp;         let (cx, cy) = cell_of(at.point);         for dx in -1..=1 {-            for dy in -1..=1 {-                for &(_, i) in bucket(&self.entries, (cx + dx, cy + dy)) {-                    let other = &samples[i as usize];-                    if seen[other.route as usize] == stamp {-                        continue;-                    }-                    if (at.ux * other.ux + at.uy * other.uy).abs() < COS_FOLD {-                        continue;-                    }-                    if distance_m(at.point, other.point) <= CORRIDOR_M {-                        seen[other.route as usize] = stamp;-                        out.push(other.route);-                    }+            // The grid is sorted by `(x, y)`, so the three cells `(x, cy - 1..=cy + 1)` are one+            // contiguous run of it, in exactly the order the three per-cell buckets were+            // visited: two binary searches over the whole grid instead of six.+            let x = cx + dx;+            let lo = self.entries.partition_point(|(k, _)| *k < (x, cy - 1));+            let hi = lo + self.entries[lo..].partition_point(|(k, _)| *k <= (x, cy + 1));+            for &(_, i) in &self.entries[lo..hi] {+                let other = &samples[i as usize];+                if seen[other.route as usize] == stamp {+                    continue;+                }+                if (at.ux * other.ux + at.uy * other.uy).abs() < COS_FOLD {+                    continue;+                }+                if distance_m(at.point, other.point) <= CORRIDOR_M {+                    seen[other.route as usize] = stamp;+                    out.push(other.route);                 }             }         }
scripts/maps/gtfs_ingest/src/bundle_part5.rs
diff --git a/scripts/maps/gtfs_ingest/src/bundle_part5.rs b/scripts/maps/gtfs_ingest/src/bundle_part5.rsindex 42a802d199..49e846806e 100644--- a/scripts/maps/gtfs_ingest/src/bundle_part5.rs+++ b/scripts/maps/gtfs_ingest/src/bundle_part5.rs@@ -39,7 +39,7 @@ fn a_shallow_merge() -> Vec<Fixture> { fn corridor_of(points: &[(i32, i32)]) -> Corridor {     let points = canonical(points);     let cum = cumulative(&points);-    Corridor { points, cum, colours: Vec::new() }+    Corridor::new(points, cum, Vec::new()) }  #[cfg(test)]@@ -146,7 +146,7 @@ mod tests_continued {     fn corridor_of(points: &[(i32, i32)]) -> Corridor {         let points = canonical(points);         let cum = cumulative(&points);-        Corridor { points, cum, colours: Vec::new() }+        Corridor::new(points, cum, Vec::new())     }      /// `n` services sharing `metres` of trunk running north and then leaving it in@@ -345,4 +345,55 @@ mod tests_continued {     fn nothing_in_nothing_out() {         assert!(assign(&[]).is_empty());     }++    /// The block-pruned [`nearest`] and [`within`] against the plain walk of every segment they+    /// replaced, over long, kinked, self-approaching references and probes near and far —+    /// including probes exactly on a vertex, where several segments tie.+    #[test]+    fn pruned_nearest_is_the_full_walk_exactly() {+        let full = |c: &Corridor, p: (i32, i32)| -> (f64, f64) {+            let mut best = (f64::INFINITY, 0.0f64);+            for at in 0..c.points.len().saturating_sub(1) {+                let (t, offset) = project(p, c.points[at], c.points[at + 1], 0.0);+                if offset < best.0 {+                    best = (offset, c.cum[at] + t * (c.cum[at + 1] - c.cum[at]));+                }+            }+            best+        };+        let mut x = 0x9E37_79B9_7F4A_7C15u64;+        let mut next = move || {+            x ^= x << 13;+            x ^= x >> 7;+            x ^= x << 17;+            x+        };+        for case in 0..40 {+            let n = [2usize, 3, 33, 64, 65, 500, 3000][case % 7];+            let (mut lat, mut lon) = (600_000_000i32 - (next() % 1_200_000_000) as i32, (next() % 1_000_000_000) as i32);+            let mut points = vec![(lat, lon)];+            for _ in 1..n {+                // Mostly onward, sometimes doubling back, so distant segments come close.+                lat += (next() % 20_001) as i32 - 6_000;+                lon += (next() % 20_001) as i32 - 10_000;+                points.push((lat, lon));+            }+            let c = Corridor::new(points.clone(), cumulative(&points), Vec::new());+            for probe in 0..200 {+                let base = points[(next() % points.len() as u64) as usize];+                let p = if probe % 10 == 0 {+                    base+                } else {+                    let r = [50i32, 500, 5_000, 200_000][probe % 4];+                    (base.0 + (next() % (2 * r as u64 + 1)) as i32 - r, base.1 + (next() % (2 * r as u64 + 1)) as i32 - r)+                };+                let (want, got) = (full(&c, p), nearest(&c, p));+                assert_eq!(want.0.to_bits(), got.0.to_bits(), "distance, case {case} probe {probe}");+                assert_eq!(want.1.to_bits(), got.1.to_bits(), "along, case {case} probe {probe}");+                for radius in [SNAP_M, CORRIDOR_M, 0.0] {+                    assert_eq!(within(&c, p, radius), want.0 <= radius, "case {case} probe {probe} r {radius}");+                }+            }+        }+    } }
scripts/maps/gtfs_ingest/src/reader.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader.rs b/scripts/maps/gtfs_ingest/src/reader.rsindex 34bf7c3b4b..9fc75c63ef 100644--- a/scripts/maps/gtfs_ingest/src/reader.rs+++ b/scripts/maps/gtfs_ingest/src/reader.rs@@ -136,6 +136,37 @@ impl Reader {         Reader::new(buf)     } +    /// Read the pack at `path`, but only the header, the directory and the listed sections.+    ///+    /// For a caller that needs a few hundred MB of a multi-GB pack: `transit_shapes --pack`+    /// reads three sections, and reading the whole 4.4 GB world pack first was most of its+    /// start-up. The buffer is still the file's full length, so every offset means what it+    /// does in [`open`](Self::open), and it is validated identically; the sections not listed+    /// read as zeros and must not be used. The zeroed buffer is allocated untouched, so the+    /// unread sections cost address space, not memory. Listed sections the pack does not have+    /// (a v6 pack has no RAIL_LINES) are skipped, for the accessors to report.+    pub fn open_sections(path: &std::path::Path, sections: &[usize]) -> Result<Reader, String> {+        use std::io::{Read, Seek, SeekFrom};+        let fail = |e: std::io::Error| format!("cannot read {}: {e}", path.display());+        let mut f = std::fs::File::open(path).map_err(fail)?;+        let len = f.metadata().map_err(fail)?.len() as usize;+        let mut buf = vec![0u8; len];+        // Header, then the directory it sizes. `new` re-checks both against the real length.+        let head = HEADER_LEN.min(len);+        f.read_exact(&mut buf[..head]).map_err(fail)?;+        if head == HEADER_LEN {+            let dir_end = (HEADER_LEN + ru32(&buf, 8) as usize * 16).min(len);+            f.read_exact(&mut buf[HEADER_LEN..dir_end]).map_err(fail)?;+        }+        let mut reader = Reader::new(buf)?;+        for &s in sections {+            let Some(&(off, l)) = reader.sec.get(s) else { continue };+            f.seek(SeekFrom::Start(off as u64)).map_err(fail)?;+            f.read_exact(&mut reader.buf[off..off + l]).map_err(fail)?;+        }+        Ok(reader)+    }+     /// The `idx`-th u32 of the header.     fn hdr(&self, idx: usize) -> u32 {         ru32(&self.buf, idx * 4)
scripts/maps/gtfs_ingest/src/reader_extra.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader_extra.rs b/scripts/maps/gtfs_ingest/src/reader_extra.rsindex d314233060..fd0c95f729 100644--- a/scripts/maps/gtfs_ingest/src/reader_extra.rs+++ b/scripts/maps/gtfs_ingest/src/reader_extra.rs@@ -66,7 +66,10 @@ impl crate::reader::Reader {             let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());             String::from_utf8_lossy(&tail[..end]).into_owned()         };+        // Each record decodes on its own; `collect` keeps pack order.+        use rayon::prelude::*;         let out = (0..count)+            .into_par_iter()             .map(|i| {                 let at = recs + i * RAIL_LINE_REC_BYTES;                 let field = |k: usize| ru32(s, at + k * 4);