gtfs_ingest: document the memory work and drop the unused entry point
- Commit
21e4624e5c73c21e4232330cfbd5bf9ef8361775- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-21 21:40 UTC (3 months ago)
- Parents
c46d54d
Diff
scripts/maps/gtfs_ingest/README.md
diff --git a/scripts/maps/gtfs_ingest/README.md b/scripts/maps/gtfs_ingest/README.mdindex 2a6f2185f3..3f605248ee 100644--- a/scripts/maps/gtfs_ingest/README.md+++ b/scripts/maps/gtfs_ingest/README.md@@ -61,7 +61,7 @@ device (used for route colours via `GTFSProvider`). - `<pack>.transit.json` — a small manifest with counts, bbox and a **per-section byte breakdown** so the compression win (profiles vs the old per-trip stop-times) is visible, plus how many routes got ride geometry.- `format_version` is 4.+ `format_version` is 5. ## Why TRX2 (v2) @@ -125,8 +125,61 @@ Fitting a shape to a pattern (`src/shapes.rs`): and routes whose trips disagreed on `shape_id`. The Douglas–Peucker tolerance is the lever on pack size: shapes dominate a v4-pack. `shapes.txt` is often the largest file in a feed, so it is streamed-(`gtfs::read_shapes`) rather than parsed into a `Csv` of `String`s.+pack. `shapes.txt` and `stop_times.txt` are the two largest files in a feed, so+both are streamed (`gtfs::read_shapes`, `gtfs::stream_stop_times`) rather than+parsed into a `Csv` of `String`s — see *Build-time memory* below.++## Build-time memory++A world build is bound by RAM, not by pack size. The pack is ~1.5–4 GB, but the+*input* representation used to cost far more: parsing every feed up front held+each one's `Csv` for the whole run, and a `Csv` row is a `Vec<String>` — roughly+10x the bytes of the CSV text it came from. Measured at 6.19 GB of RSS per 1 GB of+GTFS, which projects to ~400 GB for 1272 feeds and OOMs at feed 302.++The builder is incremental instead. `index::IndexBuilder::add_feed_dir` both+ingests a feed and **finalizes** it — routes, trips, profiles, shapes and+stop→route lists all become section bytes before the next feed is read — so the+only things that cross a feed boundary are the sections themselves (which *are*+the pack), the string pool, and `stop_lat`/`stop_lon` (8 B a stop, needed because+the transfer grid, the spatial grid and the bbox are global and `grid_cols` is not+known until the last feed is in). Peak is therefore *pack size + largest single+feed*, not the sum of all feeds:++| | before | after |+|---|---|---|+| 100 feeds (346k stops, 1.24 M trips) | 1.85 GB, 147 s | **0.66 GB, 128 s** |+| `great_britain` alone (9.5 GB of GTFS, 5.8 GB of it `stop_times.txt`) | ~60 GB (projected) | **1.93 GB, 250 s** |++Four things got it there, all verified with `transit_dump` rather than by+byte-diffing:++1. **`stop_times.txt` is streamed**, not parsed into a `Csv` — it is 5.8 GB of the+ 9.5 GB `great_britain` feed and every row reduces to a 24-byte `StopTime`. The+ streaming path has to agree with the `Csv` path *exactly*, which is subtler+ than it looks: ids are joined against `trips.txt`/`stops.txt` untrimmed, `\r`+ is swallowed anywhere, a repeated column name resolves to its last occurrence,+ and a quoted field may contain a newline. `gtfs.rs`'s tests pin all four —+ trimming ids alone silently dropped 1562 trips from one feed.+2. **Dedup maps hold no second copy.** `StringPool`, the profile table and the+ shape-blob table are keyed by hash and confirm each candidate against the+ append-only buffer that already holds the bytes. A collision can only fail to+ dedup, never merge two different values. `pattern_key_to_route` is the+ exception and compares `(route_id, stop_pattern)` in full — a false match there+ would fuse two patterns into one route, which is wrong departures rather than+ wasted bytes.+3. **Both grids are flat sorted vectors**, looked up by `partition_point`, instead+ of `HashMap`s holding millions of tiny `Vec`s. Sorting the spatial grid by+ `(cell_id, stop)` is also exactly the order the device's binary search needs.+4. **The pack streams out** through a `BufWriter`: every section length is known+ by `finish_to`, so the directory is computed up front and the pack is never+ concatenated into one giant `Vec` first.++`shape_dist_traveled` stays `f64` throughout. It is only an ordering key, so `f32`+looks free — but feeds give it 8+ significant digits, and at that width `f32`+collapses shape points millimetres apart and flips which segment a stop brackets+onto. Measured on 100 feeds it changed the fitted polyline of 0.3% of routes to+save 4 bytes a row, which is the wrong trade. ## Testing @@ -162,8 +215,23 @@ rm maps/src/main/rust/test_fixtures/mini.transit.json ``` The bytes are a captured artefact, not a reproducible one — trips are grouped out-of a `HashMap`, so route order varies between runs. The device-side assertions are-semantic for that reason.+of a `HashMap`, so route order, profile ids and service indices all vary between+runs. The device-side assertions are semantic for that reason, and so is+`transit_dump`:++```sh+cargo run --release --manifest-path scripts/maps/gtfs_ingest/Cargo.toml \+ --bin transit_dump -- world.transit dump.txt+```++It renders a pack as sort-stable text — header counts, bbox, grid, then per feed+per route (sorted) every trip with its profile expanded back to absolute+`(arr, dep)`, then stops with their routes and footpaths, services keyed by their+calendar rather than their index, and the grid cells. Two builds of the same+corpus produce byte-different packs but identical dumps, so a refactor is verified+by dumping before, dumping after, and diffing. **Do not byte-diff packs.**+`src/reader.rs` is the decoder it uses — deliberately a second implementation of+the device reader, not shared code. ## Building a regional pack
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 211f2b865d..316c70c515 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -268,8 +268,7 @@ impl ProfileTable { let (arr0, dep0) = sts[0]; write_uvarint(&mut self.scratch, dep0.saturating_sub(arr0) as u64); let mut prev_dep = dep0;- for k in 1..n {- let (arr, dep) = sts[k];+ for &(arr, dep) in &sts[1..] { write_uvarint(&mut self.scratch, arr.saturating_sub(prev_dep) as u64); write_uvarint(&mut self.scratch, dep.saturating_sub(arr) as u64); prev_dep = dep;@@ -509,31 +508,24 @@ struct BuiltTrip { stop_dists: Option<Vec<f64>>, } -/// Build the full index blob from one or more GTFS feeds. `pack_name` is stored-/// in the string pool and surfaced to the on-device planner as a fallback.+/// Build the whole pack in memory from feeds whose tables are already parsed.+/// `pack_name` is stored in the string pool and surfaced to the on-device planner+/// as a fallback. ///-/// Buffers the whole pack in memory; prefer [`build_index_to`] for anything-/// larger than a test corpus.+/// Convenience for tests and small corpora. The host tool drives+/// [`IndexBuilder`] directly instead, one feed at a time, so it never holds more+/// than one feed's tables — or a second copy of the pack. pub fn build_index( pack_name: &str, feeds: &[FeedInput], ) -> Result<(Vec<u8>, BuildStats), String> {- let mut blob = Vec::new();- let stats = build_index_to(pack_name, feeds, &mut blob)?;- Ok((blob, stats))-}--/// Build the index straight into `out` (a `BufWriter<File>` in the host tool).-pub fn build_index_to(- pack_name: &str,- feeds: &[FeedInput],- out: &mut impl Write,-) -> Result<BuildStats, String> { let mut builder = IndexBuilder::new(pack_name); for feed in feeds { builder.add_feed(feed)?; }- builder.finish_to(out)+ let mut blob = Vec::new();+ let stats = builder.finish_to(&mut blob)?;+ Ok((blob, stats)) } /// One GTFS route's own fields, before its trips are grouped into patterns.@@ -710,7 +702,7 @@ impl IndexBuilder { 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();- self.feed_name_offs.push(self.pool.intern(&feed.name));+ self.feed_name_offs.push(self.pool.intern(feed.name)); // Per-feed IANA timezone. Dedup in the pool means one shared // "America/Los_Angeles" no matter how many feeds use it. let tz = feed