Modern Apps git

← Modern-Apps.git

gtfs_ingest: stream stop_times.txt and build one feed at a time

Commit
b3dfce3560c9f19dcf213a4765714906c00fe923
Author
vayun-mathur <[email protected]>
When
2026-08-21 21:07 UTC (3 months ago)
Parents
4753d09

Diff

maps/src/main/rust/test_fixtures/mini.transit
diff --git a/maps/src/main/rust/test_fixtures/mini.transit b/maps/src/main/rust/test_fixtures/mini.transitindex 9ae7ba0b3b..1a16111007 100644Binary files a/maps/src/main/rust/test_fixtures/mini.transit and b/maps/src/main/rust/test_fixtures/mini.transit differ
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 b198e48647..506ca381f4 100644--- a/scripts/maps/gtfs_ingest/src/gtfs.rs+++ b/scripts/maps/gtfs_ingest/src/gtfs.rs@@ -6,9 +6,9 @@ //! GTFS is CSV text; times may exceed 24:00:00 (legal, means "after service //! midnight"). We keep everything in seconds-since-service-midnight. //!-//! `shapes.txt` gets its own streaming loader rather than a [`Csv`]: it is often-//! the largest file in a feed, and a `Csv` would hold every coordinate as a-//! `String`.+//! `stop_times.txt` and `shapes.txt` get streaming loaders rather than a [`Csv`]:+//! they are the two largest files in a feed, and a `Csv` would hold every+//! coordinate and every time as a `String`.  use std::collections::HashMap; use std::io::BufRead;@@ -131,13 +131,26 @@ pub fn parse_gtfs_date(s: &str) -> Option<u32> {     s.parse().ok() } +/// 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)> {+    match (parse_gtfs_time(arrival), parse_gtfs_time(departure)) {+        (Some(a), Some(d)) => Some((a, d)),+        (Some(a), None) => Some((a, a)),+        (None, Some(d)) => Some((d, d)),+        (None, None) => None,+    }+}+ /// One `shapes.txt` polyline, in `shape_pt_sequence` order. pub struct Shape {     pub lat_e7: Vec<i32>,     pub lon_e7: Vec<i32>,     /// `shape_dist_traveled`, present only when *every* point carries one.-    /// Feed-defined units (km, mi, ft, ...): only ever compared, never converted.-    pub dist: Option<Vec<f64>>,+    /// Feed-defined units (km, mi, ft, ...): only ever compared, never converted,+    /// so `f32`'s ~7 significant digits are ample and halve what a big feed's+    /// shapes cost to hold.+    pub dist: Option<Vec<f32>>, }  /// Split one CSV line into fields, honouring quotes and `""` escapes. Unlike@@ -172,8 +185,90 @@ fn split_line(line: &str) -> Vec<String> {     out } -/// A `shapes.txt` row before ordering: `(sequence, lat_e7, lon_e7, dist)`.-type RawShapePoint = (i64, i32, i32, Option<f64>);+/// One usable `stop_times.txt` row, already typed. Borrowed from the reader's+/// line buffer, so it must be consumed before the next row is read.+pub struct StopTimeRow<'a> {+    pub trip_id: &'a str,+    pub stop_id: &'a str,+    /// `stop_sequence`. GTFS defines it as a non-negative integer; a value that+    /// will not parse becomes 0, which sorts first and, the sort being stable,+    /// leaves such rows in file order.+    pub seq: u32,+    pub arr: u32,+    pub dep: u32,+    /// `shape_dist_traveled` in the feed's own units, an ordering key only, or+    /// NaN when the row carries none. A sentinel rather than an `Option` because+    /// this is the field that decides how big a `stop_times` row is, and there+    /// are billions of them.+    pub dist: f32,+}++/// Stream `dir/stop_times.txt`, calling `f` once per row that carries a trip id+/// and a usable time. Returns `None` only when the file is absent.+///+/// `stop_times.txt` is the largest file in almost every feed — 52 GB of `Csv` for+/// `great_britain` alone — and every row is reduced to a handful of bytes+/// immediately, so materializing it as `Vec<Vec<String>>` first is pure waste.+/// Like [`read_shapes`] this is `BufReader` + `read_until` + an immediate typed+/// parse.+///+/// Rows arrive in **file order**, which callers depend on: the `stop_sequence`+/// sort downstream is stable, so feeds that repeat a `stop_sequence` within a+/// trip are resolved by their file order.+pub fn stream_stop_times(dir: &Path, mut f: impl FnMut(StopTimeRow)) -> Option<()> {+    let file = std::fs::File::open(dir.join("stop_times.txt")).ok()?;+    let mut reader = std::io::BufReader::new(file);+    let mut raw: Vec<u8> = Vec::new();++    reader.read_until(b'\n', &mut raw).ok()?;+    let header_line = String::from_utf8_lossy(&raw);+    let header = split_line(header_line.trim_end_matches(['\n', '\r']));+    // Every column is optional, exactly as [`Csv::get`] treats a missing one: a+    // feed with no `stop_id` column yields no usable rows rather than an error.+    let col = |name: &str| {+        header.iter().position(|h| h.trim().trim_start_matches('\u{feff}') == name)+    };+    let (c_trip, c_stop) = (col("trip_id"), col("stop_id"));+    let (c_seq, c_arr, c_dep) =+        (col("stop_sequence"), col("arrival_time"), col("departure_time"));+    let c_dist = col("shape_dist_traveled");++    loop {+        raw.clear();+        if reader.read_until(b'\n', &mut raw).ok()? == 0 {+            break;+        }+        let line = String::from_utf8_lossy(&raw);+        let line = line.trim_end_matches(['\n', '\r']);+        if line.is_empty() {+            continue;+        }+        let fields = split_line(line);+        let get = |i: Option<usize>| i.and_then(|i| fields.get(i)).map(|s| s.trim()).unwrap_or("");+        let trip_id = get(c_trip);+        if trip_id.is_empty() {+            continue;+        }+        let Some((arr, dep)) = stop_time_pair(get(c_arr), get(c_dep)) else {+            continue;+        };+        f(StopTimeRow {+            trip_id,+            stop_id: get(c_stop),+            seq: get(c_seq).parse().unwrap_or(0),+            arr,+            dep,+            dist: get(c_dist).parse().unwrap_or(f32::NAN),+        });+    }+    Some(())+}++/// A `shapes.txt` row before ordering: `(sequence, lat_e7, lon_e7, dist)`, where+/// `dist` is NaN when the row has none. 16 bytes rather than the 32 an+/// `(i64, i32, i32, Option<f64>)` needs — this intermediate has exactly the+/// defect the streaming loader exists to avoid.+type RawShapePoint = (u32, i32, i32, f32);  /// Stream `dir/shapes.txt` into one polyline per `shape_id`. Returns `None` when /// the file is absent (it is optional) or carries no usable columns.@@ -218,8 +313,8 @@ pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {             Ok(v) => v,             Err(_) => continue,         };-        let seq: i64 = get(c_seq).parse().unwrap_or(0);-        let dist = c_dist.and_then(|i| get(i).parse::<f64>().ok());+        let seq: u32 = get(c_seq).parse().unwrap_or(0);+        let dist = c_dist.map_or(f32::NAN, |i| get(i).parse().unwrap_or(f32::NAN));         acc.entry(id.to_string()).or_default().push((             seq,             (lat * 1e7) as i32,@@ -231,14 +326,14 @@ pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {     let mut out = HashMap::with_capacity(acc.len());     for (id, mut pts) in acc {         pts.sort_by_key(|p| p.0);-        let all_dist = pts.iter().all(|p| p.3.is_some());+        let all_dist = pts.iter().all(|p| !p.3.is_nan());         out.insert(             id,             Shape {                 lat_e7: pts.iter().map(|p| p.1).collect(),                 lon_e7: pts.iter().map(|p| p.2).collect(),                 dist: if all_dist {-                    Some(pts.iter().map(|p| p.3.unwrap_or(0.0)).collect())+                    Some(pts.iter().map(|p| p.3).collect())                 } else {                     None                 },@@ -247,3 +342,96 @@ pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {     }     Some(out) }++#[cfg(test)]+mod tests {+    use super::*;++    /// 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]+    fn a_raw_shape_point_stays_sixteen_bytes() {+        assert_eq!(std::mem::size_of::<RawShapePoint>(), 16);+    }++    /// The streaming loader must agree with the [`Csv`] path row for row: the+    /// tests that pin the pack's contents feed it a `Csv`, while the host tool+    /// streams, and a divergence would mean the two build different packs.+    #[test]+    fn streaming_stop_times_matches_parsing_the_whole_table() {+        // A BOM, a quoted comma, a blank line, each arrival/departure fallback,+        // an unparseable sequence, a row with no usable time, a row with no trip+        // id, and a row that simply stops early.+        let text = "\u{feff}trip_id,stop_id,stop_sequence,arrival_time,departure_time,shape_dist_traveled\n\+             T1,S1,1,08:00:00,08:00:05,0\n\+             T1,\"S,2\",2,08:10:00,,1.5\n\+             \n\+             T1,S3,3,,08:20:00,\n\+             ,S4,4,08:30:00,08:30:00,9\n\+             T2,S5,notanumber,25:10:00,25:10:00,\n\+             T2,S6,6,,,7\n\+             T2,S7\n";++        let dir = std::env::temp_dir()+            .join(format!("gtfs_ingest_stream_{}", std::process::id()));+        std::fs::create_dir_all(&dir).expect("temp dir");+        std::fs::write(dir.join("stop_times.txt"), text).expect("write stop_times.txt");++        // NaN is the "no shape_dist_traveled" sentinel and compares unequal to+        // itself, so rows are compared by the dist's bits.+        type Row = (String, String, u32, u32, u32, u32);+        let mut streamed: Vec<Row> = Vec::new();+        stream_stop_times(&dir, |r| {+            streamed.push((+                r.trip_id.to_string(),+                r.stop_id.to_string(),+                r.seq,+                r.arr,+                r.dep,+                r.dist.to_bits(),+            ));+        })+        .expect("stop_times.txt is present");+        let _ = std::fs::remove_dir_all(&dir);++        let csv = parse_csv(text);+        let tabled: Vec<Row> = csv+            .rows+            .iter()+            .filter_map(|row| {+                let trip_id = csv.get(row, "trip_id");+                if trip_id.is_empty() {+                    return None;+                }+                let (arr, dep) = stop_time_pair(+                    csv.get(row, "arrival_time"),+                    csv.get(row, "departure_time"),+                )?;+                Some((+                    trip_id.to_string(),+                    csv.get(row, "stop_id").to_string(),+                    csv.get(row, "stop_sequence").trim().parse().unwrap_or(0),+                    arr,+                    dep,+                    csv.get(row, "shape_dist_traveled")+                        .trim()+                        .parse()+                        .unwrap_or(f32::NAN)+                        .to_bits(),+                ))+            })+            .collect();++        assert_eq!(streamed, tabled);+        // Spelled out so the filters themselves are pinned, not just the two+        // paths' agreement: T1/S1 keeps both times, "S,2" survives the quoted+        // comma with departure falling back to arrival, S3 arrives at its+        // departure, S4 has no trip, S5's sequence is unusable and its time is+        // past midnight, and S6/S7 carry no time at all.+        assert_eq!(streamed.len(), 4, "{streamed:?}");+        assert_eq!(streamed[0], ("T1".into(), "S1".into(), 1, 28800, 28805, 0f32.to_bits()));+        assert_eq!(streamed[1], ("T1".into(), "S,2".into(), 2, 29400, 29400, 1.5f32.to_bits()));+        assert_eq!(streamed[2].3, 30000, "an absent arrival takes the departure");+        assert_eq!(streamed[3], ("T2".into(), "S5".into(), 0, 90600, 90600, f32::NAN.to_bits()));+    }+}
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 26de843d2b..33dd199228 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -122,10 +122,12 @@ //!                        which falls back to `stop_id` only when `stop_code` is //!                        blank and so cannot be relied on. -use crate::gtfs::{parse_gtfs_date, parse_gtfs_time, Csv, Shape};+use crate::gtfs;+use crate::gtfs::{parse_gtfs_date, Csv, Shape}; use crate::shapes; use std::collections::HashMap; use std::io::Write;+use std::path::Path;  pub const MAGIC: u32 = 0x5452_4958; // "TRIX" pub const VERSION: u32 = 5;@@ -329,17 +331,24 @@ impl ShapeBlobs {     } } +/// One `stop_times.txt` row reduced to what the index needs: 20 bytes, against+/// the ~400 a `Csv` row costs and the 40 an `Option<f64>` dist and `i64`+/// sequence used to. This is the hot struct — a world corpus has billions. struct StopTime {+    seq: u32,     stop_idx: u32,-    seq: i64,     arr: u32,     dep: u32,-    /// `shape_dist_traveled`, in the feed's own units. An ordering key only.-    dist: Option<f64>,+    /// `shape_dist_traveled` in the feed's own units, or NaN when absent. An+    /// ordering key only, so `f32` loses nothing that matters.+    dist: f32, }  /// One input GTFS feed (already parsed). Multiple feeds merge into one pack; /// their GTFS ids are namespaced by feed so they never collide.+///+/// Holding `stop_times.txt` as a [`Csv`] costs roughly 10x the bytes of the file,+/// so the host tool uses [`FeedDir`] instead and lets the builder stream it. pub struct FeedInput<'a> {     pub name: String,     /// Transitous id prefix for this feed (`us-ca-SF-bayarea`), used to compose@@ -361,6 +370,77 @@ pub struct FeedInput<'a> {     pub shapes: Option<&'a HashMap<String, Shape>>, } +/// The same feed, but with `stop_times.txt` left on disk to be streamed out of+/// `dir` rather than parsed into a [`Csv`] first. Everything else is small enough+/// to hold.+pub struct FeedDir<'a> {+    pub name: String,+    pub motis_prefix: String,+    /// The unzipped GTFS directory holding `stop_times.txt`.+    pub dir: &'a Path,+    pub stops: &'a Csv,+    pub routes: &'a Csv,+    pub trips: &'a Csv,+    pub calendar: Option<&'a Csv>,+    pub calendar_dates: Option<&'a Csv>,+    pub agency: Option<&'a Csv>,+    pub shapes: Option<&'a HashMap<String, Shape>>,+}++/// Where a feed's `stop_times.txt` comes from.+enum StopTimesSource<'a> {+    Table(&'a Csv),+    Dir(&'a Path),+}++/// The parts of a feed [`IndexBuilder::add`] needs, from either input form.+struct FeedView<'a> {+    name: &'a str,+    motis_prefix: &'a str,+    stops: &'a Csv,+    routes: &'a Csv,+    trips: &'a Csv,+    calendar: Option<&'a Csv>,+    calendar_dates: Option<&'a Csv>,+    agency: Option<&'a Csv>,+    shapes: Option<&'a HashMap<String, Shape>>,+    stop_times: StopTimesSource<'a>,+}++impl<'a> From<&'a FeedInput<'a>> for FeedView<'a> {+    fn from(f: &'a FeedInput<'a>) -> FeedView<'a> {+        FeedView {+            name: &f.name,+            motis_prefix: &f.motis_prefix,+            stops: f.stops,+            routes: f.routes,+            trips: f.trips,+            calendar: f.calendar,+            calendar_dates: f.calendar_dates,+            agency: f.agency,+            shapes: f.shapes,+            stop_times: StopTimesSource::Table(f.stop_times),+        }+    }+}++impl<'a> From<&'a FeedDir<'a>> for FeedView<'a> {+    fn from(f: &'a FeedDir<'a>) -> FeedView<'a> {+        FeedView {+            name: &f.name,+            motis_prefix: &f.motis_prefix,+            stops: f.stops,+            routes: f.routes,+            trips: f.trips,+            calendar: f.calendar,+            calendar_dates: f.calendar_dates,+            agency: f.agency,+            shapes: f.shapes,+            stop_times: StopTimesSource::Dir(f.dir),+        }+    }+}+ /// Summary counts reported to the caller / manifest. pub struct BuildStats {     pub stops: usize,@@ -426,7 +506,7 @@ struct BuiltTrip {     /// references no usable shape.     shape_key: u32,     /// `shape_dist_traveled` per pattern stop, when every stop has one.-    stop_dists: Option<Vec<f64>>,+    stop_dists: Option<Vec<f32>>, }  /// Build the full index blob from one or more GTFS feeds. `pack_name` is stored@@ -473,18 +553,19 @@ struct TripMeta {  /// Accumulates GTFS feeds into one merged pack. ///-/// Feeds go in one at a time through [`IndexBuilder::add_feed`], which both-/// ingests a feed **and finalizes it**: its routes, trips, profiles, shapes and-/// stop→route lists are serialized before the next feed is touched, so nothing-/// per-feed survives the feed boundary. That is legal because a route never-/// references a stop outside its own feed (`stop_id_to_idx` is per-feed), which-/// `add_feed` asserts.+/// Feeds go in one at a time through [`IndexBuilder::add_feed`] (or+/// [`IndexBuilder::add_feed_dir`], which streams `stop_times.txt`), and each call+/// both ingests a feed **and finalizes it**: its routes, trips, profiles, shapes+/// and stop→route lists are serialized before the next feed is touched, so+/// nothing per-feed survives the feed boundary. That is legal because a route+/// never references a stop outside its own feed (`stop_id_to_idx` is per-feed),+/// which `add` asserts. /// /// What crosses a boundary is only the pack itself — the section buffers, the /// string pool, the profile and shape tables — plus `stop_lat`/`stop_lon`, /// services and exceptions, which the transfers, both grids and the bbox need /// once every feed is in.-struct IndexBuilder {+pub struct IndexBuilder {     pool: StringPool,     /// STRINGS offset of the pack name, for the header.     pack_name_off: u32,@@ -536,7 +617,9 @@ struct IndexBuilder { }  impl IndexBuilder {-    fn new(pack_name: &str) -> IndexBuilder {+    /// `pack_name` is stored in the string pool and surfaced to the on-device+    /// planner as a fallback.+    pub fn new(pack_name: &str) -> IndexBuilder {         let mut pool = StringPool::new();         let pack_name_off = pool.intern(pack_name);         IndexBuilder {@@ -590,7 +673,40 @@ impl IndexBuilder {         i     } -    fn add_feed(&mut self, feed: &FeedInput) -> Result<(), String> {+    /// Ingest and finalize one feed whose tables are all already parsed.+    pub fn add_feed(&mut self, feed: &FeedInput) -> Result<(), String> {+        self.add(&feed.into())+    }++    /// Ingest and finalize one feed, streaming its `stop_times.txt` off disk.+    pub fn add_feed_dir(&mut self, feed: &FeedDir) -> Result<(), String> {+        self.add(&feed.into())+    }++    /// Bytes currently held in the sections, for progress reporting: this is+    /// what the finished pack will be, so it is the number to watch.+    pub fn section_bytes(&self) -> usize {+        self.pool.bytes.len()+            + self.profiles.bytes.len()+            + self.shape_blobs.bytes.len()+            + self.sec_stops.len()+            + self.sec_stop_gtfs_id.len()+            + self.sec_routes.len()+            + self.sec_route_stops.len()+            + self.sec_route_trips.len()+            + self.sec_route_shape_idx.len()+            + self.sec_route_stop_shape.len()+            + self.sec_stop_routes.len()+            + self.sec_stop_routes_idx.len()+            + self.sec_stop_route_pos.len()+    }++    /// `(stops, routes, trips)` accumulated so far.+    pub fn counts(&self) -> (usize, usize, usize) {+        (self.stop_lat.len(), self.route_count, self.trip_total)+    }++    fn add(&mut self, feed: &FeedView) -> Result<(), String> {         let feed_idx = self.feed_name_offs.len() as u32;         let feed_stop_start = self.stop_lat.len() as u32;         let feed_exc_start = self.exceptions.len();@@ -683,30 +799,55 @@ impl IndexBuilder {          // --- stop_times grouped by trip (this feed) ---         let mut trip_stoptimes: HashMap<String, Vec<StopTime>> = HashMap::new();-        for row in &feed.stop_times.rows {-            let trip_id = feed.stop_times.get(row, "trip_id");-            if trip_id.is_empty() {-                continue;-            }-            let stop_id = feed.stop_times.get(row, "stop_id");-            let stop_idx = match stop_id_to_idx.get(stop_id) {+        let mut collect = |row: gtfs::StopTimeRow| {+            let stop_idx = match stop_id_to_idx.get(row.stop_id) {                 Some(&i) => i,-                None => continue,-            };-            let seq: i64 = feed.stop_times.get(row, "stop_sequence").trim().parse().unwrap_or(0);-            let dep = parse_gtfs_time(feed.stop_times.get(row, "departure_time"));-            let arr = parse_gtfs_time(feed.stop_times.get(row, "arrival_time"));-            let (arr, dep) = match (arr, dep) {-                (Some(a), Some(d)) => (a, d),-                (Some(a), None) => (a, a),-                (None, Some(d)) => (d, d),-                (None, None) => continue,+                None => return,             };-            let dist = feed.stop_times.get(row, "shape_dist_traveled").trim().parse::<f64>().ok();-            trip_stoptimes-                .entry(trip_id.to_string())-                .or_default()-                .push(StopTime { stop_idx, seq, arr, dep, dist });+            trip_stoptimes.entry(row.trip_id.to_string()).or_default().push(StopTime {+                seq: row.seq,+                stop_idx,+                arr: row.arr,+                dep: row.dep,+                dist: row.dist,+            });+        };+        match feed.stop_times {+            StopTimesSource::Table(csv) => {+                for row in &csv.rows {+                    let trip_id = csv.get(row, "trip_id");+                    if trip_id.is_empty() {+                        continue;+                    }+                    let Some((arr, dep)) = gtfs::stop_time_pair(+                        csv.get(row, "arrival_time"),+                        csv.get(row, "departure_time"),+                    ) else {+                        continue;+                    };+                    collect(gtfs::StopTimeRow {+                        trip_id,+                        stop_id: csv.get(row, "stop_id"),+                        seq: csv.get(row, "stop_sequence").trim().parse().unwrap_or(0),+                        arr,+                        dep,+                        dist: csv+                            .get(row, "shape_dist_traveled")+                            .trim()+                            .parse()+                            .unwrap_or(f32::NAN),+                    });+                }+            }+            StopTimesSource::Dir(dir) => {+                gtfs::stream_stop_times(dir, collect).ok_or_else(|| {+                    format!(+                        "feed '{}' ({}) missing required GTFS file: stop_times.txt",+                        feed.name,+                        dir.display()+                    )+                })?;+            }         }          // --- Services (calendar.txt) namespaced by feed ---@@ -830,7 +971,12 @@ impl IndexBuilder {                 start_time: sts.first().map(|s| s.dep).unwrap_or(0),                 stoptimes: sts.iter().map(|s| (s.arr, s.dep)).collect(),                 shape_key,-                stop_dists: sts.iter().map(|s| s.dist).collect::<Option<Vec<f64>>>(),+                // Present only when every stop in the pattern carries one, which+                // is what `shapes::fit` requires before it trusts the key.+                stop_dists: sts+                    .iter()+                    .map(|s| (!s.dist.is_nan()).then_some(s.dist))+                    .collect::<Option<Vec<f32>>>(),             });             raptor_routes[route_idx].trips.push(built_trips.len() - 1);         }@@ -992,7 +1138,7 @@ impl IndexBuilder {     }      /// Serialize the sections that need every feed, and write the pack to `out`.-    fn finish_to(self, out: &mut impl Write) -> Result<BuildStats, String> {+    pub fn finish_to(self, out: &mut impl Write) -> Result<BuildStats, String> {         let IndexBuilder {             pool,             pack_name_off,@@ -1374,12 +1520,20 @@ mod tests {         Reader, SEC_FEED_MOTIS_PREFIX, SEC_SHAPE_COORDS, SEC_STOP_GTFS_ID,     }; +    /// 20 bytes per `stop_times.txt` row is the whole point of the streaming+    /// loader — a world corpus has billions of them, and the old `Csv` ++    /// `Option<f64>` representation cost ~400 and 40.+    #[test]+    fn a_stop_time_stays_twenty_bytes() {+        assert_eq!(std::mem::size_of::<StopTime>(), 20);+    }+     fn agency(tz: &str) -> Csv {         parse_csv(&format!("agency_id,agency_name,agency_timezone\nA,Agency,{tz}\n"))     }      /// `(shape_id, points as (lat, lon), optional shape_dist_traveled)`.-    type ShapeSpec<'a> = (&'a str, Vec<(f64, f64)>, Option<Vec<f64>>);+    type ShapeSpec<'a> = (&'a str, Vec<(f64, f64)>, Option<Vec<f32>>);      fn shape_map(entries: Vec<ShapeSpec>) -> HashMap<String, Shape> {         entries
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 507de506ae..f00d1ebd39 100644--- a/scripts/maps/gtfs_ingest/src/main.rs+++ b/scripts/maps/gtfs_ingest/src/main.rs@@ -32,7 +32,7 @@  use gtfs_ingest::gtfs; use gtfs_ingest::index;-use gtfs_ingest::index::FeedInput;+use gtfs_ingest::index::FeedDir; use gtfs_ingest::manifest::{read_manifest, parse_feed_spec, FeedSpec}; use std::io::Write; use std::path::{Path, PathBuf};@@ -85,22 +85,22 @@ fn main() -> ExitCode { }  fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String> {-    // Parse every feed up front so their CSVs outlive the FeedInput borrows.-    struct FeedTables {-        name: String,-        motis_prefix: String,-        stops: gtfs::Csv,-        routes: gtfs::Csv,-        trips: gtfs::Csv,-        stop_times: gtfs::Csv,-        calendar: Option<gtfs::Csv>,-        calendar_dates: Option<gtfs::Csv>,-        agency: Option<gtfs::Csv>,-        shapes: Option<std::collections::HashMap<String, gtfs::Shape>>,-    }+    std::fs::create_dir_all(out_dir)+        .map_err(|e| format!("cannot create out dir {}: {e}", out_dir.display()))?;+    let index_path = out_dir.join(format!("{pack_name}.transit"));+    // Straight to disk through a BufWriter: the pack is 1.5-4 GB for a world+    // build, and holding a second copy of it in a `Vec` to then `fs::write` was+    // pure overhead.+    let file = std::fs::File::create(&index_path)+        .map_err(|e| format!("cannot create {}: {e}", index_path.display()))?;+    let mut writer = std::io::BufWriter::new(file); -    let mut tables: Vec<FeedTables> = Vec::with_capacity(specs.len());-    for (name, dir, motis_prefix) in specs {+    // 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.+    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())@@ -109,7 +109,6 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String         let stops = require("stops.txt")?;         let routes = require("routes.txt")?;         let trips = require("trips.txt")?;-        let stop_times = require("stop_times.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");@@ -136,47 +135,31 @@ fn run(out_dir: &Path, pack_name: &str, specs: &[FeedSpec]) -> Result<(), String                  the device will route it in its own local time"             );         }-        eprintln!("gtfs_ingest: parsed feed '{name}' ({})", dir.display());-        tables.push(FeedTables {+        builder.add_feed_dir(&FeedDir {             name: name.clone(),             motis_prefix: motis_prefix.clone(),-            stops,-            routes,-            trips,-            stop_times,-            calendar,-            calendar_dates,-            agency,-            shapes,-        });+            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),+        );     } -    let feeds: Vec<FeedInput> = tables-        .iter()-        .map(|t| FeedInput {-            name: t.name.clone(),-            motis_prefix: t.motis_prefix.clone(),-            stops: &t.stops,-            routes: &t.routes,-            trips: &t.trips,-            stop_times: &t.stop_times,-            calendar: t.calendar.as_ref(),-            calendar_dates: t.calendar_dates.as_ref(),-            agency: t.agency.as_ref(),-            shapes: t.shapes.as_ref(),-        })-        .collect();--    std::fs::create_dir_all(out_dir)-        .map_err(|e| format!("cannot create out dir {}: {e}", out_dir.display()))?;-    let index_path = out_dir.join(format!("{pack_name}.transit"));-    // Straight to disk through a BufWriter: the pack is 1.5-4 GB for a world-    // build, and holding a second copy of it in a `Vec` to then `fs::write` was-    // pure overhead.-    let file = std::fs::File::create(&index_path)-        .map_err(|e| format!("cannot create {}: {e}", index_path.display()))?;-    let mut writer = std::io::BufWriter::new(file);-    let stats = index::build_index_to(pack_name, &feeds, &mut writer)?;+    let stats = builder.finish_to(&mut writer)?;     writer         .flush()         .map_err(|e| format!("cannot finish writing {}: {e}", index_path.display()))?;
scripts/maps/gtfs_ingest/src/shapes.rs
diff --git a/scripts/maps/gtfs_ingest/src/shapes.rs b/scripts/maps/gtfs_ingest/src/shapes.rsindex 22bb9373e0..f11594416d 100644--- a/scripts/maps/gtfs_ingest/src/shapes.rs+++ b/scripts/maps/gtfs_ingest/src/shapes.rs@@ -85,13 +85,13 @@ fn simplify_span(pts: &[(i32, i32)], lo: usize, hi: usize, keep: &mut Vec<usize>     } } -fn non_decreasing(v: &[f64]) -> bool {+fn non_decreasing(v: &[f32]) -> bool {     v.windows(2).all(|w| w[1] >= w[0]) }  /// Segment index whose `shape_dist_traveled` span contains `d`, searched from /// `from` onwards so the result can never step backwards along the shape.-fn bracket(shape_dist: &[f64], d: f64, from: usize) -> usize {+fn bracket(shape_dist: &[f32], d: f32, from: usize) -> usize {     let last = shape_dist.len() - 2;     let mut seg = from.min(last);     while seg < last && shape_dist[seg + 1] < d {@@ -104,7 +104,7 @@ fn bracket(shape_dist: &[f64], d: f64, from: usize) -> usize { /// `shape_dist_traveled` from `stop_times.txt`, used only when the shape carries /// it too. Returns `None` when the shape cannot be trusted for this pattern, in /// which case the caller stores no shape and the device draws stop-to-stop.-pub fn fit(shape: &Shape, stops: &[(i32, i32)], stop_dists: Option<&[f64]>) -> Option<FittedShape> {+pub fn fit(shape: &Shape, stops: &[(i32, i32)], stop_dists: Option<&[f32]>) -> Option<FittedShape> {     let n = shape.lat_e7.len();     if n < 2 || stops.len() < 2 {         return None;@@ -237,7 +237,7 @@ fn write_zigzag(v: &mut Vec<u8>, x: i64) { mod tests {     use super::*; -    fn shape(points: &[(f64, f64)], dist: Option<&[f64]>) -> Shape {+    fn shape(points: &[(f64, f64)], dist: Option<&[f32]>) -> Shape {         Shape {             lat_e7: points.iter().map(|&(la, _)| (la * 1e7) as i32).collect(),             lon_e7: points.iter().map(|&(_, lo)| (lo * 1e7) as i32).collect(),