maps: stream stop_times, shard feeds, and pipeline the pack build
- Commit
555dc9d2732a76b7a63e167fe299a1a39d5a70df- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-26 16:43 UTC (3 months ago)
- Parents
e0cac3b
Diff
scripts/maps/gtfs_ingest/src/bin/transit_stops.rs
diff --git a/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs b/scripts/maps/gtfs_ingest/src/bin/transit_stops.rsindex 6359761a62..6c78178f2f 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs@@ -2,8 +2,8 @@ //! as newline-delimited GeoJSON (geojsonseq), one `Point` per served GTFS stop. //! //! Usage:-//! transit_stops --geojson OUT.geojsonseq <feed>...-//! transit_stops --geojson OUT.geojsonseq --manifest FILE+//! transit_stops --geojson OUT.geojsonseq <feed>... [--threads N]+//! transit_stops --geojson OUT.geojsonseq --manifest FILE [--threads N] //! //! `<feed>` is `feed_name=gtfs_dir[=motis_prefix]` or a bare `gtfs_dir`, exactly //! as `gtfs_ingest` takes them, so the same `feeds.manifest`@@ -26,6 +26,7 @@ use gtfs_ingest::gtfs::{self, Csv}; use gtfs_ingest::manifest::{parse_feed_spec, read_manifest, FeedSpec};+use gtfs_ingest::par; use std::collections::HashMap; use std::io::{BufWriter, Write}; use std::path::{Path, PathBuf};@@ -48,6 +49,20 @@ fn main() -> ExitCode { manifest = args.get(i + 1).map(PathBuf::from); i += 2; }+ "--threads" => {+ let Some(raw) = args.get(i + 1) else {+ eprintln!("transit_stops: --threads needs a value");+ return ExitCode::from(2);+ };+ match par::parse_threads(raw) {+ Ok(n) => par::set_threads(n),+ Err(e) => {+ eprintln!("transit_stops: {e}");+ return ExitCode::from(2);+ }+ }+ i += 2;+ } "-h" | "--help" => { usage(); return ExitCode::SUCCESS;@@ -92,8 +107,8 @@ fn main() -> ExitCode { } fn usage() {- eprintln!("usage: transit_stops --geojson OUT.geojsonseq <feed>...");- eprintln!(" transit_stops --geojson OUT.geojsonseq --manifest FILE");+ eprintln!("usage: transit_stops --geojson OUT.geojsonseq <feed>... [--threads N]");+ eprintln!(" transit_stops --geojson OUT.geojsonseq --manifest FILE [--threads N]"); eprintln!(" <feed> = feed_name=gtfs_dir[=motis_prefix] | gtfs_dir"); } @@ -107,87 +122,147 @@ struct Stop { route_type: u32, } -fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> {- // Dedup key: Transitous ships merged regional feeds (`SF-bayarea`) *and* the- // member agencies (`SFMTA`), so one physical platform appears several times.- // Keying on a coarsened position plus the name collapses those without- // merging genuinely distinct stops: 1e-4 deg is ~11 m, well under the gap- // between the two sides of a street.- let mut seen: HashMap<(i32, i32, String), usize> = HashMap::new();- let mut stops: Vec<Stop> = Vec::new();- let mut total_rows = 0usize;+/// What one feed contributes, before any cross-feed dedup.+struct FeedStops {+ /// Candidates in `stops.txt` order, each with the dedup key already computed.+ candidates: Vec<((i32, i32, String), Stop)>,+ rows: usize,+} - for (name, dir, motis_prefix) in specs {- let require = |file: &str| -> Result<Csv, String> {- gtfs::read_table(dir, file).ok_or_else(|| {- format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())- })- };- let stops_csv = require("stops.txt")?;- let routes_csv = require("routes.txt")?;- let trips_csv = require("trips.txt")?;- let stop_times_csv = require("stop_times.txt")?;- if motis_prefix.is_empty() {- eprintln!(- "transit_stops: warning: feed '{name}' has no MOTIS prefix; its stops \- will carry no motis_id and get no realtime delays"- );- }+/// Read one feed and reduce it to candidates. Pure with respect to every other+/// feed, which is what lets these run concurrently.+fn read_feed(spec: &FeedSpec) -> Result<FeedStops, String> {+ let (name, dir, motis_prefix) = spec;+ let require = |file: &str| -> Result<Csv, String> {+ gtfs::read_table(dir, file).ok_or_else(|| {+ format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())+ })+ };+ let stops_csv = require("stops.txt")?;+ let routes_csv = require("routes.txt")?;+ let trips_csv = require("trips.txt")?;+ if motis_prefix.is_empty() {+ eprintln!(+ "transit_stops: warning: feed '{name}' has no MOTIS prefix; its stops \+ will carry no motis_id and get no realtime delays"+ );+ } - let stop_route_type = derive_stop_modes(&routes_csv, &trips_csv, &stop_times_csv);+ let stop_route_type = derive_stop_modes(&routes_csv, &trips_csv, dir).ok_or_else(|| {+ format!(+ "feed '{name}' ({}) missing required GTFS file: stop_times.txt",+ dir.display()+ )+ })?; - let mut emitted = 0usize;- for row in &stops_csv.rows {- total_rows += 1;- let id = stops_csv.get(row, "stop_id");- if id.is_empty() {- continue;- }- // A stop no trip ever calls at is not boardable, and includes the- // unserved parent stations GTFS feeds carry alongside their platforms.- let Some(&route_type) = stop_route_type.get(id) else { continue };- let Some((lat, lon)) =- gtfs::parse_lat_lon(stops_csv.get(row, "stop_lat"), stops_csv.get(row, "stop_lon"))- else {- continue;- };- let stop_name = stops_csv.get(row, "stop_name").trim();- let motis_id = if motis_prefix.is_empty() {- String::new()- } else {- format!("{motis_prefix}_{id}")- };-- let key = (- (lat * 1e4).round() as i32,- (lon * 1e4).round() as i32,- stop_name.to_lowercase(),- );- let candidate = Stop {+ let mut out = FeedStops {+ candidates: Vec::new(),+ rows: 0,+ };+ for row in &stops_csv.rows {+ out.rows += 1;+ let id = stops_csv.get(row, "stop_id");+ if id.is_empty() {+ continue;+ }+ // A stop no trip ever calls at is not boardable, and includes the+ // unserved parent stations GTFS feeds carry alongside their platforms.+ let Some(&route_type) = stop_route_type.get(id) else { continue };+ let Some((lat, lon)) =+ gtfs::parse_lat_lon(stops_csv.get(row, "stop_lat"), stops_csv.get(row, "stop_lon"))+ else {+ continue;+ };+ let stop_name = stops_csv.get(row, "stop_name").trim();+ let motis_id = if motis_prefix.is_empty() {+ String::new()+ } else {+ format!("{motis_prefix}_{id}")+ };++ // Dedup key: Transitous ships merged regional feeds (`SF-bayarea`) *and* the+ // member agencies (`SFMTA`), so one physical platform appears several times.+ // Keying on a coarsened position plus the name collapses those without+ // merging genuinely distinct stops: 1e-4 deg is ~11 m, well under the gap+ // between the two sides of a street.+ let key = (+ (lat * 1e4).round() as i32,+ (lon * 1e4).round() as i32,+ stop_name.to_lowercase(),+ );+ out.candidates.push((+ key,+ Stop { lat_e7: (lat * 1e7).round() as i32, lon_e7: (lon * 1e7).round() as i32, name: stop_name.to_string(), motis_id, route_type,- };- match seen.get(&key) {- // Prefer the duplicate we can name in MOTIS's id space, so the- // surviving pin is the one that can fetch live departures.- Some(&existing) => {- let keep = stops[existing].motis_id.is_empty()- && !candidate.motis_id.is_empty();- if keep {- stops[existing] = candidate;+ },+ ));+ }+ Ok(out)+}++fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> {+ let mut seen: HashMap<(i32, i32, String), usize> = HashMap::new();+ let mut stops: Vec<Stop> = Vec::new();+ let mut total_rows = 0usize;++ // Feeds are read concurrently, in batches, and merged serially in SPEC ORDER.+ //+ // Per-feed reading is the cost — parsing stops/routes/trips and streaming+ // stop_times — and it touches no cross-feed state. The merge is the opposite: the+ // first-wins-then-upgrade rule below is order-dependent, so replaying it in spec+ // order is what keeps the output byte-identical however the reads interleave.+ //+ // A batch at a time rather than all feeds at once, because a batch is what bounds+ // live memory: a world build has hundreds of feeds and holding every feed's+ // candidates would trade the peak this change exists to protect.+ let batch = par::threads().max(1);+ for chunk in specs.chunks(batch) {+ let read: Vec<Result<FeedStops, String>> = if chunk.len() == 1 {+ vec![read_feed(&chunk[0])]+ } else {+ std::thread::scope(|scope| {+ let handles: Vec<_> = chunk+ .iter()+ .map(|spec| scope.spawn(|| read_feed(spec)))+ .collect();+ handles+ .into_iter()+ .map(|h| {+ h.join()+ .unwrap_or_else(|_| Err("a feed reader panicked".to_string()))+ })+ .collect()+ })+ };++ for (spec, feed) in chunk.iter().zip(read) {+ let feed = feed?;+ total_rows += feed.rows;+ let mut emitted = 0usize;+ for (key, candidate) in feed.candidates {+ match seen.get(&key) {+ // Prefer the duplicate we can name in MOTIS's id space, so the+ // surviving pin is the one that can fetch live departures.+ Some(&existing) => {+ let keep = stops[existing].motis_id.is_empty()+ && !candidate.motis_id.is_empty();+ if keep {+ stops[existing] = candidate;+ }+ }+ None => {+ seen.insert(key, stops.len());+ stops.push(candidate);+ emitted += 1; }- }- None => {- seen.insert(key, stops.len());- stops.push(candidate);- emitted += 1; } }+ eprintln!("transit_stops: feed '{}': {emitted} new stop(s)", spec.0); }- eprintln!("transit_stops: feed '{name}': {emitted} new stop(s)"); } // Deterministic output, so a rebuild produces a byte-identical layer and the@@ -239,7 +314,26 @@ fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> { /// /// GTFS has no stop->route table, so it is recovered through /// `stop_times` -> `trips` -> `routes`.-fn derive_stop_modes(routes: &Csv, trips: &Csv, stop_times: &Csv) -> HashMap<String, u32> {+///+/// `stop_times.txt` is **streamed**, not read into a `Csv`. It is the largest file+/// in almost every feed — 5.8 GB for `great_britain`, and 52 GB once materialised as+/// `Vec<Vec<String>>` — while all this needs from a row is two borrowed strs. Doing+/// it the other way was what made sharding feeds across threads impossible: peak+/// memory would have multiplied by the thread count.+///+/// `None` only when `stop_times.txt` is absent, which the caller reports as a+/// missing required file.+fn derive_stop_modes(routes: &Csv, trips: &Csv, dir: &Path) -> Option<HashMap<String, u32>> {+ let trip_type = trip_modes(routes, trips);+ let mut out: HashMap<String, u32> = HashMap::new();+ gtfs::stream_stop_times(dir, |r| {+ fold_stop_mode(&mut out, &trip_type, r.trip_id, r.stop_id);+ })?;+ Some(out)+}++/// `trip_id` -> normalized route type, for every trip whose route is known.+fn trip_modes<'a>(routes: &'a Csv, trips: &'a Csv) -> HashMap<&'a str, u32> { let mut route_type: HashMap<&str, u32> = HashMap::new(); for row in &routes.rows { let id = routes.get(row, "route_id");@@ -260,22 +354,27 @@ fn derive_stop_modes(routes: &Csv, trips: &Csv, stop_times: &Csv) -> HashMap<Str trip_type.insert(id, rt); } }+ trip_type+} - let mut out: HashMap<String, u32> = HashMap::new();- for row in &stop_times.rows {- let stop_id = stop_times.get(row, "stop_id");- if stop_id.is_empty() {- continue;- }- let Some(&rt) = trip_type.get(stop_times.get(row, "trip_id")) else { continue };- match out.get(stop_id) {- Some(&existing) if mode_rank(existing) <= mode_rank(rt) => {}- _ => {- out.insert(stop_id.to_string(), rt);- }+/// Fold one `stop_times` row into the per-stop mode map, keeping the most prominent+/// mode. Order-independent: [`mode_rank`] decides, not arrival order.+fn fold_stop_mode(+ out: &mut HashMap<String, u32>,+ trip_type: &HashMap<&str, u32>,+ trip_id: &str,+ stop_id: &str,+) {+ if stop_id.is_empty() {+ return;+ }+ let Some(&rt) = trip_type.get(trip_id) else { return };+ match out.get(stop_id) {+ Some(&existing) if mode_rank(existing) <= mode_rank(rt) => {}+ _ => {+ out.insert(stop_id.to_string(), rt); } }- out } /// Fold GTFS's extended route types (the 100-1799 ranges) onto the basic set, so@@ -346,6 +445,25 @@ mod tests { use super::*; use gtfs_ingest::gtfs::parse_csv; + /// The mode fold driven from a parsed `stop_times` table.+ ///+ /// The production path streams the file instead, but both go through+ /// [`trip_modes`] and [`fold_stop_mode`], so this exercises the same decisions+ /// without a 5.8 GB fixture on disk.+ fn derive_from_csv(routes: &Csv, trips: &Csv, stop_times: &Csv) -> HashMap<String, u32> {+ let trip_type = trip_modes(routes, trips);+ let mut out = HashMap::new();+ for row in &stop_times.rows {+ fold_stop_mode(+ &mut out,+ &trip_type,+ stop_times.get(row, "trip_id"),+ stop_times.get(row, "stop_id"),+ );+ }+ out+ }+ #[test] fn extended_route_types_fold_onto_the_basic_set() { assert_eq!(normalize_route_type(3), 3, "plain bus is unchanged");@@ -375,7 +493,7 @@ mod tests { TS,SHARED,1\n\ TB,BUSONLY,2\n", );- let modes = derive_stop_modes(&routes, &trips, &stop_times);+ let modes = derive_from_csv(&routes, &trips, &stop_times); assert_eq!(modes.get("SHARED"), Some(&1), "subway wins over bus"); assert_eq!(modes.get("BUSONLY"), Some(&3)); }@@ -385,13 +503,91 @@ mod tests { let routes = parse_csv("route_id,route_type\nR,3\n"); let trips = parse_csv("route_id,trip_id\nR,T\n"); let stop_times = parse_csv("trip_id,stop_id,stop_sequence\nT,A,1\n");- let modes = derive_stop_modes(&routes, &trips, &stop_times);+ let modes = derive_from_csv(&routes, &trips, &stop_times); // A parent station or orphan row no trip calls at is absent, which is what // keeps it out of the layer. assert_eq!(modes.get("STATION"), None); assert_eq!(modes.get("A"), Some(&3)); } + /// Sharding feeds across threads must change nothing.+ ///+ /// The fixture is built so the merge is genuinely order-sensitive: two feeds carry+ /// the SAME physical stop and BOTH have a MOTIS prefix, so the first-wins rule+ /// decides between them and only spec order can break the tie. With one prefixed+ /// feed the rule converges regardless of order, and the test would pass even if+ /// the merge were replayed in completion order — proving nothing.+ #[test]+ fn sharding_feeds_across_threads_changes_no_bytes() {+ let root = std::env::temp_dir().join(format!("gtfs_shard_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);++ // Every feed has one shared platform — same name AND same position, so the+ // dedup key really collides — plus one stop of its own.+ let write_feed = |tag: &str| -> PathBuf {+ let dir = root.join(tag);+ std::fs::create_dir_all(&dir).unwrap();+ let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();+ w("routes.txt", "route_id,route_type\nR1,3\nR2,1\n".to_string());+ w("trips.txt", "route_id,trip_id\nR1,T1\nR2,T2\n".to_string());+ w(+ "stops.txt",+ format!(+ "stop_id,stop_name,stop_lat,stop_lon\n\+ SHARED,Shared Platform,37.7749000,-122.4194000\n\+ OWN{tag},Own {tag},37.8{},-122.3{}\n",+ tag.len(),+ tag.len()+ ),+ );+ w(+ "stop_times.txt",+ format!(+ "trip_id,stop_id,stop_sequence,arrival_time,departure_time\n\+ T1,SHARED,1,08:00:00,08:00:00\n\+ T2,OWN{tag},1,09:00:00,09:00:00\n"+ ),+ );+ dir+ };++ // Seven feeds, so 2- and 3-thread batches both straddle a boundary. Feeds a+ // and b both carry a prefix, so which of them wins SHARED depends on order.+ let specs: Vec<FeedSpec> = ["a", "b", "c", "d", "e", "f", "g"]+ .iter()+ .map(|t| (t.to_string(), write_feed(t), format!("p{t}")))+ .collect();++ let run_at = |n: usize| -> Vec<u8> {+ par::set_threads(n);+ let out = root.join(format!("stops.t{n}.geojsonseq"));+ run(&out, &specs).unwrap();+ std::fs::read(&out).unwrap()+ };++ let base = run_at(1);+ assert!(!base.is_empty(), "the fixture produced no stops");+ // The shared platform survives exactly once, and it is the FIRST feed's.+ let text = String::from_utf8(base.clone()).unwrap();+ assert_eq!(+ text.matches("Shared Platform").count(),+ 1,+ "the shared stop must dedup to one feature: {text}"+ );+ assert!(+ text.contains("\"pa_SHARED\""),+ "feed 'a' comes first in spec order, so its id must survive: {text}"+ );+ for n in [2, 3, 7, 32] {+ assert!(+ run_at(n) == base,+ "{n} threads perturbed the layer"+ );+ }+ par::clear_threads();+ let _ = std::fs::remove_dir_all(&root);+ }+ #[test] fn json_escaping_covers_quotes_and_controls() { let mut out = Vec::new();
scripts/maps/gtfs_ingest/src/lib.rs
diff --git a/scripts/maps/gtfs_ingest/src/lib.rs b/scripts/maps/gtfs_ingest/src/lib.rsindex 71e6ee9baa..d432602109 100644--- a/scripts/maps/gtfs_ingest/src/lib.rs+++ b/scripts/maps/gtfs_ingest/src/lib.rs@@ -14,6 +14,7 @@ pub mod gtfs; pub mod index; pub mod json; pub mod manifest;+pub mod par; pub mod reader; pub mod registry; pub mod shapes;
scripts/maps/gtfs_ingest/src/main.rs
diff --git a/scripts/maps/gtfs_ingest/src/main.rs b/scripts/maps/gtfs_ingest/src/main.rsindex 8644959b2d..4382eb8d9e 100644--- a/scripts/maps/gtfs_ingest/src/main.rs+++ b/scripts/maps/gtfs_ingest/src/main.rs@@ -95,69 +95,87 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String .map_err(|e| format!("cannot create {}: {e}", index_path.display()))?; let mut writer = std::io::BufWriter::new(file); - // One feed at a time, each dropped before the next is read. Parsing all of- // them up front is what made a world build need ~400 GB: a feed's tables cost- // several times the feed on disk, and the builder only needs one feed's worth- // at once.+ // Ingestion stays SERIAL and is overlapped with reading the next feed.+ //+ // `IndexBuilder` is one giant cross-feed accumulator — `StringPool::intern` hands+ // back a byte offset that is written straight into section payloads, and+ // `ROUTE_TRIPS` encodes `headsign_off` as a uvarint inside a varint stream — so+ // sharding it would mean remapping every offset and re-encoding every trip list.+ // Parsing CSV is the CPU cost; ingesting is pointer-shuffling. Overlapping the two+ // gets most of the win for none of that risk and needs no format change.+ //+ // Depth ONE, deliberately. The comment above is the reason: a feed's tables cost+ // several times the feed on disk, and parsing every feed up front is what made a+ // world build need ~400 GB. One feed queued plus one being parsed plus one being+ // ingested is three resident, and three is the most this is willing to spend+ // without a measurement on real feeds to justify more. let mut builder = index::IndexBuilder::new(pack_name);- for (n, (name, dir, motis_prefix)) in specs.iter().enumerate() {- let require = |file: &str| -> Result<gtfs::Csv, String> {- gtfs::read_table(dir, file).ok_or_else(|| {- format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())- })- };- let stops = require("stops.txt")?;- let routes = require("routes.txt")?;- let trips = require("trips.txt")?;- let calendar = gtfs::read_table(dir, "calendar.txt");- let calendar_dates = gtfs::read_table(dir, "calendar_dates.txt");- let agency = gtfs::read_table(dir, "agency.txt");- let shapes = gtfs::read_shapes(dir);- if shapes.is_none() {- eprintln!(- "gtfs_ingest: warning: feed '{name}' has no shapes.txt; its ride legs \- will draw stop-to-stop"- );- }- if calendar.is_none() && calendar_dates.is_none() {- eprintln!(- "gtfs_ingest: warning: feed '{name}' has no calendar.txt or \- calendar_dates.txt; its services will never be scheduled"- );- }- // Without a timezone the device falls back to its own, which is wrong- // for any feed outside the user's zone.- if agency.as_ref().is_none_or(|a| {- a.rows.first().is_none_or(|row| a.get(row, "agency_timezone").trim().is_empty())- }) {+ let (tx, rx) = std::sync::mpsc::sync_channel::<Result<Loaded, String>>(1);+ let total = specs.len();+ let result: Result<(), String> = std::thread::scope(|scope| {+ scope.spawn(move || {+ for spec in specs {+ // A send failure means the consumer stopped, which happens only when+ // it is already returning an error of its own.+ if tx.send(load_feed(spec)).is_err() {+ return;+ }+ }+ });++ for (n, loaded) in rx.iter().enumerate() {+ let f = loaded?;+ if f.shapes.is_none() {+ eprintln!(+ "gtfs_ingest: warning: feed '{}' has no shapes.txt; its ride legs \+ will draw stop-to-stop",+ f.name+ );+ }+ if f.calendar.is_none() && f.calendar_dates.is_none() {+ eprintln!(+ "gtfs_ingest: warning: feed '{}' has no calendar.txt or \+ calendar_dates.txt; its services will never be scheduled",+ f.name+ );+ }+ // Without a timezone the device falls back to its own, which is wrong+ // for any feed outside the user's zone.+ if f.agency.as_ref().is_none_or(|a| {+ a.rows.first().is_none_or(|row| a.get(row, "agency_timezone").trim().is_empty())+ }) {+ eprintln!(+ "gtfs_ingest: warning: feed '{}' has no agency_timezone; \+ the device will route it in its own local time",+ f.name+ );+ }+ builder.add_feed_dir(&FeedDir {+ name: f.name.clone(),+ motis_prefix: f.motis_prefix.clone(),+ dir: &f.dir,+ stops: &f.stops,+ routes: &f.routes,+ trips: &f.trips,+ calendar: f.calendar.as_ref(),+ calendar_dates: f.calendar_dates.as_ref(),+ agency: f.agency.as_ref(),+ shapes: f.shapes.as_ref(),+ })?;+ // Per feed, so a regression in the size or count curve shows at feed 200+ // rather than at hour six.+ let (stops_so_far, routes_so_far, trips_so_far) = builder.counts(); eprintln!(- "gtfs_ingest: warning: feed '{name}' has no agency_timezone; \- the device will route it in its own local time"+ "gtfs_ingest: [{}/{total}] {}: {:.1} MiB of sections, {stops_so_far} stops, \+ {routes_so_far} routes, {trips_so_far} trips",+ n + 1,+ f.name,+ builder.section_bytes() as f64 / (1024.0 * 1024.0), ); }- builder.add_feed_dir(&FeedDir {- name: name.clone(),- motis_prefix: motis_prefix.clone(),- dir,- stops: &stops,- routes: &routes,- trips: &trips,- calendar: calendar.as_ref(),- calendar_dates: calendar_dates.as_ref(),- agency: agency.as_ref(),- shapes: shapes.as_ref(),- })?;- // Per feed, so a regression in the size or count curve shows at feed 200- // rather than at hour six.- let (stops_so_far, routes_so_far, trips_so_far) = builder.counts();- eprintln!(- "gtfs_ingest: [{}/{}] {name}: {:.1} MiB of sections, {stops_so_far} stops, \- {routes_so_far} routes, {trips_so_far} trips",- n + 1,- specs.len(),- builder.section_bytes() as f64 / (1024.0 * 1024.0),- );- }+ Ok(())+ });+ result?; let stats = builder.finish_to(&mut writer)?; writer@@ -235,6 +253,48 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String Ok(()) } +/// One feed's tables, read off disk and owned.+///+/// Exists so reading can happen on a different thread from ingesting: [`FeedDir`]+/// borrows, and a borrow cannot cross the channel that carries the feed to the+/// builder.+struct Loaded {+ name: String,+ motis_prefix: String,+ dir: PathBuf,+ stops: gtfs::Csv,+ routes: gtfs::Csv,+ trips: gtfs::Csv,+ calendar: Option<gtfs::Csv>,+ calendar_dates: Option<gtfs::Csv>,+ agency: Option<gtfs::Csv>,+ shapes: Option<std::collections::HashMap<String, gtfs::Shape>>,+}++/// Read one feed's tables. `stop_times.txt` is NOT read here — `add_feed_dir`+/// streams it from `dir`, which is why the prefetch does not carry the largest file+/// in the feed and why its memory cost is bounded by the smaller tables.+fn load_feed(spec: &FeedSpec) -> Result<Loaded, String> {+ let (name, dir, motis_prefix) = spec;+ let require = |file: &str| -> Result<gtfs::Csv, String> {+ gtfs::read_table(dir, file).ok_or_else(|| {+ format!("feed '{name}' ({}) missing required GTFS file: {file}", dir.display())+ })+ };+ Ok(Loaded {+ name: name.clone(),+ motis_prefix: motis_prefix.clone(),+ dir: dir.clone(),+ stops: require("stops.txt")?,+ routes: require("routes.txt")?,+ trips: require("trips.txt")?,+ calendar: gtfs::read_table(dir, "calendar.txt"),+ calendar_dates: gtfs::read_table(dir, "calendar_dates.txt"),+ agency: gtfs::read_table(dir, "agency.txt"),+ shapes: gtfs::read_shapes(dir),+ })+}+ /// Minimal JSON string escaper for the manifest. fn json_str(s: &str) -> String { let mut out = String::with_capacity(s.len() + 2);@@ -253,3 +313,64 @@ fn json_str(s: &str) -> String { out.push('"'); out }++#[cfg(test)]+mod tests {+ use super::*;++ /// A minimal but complete GTFS feed, distinct per tag.+ fn write_feed(root: &Path, tag: &str) -> PathBuf {+ let dir = root.join(tag);+ std::fs::create_dir_all(&dir).unwrap();+ let w = |file: &str, body: String| std::fs::write(dir.join(file), body).unwrap();+ w("agency.txt", format!("agency_id,agency_name,agency_timezone\nA{tag},Agency {tag},America/Los_Angeles\n"));+ w("routes.txt", format!("route_id,agency_id,route_short_name,route_type\nR{tag},A{tag},{tag}1,3\n"));+ w("trips.txt", format!("route_id,service_id,trip_id,trip_headsign\nR{tag},S{tag},T{tag},To {tag}\n"));+ w("calendar.txt", format!("service_id,monday,tuesday,wednesday,thursday,friday,saturday,sunday,start_date,end_date\nS{tag},1,1,1,1,1,1,1,20260101,20271231\n"));+ w("stops.txt", format!("stop_id,stop_name,stop_lat,stop_lon\nS{tag}1,Stop {tag} One,37.7{},-122.4{}\nS{tag}2,Stop {tag} Two,37.8{},-122.3{}\n", tag.len(), tag.len(), tag.len(), tag.len()));+ w("stop_times.txt", format!("trip_id,arrival_time,departure_time,stop_id,stop_sequence\nT{tag},08:00:00,08:00:00,S{tag}1,1\nT{tag},08:10:00,08:10:00,S{tag}2,2\n"));+ dir+ }++ /// The pack must depend on feed ORDER and nothing else.+ ///+ /// Reading is pipelined onto another thread while `IndexBuilder` ingests, so the+ /// thing that could break is the order `add_feed_dir` sees. Two assertions pin it:+ /// the same specs twice must be byte-identical (the pipeline is deterministic), and+ /// reversed specs must NOT be (order genuinely decides the string-pool offsets, so+ /// the first assertion is not passing for trivial reasons).+ #[test]+ fn the_pack_is_deterministic_and_order_sensitive() {+ let root = std::env::temp_dir().join(format!("gtfs_pack_{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&root);+ let dirs: Vec<PathBuf> = ["a", "bb", "ccc", "dddd", "eeeee"]+ .iter()+ .map(|t| write_feed(&root, t))+ .collect();+ let specs: Vec<FeedSpec> = ["a", "bb", "ccc", "dddd", "eeeee"]+ .iter()+ .zip(&dirs)+ .map(|(t, d)| (t.to_string(), d.clone(), format!("p{t}")))+ .collect();++ let build = |name: &str, specs: &[FeedSpec]| -> Vec<u8> {+ let out = root.join(name);+ run(&out, "world", specs).unwrap();+ std::fs::read(out.join("world.transit")).unwrap()+ };++ let once = build("one", &specs);+ let twice = build("two", &specs);+ assert!(once == twice, "the pipelined pack build is not deterministic");++ let mut reversed = specs.clone();+ reversed.reverse();+ let backwards = build("rev", &reversed);+ assert!(+ backwards != once,+ "feed order does not affect the pack, so the determinism check above \+ proves nothing about ordering"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+}\ No newline at end of file
scripts/maps/gtfs_ingest/src/par.rs
diff --git a/scripts/maps/gtfs_ingest/src/par.rs b/scripts/maps/gtfs_ingest/src/par.rsnew file mode 100644index 0000000000..87c79ee6c4--- /dev/null+++ b/scripts/maps/gtfs_ingest/src/par.rs@@ -0,0 +1,105 @@+//! The thread budget.+//!+//! Spelled the same way `osm_ingest::par` and `tile_build::par` spell it, so one+//! `MAPS_THREADS` export governs a whole build and the fan-out in `build_all.sh`+//! does not oversubscribe the box. `available_parallelism()` reports the whole+//! machine to every process, so six concurrent tools each claiming 32 threads on a+//! 32-core box finish slower than running in sequence.+//!+//! Unlike the other two crates this one has **no rayon**, and deliberately: this+//! crate's documented property is zero external dependencies, and its parallel work+//! is a handful of whole GTFS feeds per batch rather than millions of tiny items.+//! One `std::thread::scope` per batch is all that shape needs; work stealing would+//! buy nothing.++use std::sync::atomic::{AtomicUsize, Ordering};++/// 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 from `main` after parsing.+pub fn set_threads(n: usize) {+ OVERRIDE.store(n.max(1), Ordering::Relaxed);+}++/// Drop the override again, restoring the `MAPS_THREADS`-or-the-box default.+///+/// Not `#[cfg(test)]`: the binaries in this crate are separate compilation units, so+/// a test in `transit_stops` cannot see the library's test-only items.+pub fn clear_threads() {+ OVERRIDE.store(0, Ordering::Relaxed);+}++/// Threads to use. `--threads` beats `MAPS_THREADS` beats the box.+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 build+/// over a typo in an environment variable serves nobody.+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.+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}"))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[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);+ 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");+ }+}