Modern Apps git

← Modern-Apps.git

gtfs_ingest: drop stops whose coordinates cannot be represented

Commit
fc1b6257c6d46582c8ca2be6839a5ba1c061b1ea
Author
vayun-mathur <[email protected]>
When
2026-08-21 23:01 UTC (3 months ago)
Parents
3f5a2a0

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 91577307da..6359761a62 100644--- a/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs+++ b/scripts/maps/gtfs_ingest/src/bin/transit_stops.rs@@ -146,17 +146,11 @@ fn run(geojson: &Path, specs: &[FeedSpec]) -> Result<(), String> {             // 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 lat: f64 = match stops_csv.get(row, "stop_lat").trim().parse() {-                Ok(v) => v,-                Err(_) => continue,-            };-            let lon: f64 = match stops_csv.get(row, "stop_lon").trim().parse() {-                Ok(v) => v,-                Err(_) => continue,-            };-            if !lat.is_finite() || !lon.is_finite() {+            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()
scripts/maps/gtfs_ingest/src/gtfs.rs
diff --git a/scripts/maps/gtfs_ingest/src/gtfs.rs b/scripts/maps/gtfs_ingest/src/gtfs.rsindex 6fd3ffe7e8..66e46a6bd8 100644--- a/scripts/maps/gtfs_ingest/src/gtfs.rs+++ b/scripts/maps/gtfs_ingest/src/gtfs.rs@@ -132,6 +132,29 @@ pub fn parse_gtfs_date(s: &str) -> Option<u32> {     s.parse().ok() } +/// Parse a `stop_lat`/`stop_lon` pair, rejecting anything that is not a finite+/// coordinate inside the WGS84 ranges.+///+/// The range check is not pedantry: `(lat * 1e7) as i32` **saturates**, so a feed+/// with `stop_lat = 500` yields `i32::MAX` rather than an error. One such row sets+/// a whole pack's bbox to `i32::MAX`, at which point the device's `covers()` adds+/// its 5.5 km margin to that, overflows, and concludes the pack covers *nothing*.+/// A single bad stop in one of 1272 feeds could therefore disable transit routing+/// for the entire pack.+///+/// Returns degrees, not `e7`, because callers disagree on rounding — the index+/// truncates and `transit_stops` rounds — and neither may change.+pub fn parse_lat_lon(lat: &str, lon: &str) -> Option<(f64, f64)> {+    let lat: f64 = lat.trim().parse().ok()?;+    let lon: f64 = lon.trim().parse().ok()?;+    // A range `contains` is false for NaN and for both infinities, so this+    // subsumes the finiteness check.+    if !(-90.0..=90.0).contains(&lat) || !(-180.0..=180.0).contains(&lon) {+        return None;+    }+    Some((lat, lon))+}+ /// GTFS lets a `stop_times.txt` row give only one of arrival/departure; the /// missing one means "no dwell here". A row with neither is unusable. pub fn stop_time_pair(arrival: &str, departure: &str) -> Option<(u32, u32)> {@@ -336,13 +359,8 @@ pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {         if id.is_empty() {             continue;         }-        let lat: f64 = match get(c_lat).parse() {-            Ok(v) => v,-            Err(_) => continue,-        };-        let lon: f64 = match get(c_lon).parse() {-            Ok(v) => v,-            Err(_) => continue,+        let Some((lat, lon)) = parse_lat_lon(get(c_lat), get(c_lon)) else {+            continue;         };         let seq: u32 = get(c_seq).parse().unwrap_or(0);         let dist = c_dist.map_or(f64::NAN, |i| get(i).parse().unwrap_or(f64::NAN));@@ -378,6 +396,33 @@ pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> { mod tests {     use super::*; +    /// A coordinate outside the WGS84 ranges must be rejected, not cast: the cast+    /// saturates, so one bad row would put `i32::MAX` in the pack's bbox and the+    /// device's `covers()` would then overflow its margin and match nothing.+    #[test]+    fn an_out_of_range_coordinate_is_rejected_rather_than_saturated() {+        assert_eq!(parse_lat_lon("37.7", "-122.4"), Some((37.7, -122.4)));+        assert_eq!(parse_lat_lon(" 37.7 ", " -122.4 "), Some((37.7, -122.4)));+        assert_eq!(parse_lat_lon("-90", "180"), Some((-90.0, 180.0)));+        for (lat, lon) in [+            ("500", "0"),+            ("0", "500"),+            ("-91", "0"),+            ("0", "180.5"),+            ("nan", "0"),+            ("inf", "0"),+            ("", "0"),+            ("abc", "0"),+        ] {+            assert_eq!(parse_lat_lon(lat, lon), None, "{lat},{lon} must not be accepted");+        }+        // Why rejecting matters: past ~±214 degrees the e7 cast saturates instead+        // of wrapping, so the bad value lands in the bbox as the largest possible+        // one. (A value like -91 stays in range for an i32 — still nonsense, but+        // it is the saturating case that breaks the device.)+        assert_eq!((500.0f64 * 1e7) as i32, i32::MAX);+    }+     /// The `shapes.txt` intermediate is one of the two structures a world build     /// has billions of, so its size is part of the contract, not an accident.     #[test]
scripts/maps/gtfs_ingest/src/index.rs
diff --git a/scripts/maps/gtfs_ingest/src/index.rs b/scripts/maps/gtfs_ingest/src/index.rsindex 316c70c515..378500695b 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -461,6 +461,10 @@ pub struct BuildStats {     pub multi_shape_routes: usize,     /// Routes whose shape failed validation and fell back to stop-to-stop.     pub dropped_shape_routes: usize,+    /// Stops dropped because `stop_lat`/`stop_lon` was missing, unparseable or+    /// outside the WGS84 ranges. A non-zero count is a data-quality signal, not+    /// a build error.+    pub dropped_stops_bad_coord: usize, }  fn append_u32(v: &mut Vec<u8>, x: u32) {@@ -606,6 +610,7 @@ pub struct IndexBuilder {     shaped_routes: usize,     multi_shape_routes: usize,     dropped_shape_routes: usize,+    dropped_stops_bad_coord: usize, }  impl IndexBuilder {@@ -649,6 +654,7 @@ impl IndexBuilder {             shaped_routes: 0,             multi_shape_routes: 0,             dropped_shape_routes: 0,+            dropped_stops_bad_coord: 0,         }     } @@ -720,11 +726,14 @@ impl IndexBuilder {             if id.is_empty() {                 continue;             }-            let lat: f64 = feed.stops.get(row, "stop_lat").trim().parse().unwrap_or(f64::NAN);-            let lon: f64 = feed.stops.get(row, "stop_lon").trim().parse().unwrap_or(f64::NAN);-            if lat.is_nan() || lon.is_nan() {+            // Out-of-range coordinates are dropped, not clamped: see+            // `gtfs::parse_lat_lon` for what one bad row does to the bbox.+            let Some((lat, lon)) =+                gtfs::parse_lat_lon(feed.stops.get(row, "stop_lat"), feed.stops.get(row, "stop_lon"))+            else {+                self.dropped_stops_bad_coord += 1;                 continue;-            }+            };             let lat_e7 = (lat * 1e7) as i32;             let lon_e7 = (lon * 1e7) as i32;             let name = feed.stops.get(row, "stop_name");@@ -1166,6 +1175,7 @@ impl IndexBuilder {             shaped_routes,             multi_shape_routes,             dropped_shape_routes,+            dropped_stops_bad_coord,         } = self;         let stop_count = stop_lat.len();         if stop_count == 0 {@@ -1461,6 +1471,7 @@ impl IndexBuilder {             shaped_routes,             multi_shape_routes,             dropped_shape_routes,+            dropped_stops_bad_coord,         })     } 
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 f00d1ebd39..8644959b2d 100644--- a/scripts/maps/gtfs_ingest/src/main.rs+++ b/scripts/maps/gtfs_ingest/src/main.rs@@ -180,6 +180,7 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String          \"routes\": {routes},\n  \"trips\": {trips},\n  \"profiles\": {profiles},\n  \          \"transfers\": {transfers},\n  \"shaped_routes\": {shaped},\n  \          \"dropped_shape_routes\": {dropped},\n  \+         \"dropped_stops_bad_coord\": {bad_coord},\n  \          \"bbox_e7\": [{min_lat}, {min_lon}, {max_lat}, {max_lon}],\n  \          \"section_bytes\": {{\n{sections}\n  }}\n}}\n",         pack = json_str(pack_name),@@ -194,6 +195,7 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String         transfers = stats.transfers,         shaped = stats.shaped_routes,         dropped = stats.dropped_shape_routes,+        bad_coord = stats.dropped_stops_bad_coord,         min_lat = stats.min_lat_e7,         min_lon = stats.min_lon_e7,         max_lat = stats.max_lat_e7,@@ -221,6 +223,15 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String          {} with more than one shape_id",         stats.shaped_routes, stats.routes, stats.dropped_shape_routes, stats.multi_shape_routes,     );+    if stats.dropped_stops_bad_coord > 0 {+        // Loud, because a coordinate outside the WGS84 ranges would otherwise+        // saturate into the bbox and break the device's coverage test.+        eprintln!(+            "gtfs_ingest: warning: dropped {} stops with a missing or out-of-range \+             stop_lat/stop_lon",+            stats.dropped_stops_bad_coord,+        );+    }     Ok(()) }