Modern Apps git

← Modern-Apps.git

maps: draw transit ride legs from GTFS shapes (TRX2 v4)

Commit
171ead1d124c974a1a29a12a9bc7b6f769ecba39
Author
vayun-mathur <[email protected]>
When
2026-08-20 21:14 UTC (3 months ago)
Parents
005055a

Diff

maps/src/main/rust/src/transit.rs
diff --git a/maps/src/main/rust/src/transit.rs b/maps/src/main/rust/src/transit.rsindex 5335cd277d..87c3de6609 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -1,10 +1,14 @@ //! On-device transit index loader + RAPTOR journey planner (P11b / world pack). //! //! Consumes the compact `.transit` index produced by the host tool-//! `scripts/maps/gtfs_ingest` (P11a). The on-disk layout (format v2 "TRX2") is+//! `scripts/maps/gtfs_ingest` (P11a). The on-disk layout (format v4 "TRX2") is //! documented at the top of that tool's `src/index.rs` and MUST stay in sync //! with the section constants and record accessors here. //!+//! v4 adds three sections (20-22) carrying GTFS `shapes.txt` geometry, so a ride+//! leg draws the vehicle's real path instead of a line through its stops. v3+//! packs are still accepted and fall back to stop-to-stop geometry.+//! //! v2 exists to make a single global (world) pack feasible. Instead of an 8 B //! `(arr,dep)` stop-time per stop *per trip* (which blew a world pack past the //! u32 stop-time ceiling and ~10–20 GB), a trip is just `{ start_time,@@ -19,17 +23,26 @@ //! scanning all stops, and access/egress use the grid — both required so a //! world-sized stop set stays fast. Access/egress walk straight-line to nearby //! stops rather than the road graph, keeping transit decoupled from the-//! road-graph merge gap. The road A* still handles walking legs elsewhere.+//! road-graph merge gap; `lib.rs` re-draws the resulting walk legs along the+//! road graph afterwards, without re-timing them.  use crate::graph::{read_at, MmapRegion}; use std::collections::HashMap;  // --- Format constants (mirror scripts/maps/gtfs_ingest/src/index.rs) --- const MAGIC: u32 = 0x5452_4958; // "TRIX"-const VERSION: u32 = 2;+/// Newest format this reader understands.+const VERSION: u32 = 4;+/// Oldest format still accepted. Reading both means an app update and a pack+/// rebuild can land in either order without offline transit silently degrading+/// to the online planner in between.+const VERSION_MIN: u32 = 3; pub const NONE: u32 = 0xFFFF_FFFF; const HEADER_LEN: usize = 80;-const SECTION_COUNT: usize = 17;+/// Section count of the newest format. The section directory is sized to this+/// and a v3 pack simply leaves the trailing entries empty.+const SECTION_COUNT: usize = 23;+const SECTION_COUNT_V3: usize = 20;  const SEC_STRINGS: usize = 0; const SEC_STOPS: usize = 1;@@ -48,6 +61,12 @@ const SEC_GRID_CELL_IDS: usize = 13; const SEC_GRID_CELL_OFF: usize = 14; const SEC_GRID_STOPS: usize = 15; const SEC_FEEDS: usize = 16;+const SEC_FEED_TZ: usize = 17;+const SEC_EXCEPTIONS_IDX: usize = 18;+const SEC_STOP_ROUTE_POS: usize = 19;+const SEC_SHAPE_COORDS: usize = 20;+const SEC_ROUTE_SHAPE_IDX: usize = 21;+const SEC_ROUTE_STOP_SHAPE: usize = 22;  const WALK_SPEED_M_S: f64 = 1.33; /// Access/egress radius: how far we will walk to the first / from the last stop.@@ -120,16 +139,36 @@ struct ProfileDec {     dep_rel: Vec<i32>, } +/// What a journey leg is; maps onto `RouteService.API.Maneuver` at the JNI+/// boundary (`Walk` → UNSPECIFIED, `Wait` → WAIT, `Ride` → RIDE).+#[derive(Clone, Copy, PartialEq, Eq)]+pub enum LegKind {+    Walk,+    /// Waiting at a stop for the next departure.+    Wait,+    /// Riding a transit vehicle.+    Ride,+}++impl LegKind {+    pub fn is_transit(self) -> bool {+        self == LegKind::Ride+    }+}+ /// A single leg of a planned journey, with owned strings ready for JNI. pub struct TransitLeg {-    pub is_transit: bool,+    pub kind: LegKind,+    /// Route short/long name for a ride (or the awaited route for a wait).     pub name: String,     pub feed: String,-    pub from_code: String,-    pub to_code: String,-    /// GTFS trip headsign; retained for richer transit UI (not yet marshaled).-    #[allow(dead_code)]+    /// Stop name (falling back to `stop_code` when the feed has no name).+    pub from_stop: String,+    pub to_stop: String,+    /// GTFS `trip_headsign`.     pub headsign: String,+    /// GTFS `route_color` as packed 0xRRGGBB, or 0 when the feed omits it.+    pub route_color: u32,     pub dep_secs: u32,     pub arr_secs: u32,     pub stop_count: i32,@@ -138,11 +177,38 @@ pub struct TransitLeg {     pub coords: Vec<f64>, } -/// mmap'd, read-only transit index for one pack (may hold many merged feeds).+/// What keeps an index's bytes alive: an mmap of the pack file in production, or+/// an owned buffer in tests (a `Vec`'s heap allocation doesn't move when the+/// enum does, so `base` stays valid).+enum Backing {+    Mmap(MmapRegion),+    #[cfg(test)]+    Owned(Vec<u8>),+}++impl Backing {+    fn base(&self) -> *const u8 {+        match self {+            Backing::Mmap(r) => r.base(),+            #[cfg(test)]+            Backing::Owned(v) => v.as_ptr(),+        }+    }+    fn len(&self) -> usize {+        match self {+            Backing::Mmap(r) => r.len,+            #[cfg(test)]+            Backing::Owned(v) => v.len(),+        }+    }+}++/// Read-only transit index for one pack (may hold many merged feeds). pub struct TransitIndex {-    _region: MmapRegion,+    _backing: Backing,     base: *const u8,     stop_count: u32,+    route_count: u32,     service_count: u32,     feed_count: u32,     feed_name_off: u32,@@ -174,21 +240,41 @@ impl TransitIndex {         path.push_str(feed);         path.push_str(".transit"); -        let region = MmapRegion::map(&path)?;-        if region.len < HEADER_LEN {+        TransitIndex::parse(Backing::Mmap(MmapRegion::map(&path)?))+    }++    /// Build an index over an in-memory TRX2 blob, so the planner can be tested+    /// without a pack file (the crate's mmap loader is Unix-only).+    #[cfg(test)]+    pub fn from_bytes(bytes: Vec<u8>) -> Option<TransitIndex> {+        TransitIndex::parse(Backing::Owned(bytes))+    }++    /// Validate the TRX2 header + section directory. A pack whose version this+    /// build does not know is rejected here, which is what lets the Kotlin side+    /// fall back to the online planner instead of misreading it. Versions+    /// `VERSION_MIN..=VERSION` are all accepted; the directory is sized from the+    /// header's own `section_count`, so a v3 pack loads with the v4-only+    /// sections left empty and every read of them gated on a non-zero length.+    fn parse(backing: Backing) -> Option<TransitIndex> {+        if backing.len() < HEADER_LEN {             return None;         }-        let base = region.base();+        let base = backing.base();         let magic: u32 = unsafe { read_at::<u32>(base, 0) };         let version: u32 = unsafe { read_at::<u32>(base, 1) };-        if magic != MAGIC || version != VERSION {+        if magic != MAGIC || !(VERSION_MIN..=VERSION).contains(&version) {+            return None;+        }+        let section_count = unsafe { read_at::<u32>(base, 2) } as usize;+        if section_count < SECTION_COUNT_V3 {             return None;         }-        let section_count: u32 = unsafe { read_at::<u32>(base, 2) };-        if section_count as usize != SECTION_COUNT {+        if HEADER_LEN + section_count.saturating_mul(16) > backing.len() {             return None;         }         let stop_count: u32 = unsafe { read_at::<u32>(base, 3) };+        let route_count: u32 = unsafe { read_at::<u32>(base, 4) };         let service_count: u32 = unsafe { read_at::<u32>(base, 6) };         let feed_count: u32 = unsafe { read_at::<u32>(base, 8) };         let grid_cell_count: u32 = unsafe { read_at::<u32>(base, 9) };@@ -202,22 +288,25 @@ impl TransitIndex {         let grid_cell_e7: u32 = unsafe { read_at::<u32>(base, 17) };         let grid_cols: u32 = unsafe { read_at::<u32>(base, 18) }; -        // Directory: SECTION_COUNT * (u64 offset, u64 len) starting at HEADER_LEN.+        // Directory: section_count * (u64 offset, u64 len) starting at HEADER_LEN.+        // A newer pack may carry more sections than this build knows; ignore the+        // tail rather than rejecting it.         let dir_base = unsafe { base.add(HEADER_LEN) };         let mut sec = [(0usize, 0usize); SECTION_COUNT];-        for (i, s) in sec.iter_mut().enumerate() {+        for (i, s) in sec.iter_mut().enumerate().take(section_count.min(SECTION_COUNT)) {             let off: u64 = unsafe { read_at::<u64>(dir_base, i * 2) };             let len: u64 = unsafe { read_at::<u64>(dir_base, i * 2 + 1) };-            if off as usize + len as usize > region.len {+            if off as usize + len as usize > backing.len() {                 return None;             }             *s = (off as usize, len as usize);         }          Some(TransitIndex {-            _region: region,+            _backing: backing,             base,             stop_count,+            route_count,             service_count,             feed_count,             feed_name_off,@@ -295,6 +384,11 @@ impl TransitIndex {     fn stop_route(&self, i: u32) -> u32 {         unsafe { read_at::<u32>(self.sec_ptr(SEC_STOP_ROUTES), i as usize) }     }+    /// Position of the stop within that route's stop pattern, parallel to+    /// [`Self::stop_route`] (first occurrence, as the writer records it).+    fn stop_route_pos(&self, i: u32) -> u32 {+        unsafe { read_at::<u32>(self.sec_ptr(SEC_STOP_ROUTE_POS), i as usize) }+    }     fn transfers_range(&self, stop: u32) -> (u32, u32) {         let idx = self.sec_ptr(SEC_TRANSFERS_IDX);         let s = unsafe { read_at::<u32>(idx, stop as usize) };@@ -307,12 +401,70 @@ impl TransitIndex {     fn service(&self, i: u32) -> ServiceRec {         unsafe { read_at::<ServiceRec>(self.sec_ptr(SEC_SERVICES), i as usize) }     }-    fn exception_count(&self) -> u32 {-        (self.sec[SEC_EXCEPTIONS].1 / std::mem::size_of::<ExcRec>()) as u32-    }     fn exception(&self, i: u32) -> ExcRec {         unsafe { read_at::<ExcRec>(self.sec_ptr(SEC_EXCEPTIONS), i as usize) }     }+    /// `[start, end)` range of EXCEPTIONS belonging to `service_idx`, ascending+    /// by date. v3 CSR index; replaces a full scan of every exception per call.+    fn exceptions_range(&self, service_idx: u32) -> (u32, u32) {+        let idx = self.sec_ptr(SEC_EXCEPTIONS_IDX);+        let s = unsafe { read_at::<u32>(idx, service_idx as usize) };+        let e = unsafe { read_at::<u32>(idx, service_idx as usize + 1) };+        (s, e)+    }++    /// Byte offset of `route_idx`'s polyline within SHAPE_COORDS, or `None` when+    /// the pack predates v4, or the ingester found no usable `shapes.txt`+    /// geometry for that route. Offsets are not a prefix sum: routes sharing a+    /// `shape_id` share one blob, so several may point at the same offset.+    fn route_shape_off(&self, route_idx: u32) -> Option<usize> {+        if route_idx >= self.route_count {+            return None;+        }+        if self.sec[SEC_ROUTE_SHAPE_IDX].1 < (self.route_count as usize + 1) * 4 {+            return None;+        }+        let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_ROUTE_SHAPE_IDX), route_idx as usize) };+        // NONE marks "no shape"; an offset with no room for the point count is+        // corrupt and gets the same fallback.+        if (off as usize).saturating_add(4) > self.sec[SEC_SHAPE_COORDS].1 {+            return None;+        }+        Some(off as usize)+    }++    /// Vertex index within its route's shape for ROUTE_STOPS entry `i`, or+    /// [`NONE`] when the pack carries no shape for it.+    fn route_stop_shape(&self, i: u32) -> u32 {+        if (i as usize + 1) * 4 > self.sec[SEC_ROUTE_STOP_SHAPE].1 {+            return NONE;+        }+        unsafe { read_at::<u32>(self.sec_ptr(SEC_ROUTE_STOP_SHAPE), i as usize) }+    }++    /// Decode vertices `from..=to` of the shape blob at byte offset `off`, as+    /// `(lat, lon)` degrees. Deltas accumulate from the blob's first point, so+    /// decoding always starts there and discards the head.+    fn shape_slice(&self, off: usize, from: u32, to: u32) -> Vec<(f64, f64)> {+        let point_count = unsafe {+            read_at::<u32>(self.base.add(self.sec[SEC_SHAPE_COORDS].0 + off), 0)+        };+        if to < from || to >= point_count {+            return Vec::new();+        }+        let mut pos = off + 4;+        let mut lat_e7 = 0i64;+        let mut lon_e7 = 0i64;+        let mut out = Vec::with_capacity((to - from + 1) as usize);+        for v in 0..=to {+            lat_e7 += zigzag(self.uvarint(SEC_SHAPE_COORDS, &mut pos));+            lon_e7 += zigzag(self.uvarint(SEC_SHAPE_COORDS, &mut pos));+            if v >= from {+                out.push((lat_e7 as f64 * 1e-7, lon_e7 as f64 * 1e-7));+            }+        }+        out+    }      /// Decode a route's varint trip block into `TripDec`s (start-time order).     fn route_trips(&self, rec: &RouteRec) -> Vec<TripDec> {@@ -362,6 +514,18 @@ impl TransitIndex {         (s.lat_e7 as f64 * 1e-7, s.lon_e7 as f64 * 1e-7)     } +    /// Display name of a stop, falling back to its code when the feed's+    /// `stop_name` is blank. The UI presents these as names, not codes.+    fn stop_label(&self, i: u32) -> String {+        let s = self.stop(i);+        let name = self.read_str(s.name_off);+        if name.is_empty() {+            self.read_str(s.code_off)+        } else {+            name+        }+    }+     // --- Spatial grid (sparse CSR) ---      fn cell_row(&self, lat_e7: i32) -> i64 {@@ -479,6 +643,36 @@ impl TransitIndex {         self.read_str(off)     } +    /// IANA timezone of feed `feed_idx` from FEED_TZ, or empty when the feed had+    /// no `agency.txt`.+    fn feed_tz_of(&self, feed_idx: u32) -> String {+        if feed_idx >= self.feed_count {+            return String::new();+        }+        let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_FEED_TZ), feed_idx as usize) };+        self.read_str(off)+    }++    /// IANA timezone of the feed covering `(lat, lon)`, resolved via the nearest+    /// stop and one of the routes serving it. Stops carry no `feed_idx` — only+    /// `RouteRec` does — so the route hop is required. Empty when nothing is+    /// near enough or the feed has no timezone.+    pub fn timezone_at(&self, lat: f64, lon: f64) -> String {+        const NEAREST_MAX_M: f64 = 5000.0;+        let (stop, _) = match self.nearest_stop(lat, lon, NEAREST_MAX_M) {+            Some(v) => v,+            None => return String::new(),+        };+        let (rs, re) = self.stop_routes_range(stop);+        for i in rs..re {+            let tz = self.feed_tz_of(self.route(self.stop_route(i)).feed_idx);+            if !tz.is_empty() {+                return tz;+            }+        }+        String::new()+    }+     /// Whether `service_idx` runs on the query weekday/date.     fn service_runs(&self, service_idx: u32, weekday: u32, date: u32) -> bool {         if service_idx >= self.service_count {@@ -488,13 +682,20 @@ impl TransitIndex {         let start = s.start_date;         let end = s.end_date;         let mask = s.weekday_mask;-        let mut runs = date >= start && date <= end && (mask & (1 << (weekday & 7))) != 0;-        // Apply calendar_dates exceptions for this exact date.-        let n = self.exception_count();-        for i in 0..n {-            let e = self.exception(i);-            if e.service_idx == service_idx && e.date == date {-                runs = e.added == 1;+        let runs = date >= start && date <= end && (mask & (1 << (weekday & 7))) != 0;+        // A `calendar_dates` row for this exact date overrides the weekly mask.+        // EXCEPTIONS is date-sorted within the service's CSR range (v3), so this+        // is a binary search rather than a scan of the whole pack.+        let (mut lo, mut hi) = self.exceptions_range(service_idx);+        while lo < hi {+            let mid = lo + (hi - lo) / 2;+            let e = self.exception(mid);+            if e.date == date {+                return e.added == 1;+            } else if e.date < date {+                lo = mid + 1;+            } else {+                hi = mid;             }         }         runs@@ -509,9 +710,152 @@ fn dist_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {     (dlat * dlat + dlon * dlon).sqrt() } -/// Absolute time = trip start_time + a profile offset (relative), clamped ≥ 0.-fn abs_time(start_time: u32, rel: i32) -> u32 {-    (start_time as i64 + rel as i64).max(0) as u32+/// Undo the producer's zigzag encoding (`(n << 1) ^ (n >> 63)`).+fn zigzag(u: u64) -> i64 {+    ((u >> 1) as i64) ^ -((u & 1) as i64)+}++/// Absolute time in the **query day's** frame: trip `start_time` plus a profile+/// offset. GTFS stores a trip running past midnight on its own service day+/// (`24:30:00`), so a trip inherited from the previous service day is shifted+/// back one full day.+fn abs_time_on(start_time: u32, rel: i32, prev_day: bool) -> u32 {+    let shift = if prev_day { SECS_PER_DAY as i64 } else { 0 };+    (start_time as i64 + rel as i64 - shift).max(0) as u32+}++/// The two service days a query may draw trips from: the query day itself, and+/// the day before it, whose `>24:00:00` trips run into the query day. Weekdays+/// are 0=Mon..6=Sun and dates are `yyyymmdd`, both in the **feed's** timezone.+#[derive(Clone, Copy)]+pub struct QueryDay {+    pub weekday: u32,+    pub date: u32,+    pub prev_weekday: u32,+    pub prev_date: u32,+}++/// The query-specific view of the timetable: which service days are eligible,+/// and what realtime knows about them. Threaded through the RAPTOR rounds.+#[derive(Clone, Copy)]+pub struct Schedule<'a> {+    pub day: QueryDay,+    pub overlay: Option<&'a DelayOverlay>,+}++impl Schedule<'_> {+    /// Whether `service_idx` runs on the query day (`prev = false`) or on the+    /// preceding service day (`prev = true`).+    fn runs(&self, idx: &TransitIndex, service_idx: u32, prev: bool) -> bool {+        if prev {+            idx.service_runs(service_idx, self.day.prev_weekday, self.day.prev_date)+        } else {+            idx.service_runs(service_idx, self.day.weekday, self.day.date)+        }+    }++    fn adjustment(&self, route: u32, pos: u32, sched: u32) -> Option<Adjustment> {+        self.overlay.and_then(|o| o.get(route, pos, sched))+    }++    /// How much earlier than its timetable slot any trip could depart.+    fn max_early_secs(&self) -> u32 {+        self.overlay.map_or(0, |o| o.max_early_secs)+    }+}++/// Realtime delays and cancellations lifted from a MOTIS departure board, so+/// RAPTOR plans against live times instead of the bare timetable.+///+/// The join is a **fingerprint**, not a trip id: TRX2 stores no `trip_id` (the+/// ingest tool discards it) and MOTIS's `tripId` is an opaque internally-encoded+/// handle, not a bare GTFS id. Worse, a v2 *profile* is deliberately shared+/// across many trips, so a delay can never hang off one. Entries are therefore+/// keyed on `(route_idx, stop_pos, scheduled_departure)` and resolved **once**,+/// at construction — never inside the RAPTOR hot loop.+#[derive(Default)]+pub struct DelayOverlay {+    entries: HashMap<(u32, u32, u32), Adjustment>,+    /// Largest amount by which any entry pulls a departure **earlier** (seconds,+    /// ≥ 0). `earliest_trip`'s early break needs this: a vehicle running early+    /// makes `dep < start_time`, so the break bound has to be widened by it or+    /// the scan can stop before a trip whose live departure is earlier.+    max_early_secs: u32,+}++#[derive(Clone, Copy)]+struct Adjustment {+    delay_secs: i32,+    cancelled: bool,+}++/// One realtime board entry as it crosses the JNI boundary.+pub struct DelayEntry {+    /// Board-stop coordinates; matched to a baked stop via the spatial grid,+    /// because MOTIS stop ids share no namespace with the pack.+    pub lat: f64,+    pub lon: f64,+    /// MOTIS `routeShortName`, matched against the baked route name.+    pub route_name: String,+    /// Scheduled departure, seconds since feed-local midnight.+    pub sched_secs: u32,+    pub delay_secs: i32,+    pub cancelled: bool,+}++impl DelayOverlay {+    /// Resolve realtime board entries against the index. Entries whose stop or+    /// route can't be matched are dropped — a miss must leave the schedule+    /// untouched, never guess.+    pub fn build(idx: &TransitIndex, entries: &[DelayEntry]) -> DelayOverlay {+        /// A MOTIS stop and its baked counterpart are the same platform, so keep+        /// this tight enough that adjacent platforms don't collide.+        const MATCH_RADIUS_M: f64 = 60.0;++        let mut out = DelayOverlay::default();+        for e in entries {+            if e.delay_secs == 0 && !e.cancelled {+                continue;+            }+            let stop = match idx.nearest_stop(e.lat, e.lon, MATCH_RADIUS_M) {+                Some((s, _)) => s,+                None => continue,+            };+            let (rs, re) = idx.stop_routes_range(stop);+            for i in rs..re {+                let r = idx.stop_route(i);+                if idx.read_str(idx.route(r).name_off) != e.route_name {+                    continue;+                }+                out.max_early_secs = out.max_early_secs.max((-e.delay_secs).max(0) as u32);+                out.entries.insert(+                    (r, idx.stop_route_pos(i), e.sched_secs),+                    Adjustment { delay_secs: e.delay_secs, cancelled: e.cancelled },+                );+            }+        }+        out+    }++    fn get(&self, route: u32, pos: u32, sched: u32) -> Option<Adjustment> {+        self.entries.get(&(route, pos, sched)).copied()+    }+}++/// Apply an overlay adjustment to a scheduled time, clamped ≥ 0.+fn delayed(sched: u32, delay_secs: i32) -> u32 {+    (sched as i64 + delay_secs as i64).max(0) as u32+}++/// The trip being ridden while scanning a route, plus the realtime shift that+/// applies to the rest of its journey.+#[derive(Clone, Copy)]+struct Boarding {+    /// Local index into the route's decoded trip list.+    trip: usize,+    /// This trip belongs to the previous service day (a `>24:00:00` trip).+    prev_day: bool,+    delay_secs: i32, }  /// Fetch (and cache) a decoded profile.@@ -527,15 +871,17 @@ fn get_profile<'a>( #[derive(Clone, Copy)] enum Reached {     Origin,-    /// Boarded `route` on its local `trip` at `board_stop`, alighting here.-    Transit { route: u32, trip: u32, board_stop: u32 },+    /// Boarded `route` at `board_stop` (see [`Boarding`]), alighting here.+    Transit { route: u32, board_stop: u32, boarding: Boarding },     /// Walked from `from_stop` (footpath transfer or egress precursor).     Walk { from_stop: u32 }, }  /// Plan an earliest-arrival transit journey between two WGS84 points departing-/// at `dep_secs` seconds since midnight on the given `weekday` (0=Mon..6=Sun)-/// and `date` (yyyymmdd). Returns the ordered legs, or `None` if unreachable.+/// at `dep_secs` seconds since midnight. All times are in the feed's local frame+/// (see [`QueryDay`]). When `sched` carries an overlay, cancelled trips are+/// skipped and delayed ones are planned at their live times. Returns the ordered+/// legs, or `None` if unreachable. pub fn plan(     idx: &TransitIndex,     from_lat: f64,@@ -543,8 +889,7 @@ pub fn plan(     to_lat: f64,     to_lon: f64,     dep_secs: u32,-    weekday: u32,-    date: u32,+    sched: Schedule, ) -> Option<Vec<TransitLeg>> {     let n = idx.stop_count as usize;     if n == 0 {@@ -596,20 +941,15 @@ pub fn plan(             let (rs, re) = idx.stop_routes_range(s);             for i in rs..re {                 let r = idx.stop_route(i);-                let route = idx.route(r);-                for pos in 0..route.n_stops {-                    if idx.route_stop(route.first_route_stop + pos) == s {-                        route_earliest-                            .entry(r)-                            .and_modify(|e| {-                                if pos < *e {-                                    *e = pos;-                                }-                            })-                            .or_insert(pos);-                        break;-                    }-                }+                let pos = idx.stop_route_pos(i);+                route_earliest+                    .entry(r)+                    .and_modify(|e| {+                        if pos < *e {+                            *e = pos;+                        }+                    })+                    .or_insert(pos);             }         } @@ -620,24 +960,29 @@ pub fn plan(             if trips.is_empty() {                 continue;             }-            let mut cur_trip: Option<usize> = None; // local index into `trips`+            let mut cur_trip: Option<Boarding> = None;             let mut board_stop: u32 = 0;             for pos in start_pos..route.n_stops {                 let stop = idx.route_stop(route.first_route_stop + pos); -                // If riding, relax arrival at this stop.-                if let Some(ti) = cur_trip {-                    let td = trips[ti];+                // If riding, relax arrival at this stop. A delayed vehicle+                // arrives late everywhere downstream, so the boarding shift+                // carries through the rest of the leg.+                if let Some(b) = cur_trip {+                    let td = trips[b.trip];                     let arr_rel = {                         let p = get_profile(&mut prof_cache, idx, td.profile_id);                         p.arr_rel.get(pos as usize).copied()                     };                     if let Some(arr_rel) = arr_rel {-                        let arr = abs_time(td.start_time, arr_rel);+                        let arr = delayed(+                            abs_time_on(td.start_time, arr_rel, b.prev_day),+                            b.delay_secs,+                        );                         if arr < best[stop as usize] {                             best[stop as usize] = arr;                             label[stop as usize] =-                                Reached::Transit { route: r, trip: ti as u32, board_stop };+                                Reached::Transit { route: r, board_stop, boarding: b };                             improved.push(stop);                         }                     }@@ -646,19 +991,21 @@ pub fn plan(                 // Can we (re)board an earlier trip here given our arrival?                 let ready = best[stop as usize];                 if ready != inf {-                    if let Some(ti) =-                        earliest_trip(idx, &mut prof_cache, &trips, pos, ready, weekday, date)+                    if let Some(cand) =+                        earliest_trip(idx, &mut prof_cache, r, &trips, pos, ready, sched)                     {                         let board_here = match cur_trip {                             None => true,                             Some(cur) => {-                                let new_dep = trip_dep(idx, &mut prof_cache, &trips[ti], pos);-                                let cur_dep = trip_dep(idx, &mut prof_cache, &trips[cur], pos);+                                let new_dep =+                                    trip_dep(idx, &mut prof_cache, &trips[cand.trip], pos, cand);+                                let cur_dep =+                                    trip_dep(idx, &mut prof_cache, &trips[cur.trip], pos, cur);                                 new_dep < cur_dep                             }                         };                         if board_here {-                            cur_trip = Some(ti);+                            cur_trip = Some(cand);                             board_stop = stop;                         }                     }@@ -702,8 +1049,9 @@ pub fn plan(     loop {         guard += 1;         if guard > MAX_ROUNDS * 4 + 16 {-            origin_stop = cur;-            break;+            // A cycle in the labels would otherwise yield a silently truncated+            // journey; bail so the caller falls back to the online planner.+            return None;         }         match label[cur as usize] {             Reached::Origin => {@@ -711,11 +1059,24 @@ pub fn plan(                 break;             }             Reached::Walk { from_stop } => {-                legs.push(make_walk_leg(idx, from_stop, cur));+                legs.push(make_walk_leg(+                    idx,+                    from_stop,+                    cur,+                    best[from_stop as usize],+                    best[cur as usize],+                ));                 cur = from_stop;             }-            Reached::Transit { route, trip, board_stop } => {-                legs.push(make_transit_leg(idx, &mut prof_cache, route, trip, board_stop, cur));+            Reached::Transit { route, board_stop, boarding } => {+                legs.push(make_transit_leg(+                    idx,+                    &mut prof_cache,+                    route,+                    boarding,+                    board_stop,+                    cur,+                ));                 cur = board_stop;             }         }@@ -730,15 +1091,16 @@ pub fn plan(         legs.insert(             0,             TransitLeg {-                is_transit: false,+                kind: LegKind::Walk,                 name: "Walk".to_string(),                 feed: String::new(),-                from_code: String::new(),-                to_code: idx.read_str(idx.stop(first_stop).code_off),+                from_stop: String::new(),+                to_stop: idx.stop_label(first_stop),                 headsign: String::new(),+                route_color: 0,                 dep_secs,                 arr_secs: best[first_stop as usize]-                    .min(dep_secs + (access_d / WALK_SPEED_M_S) as u32),+                    .min(dep_secs + (access_d / WALK_SPEED_M_S).ceil() as u32),                 stop_count: 0,                 dist_m: access_d,                 coords: vec![from_lon, from_lat, flon, flat],@@ -749,12 +1111,13 @@ pub fn plan(     let egress_d = dist_m(to_lat, to_lon, elat, elon);     if egress_d > 1.0 {         legs.push(TransitLeg {-            is_transit: false,+            kind: LegKind::Walk,             name: "Walk".to_string(),             feed: String::new(),-            from_code: idx.read_str(idx.stop(best_stop).code_off),-            to_code: String::new(),+            from_stop: idx.stop_label(best_stop),+            to_stop: String::new(),             headsign: String::new(),+            route_color: 0,             dep_secs: best[best_stop as usize],             arr_secs: best[best_stop as usize].saturating_add(best_walk),             stop_count: 0,@@ -766,10 +1129,43 @@ pub fn plan(     if legs.is_empty() {         return None;     }-    Some(legs)+    Some(insert_wait_legs(legs, dep_secs))+}++/// Minimum gap before we surface an explicit WAIT leg, so a 30-second dwell+/// doesn't become its own step.+const MIN_WAIT_SECS: u32 = 60;++/// Insert an explicit WAIT leg before each ride the traveller has to wait for.+/// RAPTOR already knows both times; without this the wait is invisible and the+/// journey's step durations don't add up to its total. `dep_secs` is when the+/// traveller is ready, which is what the first leg waits from.+fn insert_wait_legs(legs: Vec<TransitLeg>, dep_secs: u32) -> Vec<TransitLeg> {+    let mut out: Vec<TransitLeg> = Vec::with_capacity(legs.len());+    for leg in legs {+        let ready = out.last().map_or(dep_secs, |prev| prev.arr_secs);+        if leg.kind == LegKind::Ride && leg.dep_secs >= ready + MIN_WAIT_SECS {+            out.push(TransitLeg {+                kind: LegKind::Wait,+                name: leg.name.clone(),+                feed: String::new(),+                from_stop: leg.from_stop.clone(),+                to_stop: leg.from_stop.clone(),+                headsign: leg.headsign.clone(),+                route_color: leg.route_color,+                dep_secs: ready,+                arr_secs: leg.dep_secs,+                stop_count: 0,+                dist_m: 0.0,+                coords: Vec::new(),+            });+        }+        out.push(leg);+    }+    out } -/// A single upcoming scheduled departure from a stop (offline board).+/// A single upcoming departure from a stop (offline board). pub struct StopDeparture {     pub route_name: String,     pub headsign: String,@@ -777,9 +1173,14 @@ pub struct StopDeparture {     pub stop_code: String,     pub route_color: u32,     pub route_type: u32,-    /// Departure time in seconds since service-day midnight (may exceed 86400 for-    /// trips running past midnight).+    /// Scheduled departure in seconds since the query day's midnight.     pub dep_secs: u32,+    /// Realtime shift from the overlay; 0 when there is no live data.+    pub delay_secs: i32,+    /// True when realtime says this trip is cancelled.+    pub cancelled: bool,+    /// Whether the overlay had live data for this departure at all.+    pub real_time: bool, }  /// Build an offline departure board for the stop(s) nearest to `(lat,lon)`.@@ -794,8 +1195,7 @@ pub fn stop_departures(     lat: f64,     lon: f64,     dep_secs: u32,-    weekday: u32,-    date: u32,+    sched: Schedule,     max: usize, ) -> Vec<StopDeparture> {     const STATION_RADIUS_M: f64 = 150.0;@@ -821,57 +1221,89 @@ pub fn stop_departures(             let r = idx.stop_route(i);             let route = idx.route(r);             // Position of this stop within the route's ordered stop list.-            let mut pos = u32::MAX;-            for p in 0..route.n_stops {-                if idx.route_stop(route.first_route_stop + p) == s {-                    pos = p;-                    break;-                }-            }-            // Skip if not on the route, or it's the terminus (no onward departure).-            if pos == u32::MAX || pos + 1 >= route.n_stops {+            let pos = idx.stop_route_pos(i);+            // Skip if it's the terminus (no onward departure).+            if pos + 1 >= route.n_stops {                 continue;             }             let rname = idx.read_str(route.name_off);             let feed = idx.feed_name_of(route.feed_idx);             let trips = idx.route_trips(&route);             for td in &trips {-                if !idx.service_runs(td.service_idx, weekday, date) {-                    continue;-                }-                let dep = trip_dep(idx, &mut prof_cache, td, pos);-                if dep < dep_secs {-                    continue;+                // Sweep the previous service day too, so a 00:30 query still+                // finds a trip GTFS stored as 24:30:00 the day before.+                for prev_day in [true, false] {+                    if !sched.runs(idx, td.service_idx, prev_day) {+                        continue;+                    }+                    let Some(scheduled) = trip_sched_dep(idx, &mut prof_cache, td, pos, prev_day)+                    else {+                        continue;+                    };+                    let adj = sched.adjustment(r, pos, scheduled);+                    // Compare against the *live* time so a delayed trip that has+                    // not left yet stays on the board.+                    if delayed(scheduled, adj.map_or(0, |a| a.delay_secs)) < dep_secs {+                        continue;+                    }+                    out.push(StopDeparture {+                        route_name: rname.clone(),+                        headsign: idx.read_str(td.headsign_off),+                        feed: feed.clone(),+                        stop_code: code.clone(),+                        route_color: route.color,+                        route_type: route.route_type,+                        dep_secs: scheduled,+                        delay_secs: adj.map_or(0, |a| a.delay_secs),+                        cancelled: adj.is_some_and(|a| a.cancelled),+                        real_time: adj.is_some(),+                    });                 }-                out.push(StopDeparture {-                    route_name: rname.clone(),-                    headsign: idx.read_str(td.headsign_off),-                    feed: feed.clone(),-                    stop_code: code.clone(),-                    route_color: route.color,-                    route_type: route.route_type,-                    dep_secs: dep,-                });             }         }     }-    out.sort_by_key(|d| d.dep_secs);+    out.sort_by_key(|d| delayed(d.dep_secs, d.delay_secs));     out.truncate(max);     out } -/// Departure time (abs secs) of `trip` at stop-position `pos`.+/// Departure time (query-day secs) of `trip` at stop-position `pos`, including+/// the realtime shift the traveller boarded with. fn trip_dep(     idx: &TransitIndex,     cache: &mut HashMap<u32, ProfileDec>,     trip: &TripDec,     pos: u32,+    boarding: Boarding, ) -> u32 {     let dep_rel = {         let p = get_profile(cache, idx, trip.profile_id);         p.dep_rel.get(pos as usize).copied().unwrap_or(0)     };-    abs_time(trip.start_time, dep_rel)+    delayed(abs_time_on(trip.start_time, dep_rel, boarding.prev_day), boarding.delay_secs)+}++/// Scheduled (timetable) departure of `trip` at `pos` in the query day's frame,+/// ignoring realtime. `None` when `prev_day` is set but the trip does not+/// actually run into the query day — i.e. its GTFS time is below `24:00:00`, so+/// it belongs wholly to yesterday and must not be considered at all.+fn trip_sched_dep(+    idx: &TransitIndex,+    cache: &mut HashMap<u32, ProfileDec>,+    trip: &TripDec,+    pos: u32,+    prev_day: bool,+) -> Option<u32> {+    let dep_rel = {+        let p = get_profile(cache, idx, trip.profile_id);+        p.dep_rel.get(pos as usize).copied().unwrap_or(0)+    };+    let t = trip.start_time as i64 + dep_rel as i64+        - if prev_day { SECS_PER_DAY as i64 } else { 0 };+    if t < 0 {+        return None;+    }+    Some(t as u32) }  /// Relax one-hop footpath transfers from each `seed` stop, appending any stop@@ -901,49 +1333,75 @@ fn relax_transfers(     } } -/// Earliest trip (local index) on this route departing stop-position `pos` no-/// earlier than `ready` whose service runs on the query day.+/// Earliest trip on this route departing stop-position `pos` no earlier than+/// `ready`, whose service runs on `day` and which realtime hasn't cancelled.+/// Times are in the query day's frame and include any realtime delay. fn earliest_trip(     idx: &TransitIndex,     cache: &mut HashMap<u32, ProfileDec>,+    route_idx: u32,     trips: &[TripDec],     pos: u32,     ready: u32,-    weekday: u32,-    date: u32,-) -> Option<usize> {-    let mut best_ti: Option<usize> = None;+    sched: Schedule,+) -> Option<Boarding> {+    let mut best: Option<Boarding> = None;     let mut best_dep = u32::MAX;-    for (i, td) in trips.iter().enumerate() {-        if !idx.service_runs(td.service_idx, weekday, date) {-            continue;-        }-        let dep = trip_dep(idx, cache, td, pos);-        if dep >= ready && dep < best_dep {-            best_dep = dep;-            best_ti = Some(i);+    // Trips are written start-time sorted and every profile offset is >= 0, so+    // `dep >= start_time - max_early`. Once start_time passes that bound, no+    // later trip on this day can improve on `best_dep`. Exact, not a heuristic:+    // with no realtime the slack is 0, and realtime can only pull a departure+    // earlier by `max_early_secs`.+    let slack = sched.max_early_secs();+    // Previous-day trips first: theirs are the earliest times in this frame.+    for prev_day in [true, false] {+        for (i, td) in trips.iter().enumerate() {+            if best.is_some() && td.start_time >= best_dep.saturating_add(slack) && !prev_day {+                break;+            }+            if !sched.runs(idx, td.service_idx, prev_day) {+                continue;+            }+            // A previous-day trip only counts if it actually runs into the query+            // day (a GTFS time at or past 24:00:00).+            let Some(scheduled) = trip_sched_dep(idx, cache, td, pos, prev_day) else {+                continue;+            };+            let adj = sched.adjustment(route_idx, pos, scheduled);+            if adj.is_some_and(|a| a.cancelled) {+                continue;+            }+            let delay_secs = adj.map_or(0, |a| a.delay_secs);+            let dep = delayed(scheduled, delay_secs);+            if dep >= ready && dep < best_dep {+                best_dep = dep;+                best = Some(Boarding { trip: i, prev_day, delay_secs });+            }         }     }-    best_ti+    best }  fn make_transit_leg(     idx: &TransitIndex,     cache: &mut HashMap<u32, ProfileDec>,     route_idx: u32,-    trip_local: u32,+    boarding: Boarding,     board_stop: u32,     alight_stop: u32, ) -> TransitLeg {     let route = idx.route(route_idx);     let trips = idx.route_trips(&route);-    let td = trips.get(trip_local as usize).copied().unwrap_or(TripDec {+    let td = trips.get(boarding.trip).copied().unwrap_or(TripDec {         start_time: 0,         profile_id: 0,         service_idx: 0,         headsign_off: NONE,     });-    // Find board/alight positions along the route.+    // Find board/alight positions along the route. This keeps the linear scan+    // (and its last-match semantics) rather than using STOP_ROUTE_POS, which+    // records the *first* occurrence — for a route that visits a stop twice the+    // two differ, and this runs once per leg, not in the RAPTOR hot loop.     let mut board_pos = 0u32;     let mut alight_pos = 0u32;     for pos in 0..route.n_stops {@@ -957,36 +1415,65 @@ fn make_transit_leg(     }     let (dep, arr) = {         let p = get_profile(cache, idx, td.profile_id);-        let dep = abs_time(td.start_time, p.dep_rel.get(board_pos as usize).copied().unwrap_or(0));-        let arr = abs_time(td.start_time, p.arr_rel.get(alight_pos as usize).copied().unwrap_or(0));-        (dep, arr)+        let dep = abs_time_on(+            td.start_time,+            p.dep_rel.get(board_pos as usize).copied().unwrap_or(0),+            boarding.prev_day,+        );+        let arr = abs_time_on(+            td.start_time,+            p.arr_rel.get(alight_pos as usize).copied().unwrap_or(0),+            boarding.prev_day,+        );+        (delayed(dep, boarding.delay_secs), delayed(arr, boarding.delay_secs))     };      let mut coords = Vec::new();     let mut dist = 0.0;-    let mut prev: Option<(f64, f64)> = None;     let mut count = 0i32;     if alight_pos >= board_pos {-        for pos in board_pos..=alight_pos {-            let s = idx.route_stop(route.first_route_stop + pos);-            let (lat, lon) = idx.stop_ll(s);+        count = (alight_pos - board_pos + 1) as i32;+        // Prefer the feed's own `shapes.txt` geometry (v4 packs): it is the path+        // the vehicle actually takes, and it makes `dist_m` truthful — a line+        // through the stops under-reports every ride. A v3 pack, or a route the+        // ingester could not attach a shape to, falls back to one vertex per stop.+        let shaped = idx.route_shape_off(route_idx).and_then(|off| {+            let from = idx.route_stop_shape(route.first_route_stop + board_pos);+            let to = idx.route_stop_shape(route.first_route_stop + alight_pos);+            if from == NONE || to == NONE {+                return None;+            }+            let pts = idx.shape_slice(off, from, to);+            if pts.len() < 2 {+                None+            } else {+                Some(pts)+            }+        });+        let points = shaped.unwrap_or_else(|| {+            (board_pos..=alight_pos)+                .map(|pos| idx.stop_ll(idx.route_stop(route.first_route_stop + pos)))+                .collect()+        });+        let mut prev: Option<(f64, f64)> = None;+        for (lat, lon) in points {             if let Some((plat, plon)) = prev {                 dist += dist_m(plat, plon, lat, lon);             }             prev = Some((lat, lon));             coords.push(lon);             coords.push(lat);-            count += 1;         }     }      TransitLeg {-        is_transit: true,+        kind: LegKind::Ride,         name: idx.read_str(route.name_off),         feed: idx.feed_name_of(route.feed_idx),-        from_code: idx.read_str(idx.stop(board_stop).code_off),-        to_code: idx.read_str(idx.stop(alight_stop).code_off),+        from_stop: idx.stop_label(board_stop),+        to_stop: idx.stop_label(alight_stop),         headsign: idx.read_str(td.headsign_off),+        route_color: route.color,         dep_secs: dep,         arr_secs: arr,         stop_count: (count - 1).max(0),@@ -995,18 +1482,25 @@ fn make_transit_leg(     } } -fn make_walk_leg(idx: &TransitIndex, from_stop: u32, to_stop: u32) -> TransitLeg {+fn make_walk_leg(+    idx: &TransitIndex,+    from_stop: u32,+    to_stop: u32,+    dep_secs: u32,+    arr_secs: u32,+) -> TransitLeg {     let (flat, flon) = idx.stop_ll(from_stop);     let (tlat, tlon) = idx.stop_ll(to_stop);     TransitLeg {-        is_transit: false,+        kind: LegKind::Walk,         name: "Walk".to_string(),         feed: String::new(),-        from_code: idx.read_str(idx.stop(from_stop).code_off),-        to_code: idx.read_str(idx.stop(to_stop).code_off),+        from_stop: idx.stop_label(from_stop),+        to_stop: idx.stop_label(to_stop),         headsign: String::new(),-        dep_secs: 0,-        arr_secs: 0,+        route_color: 0,+        dep_secs,+        arr_secs,         stop_count: 0,         dist_m: dist_m(flat, flon, tlat, tlon),         coords: vec![flon, flat, tlon, tlat],@@ -1020,5 +1514,1044 @@ const _: () = {     assert!(std::mem::size_of::<TransferRec>() == 8);     assert!(std::mem::size_of::<ServiceRec>() == 12);     assert!(std::mem::size_of::<ExcRec>() == 12);-    let _ = SECS_PER_DAY; };++#[cfg(test)]+mod tests {+    use super::*;++    // --- A minimal TRX2 writer (v3 or v4), so the planner can be exercised+    // without a pack file. It is deliberately independent of+    // `scripts/maps/gtfs_ingest`: if the two drift, these tests fail, which is+    // the point (the real writer lives in another crate and cannot be linked).++    const GRID_CELL_E7: u32 = 200_000; // 0.02 deg, as the ingest tool uses+    const MAX_TRANSFER_M: f64 = 400.0;++    struct Stop {+        lat: f64,+        lon: f64,+        name: &'static str,+        code: &'static str,+    }++    struct Trip {+        start: u32,+        /// `(arr, dep)` per pattern position; `arr[0]` may equal `start`.+        stoptimes: Vec<(u32, u32)>,+        service: u32,+        headsign: &'static str,+    }++    /// A GTFS `shapes.txt` polyline plus, parallel to the route's pattern, each+    /// stop's vertex index within it.+    struct Shape {+        points: Vec<(f64, f64)>,+        stop_vertices: Vec<u32>,+    }++    struct Route {+        name: &'static str,+        color: u32,+        route_type: u32,+        feed: u32,+        pattern: Vec<u32>,+        trips: Vec<Trip>,+        /// v4 ride geometry. `None` reproduces a route the ingester could not+        /// attach a shape to, and is what every route in a v3 blob looks like.+        shape: Option<Shape>,+    }++    struct Service {+        mask: u8,+        start: u32,+        end: u32,+    }++    struct Pack {+        stops: Vec<Stop>,+        routes: Vec<Route>,+        services: Vec<Service>,+        /// `(service_idx, yyyymmdd, added)`, in any order.+        exceptions: Vec<(u32, u32, u32)>,+        /// `(feed name, IANA timezone)`.+        feeds: Vec<(&'static str, &'static str)>,+    }++    #[derive(Default)]+    struct Pool {+        bytes: Vec<u8>,+        map: HashMap<String, u32>,+    }++    impl Pool {+        fn new() -> Pool {+            Pool { bytes: vec![0], map: HashMap::new() }+        }+        fn intern(&mut self, s: &str) -> u32 {+            if s.is_empty() {+                return NONE;+            }+            if let Some(&o) = self.map.get(s) {+                return o;+            }+            let off = self.bytes.len() as u32;+            self.bytes.extend_from_slice(s.as_bytes());+            self.bytes.push(0);+            self.map.insert(s.to_string(), off);+            off+        }+    }++    fn u32b(v: &mut Vec<u8>, x: u32) {+        v.extend_from_slice(&x.to_le_bytes());+    }+    fn i32b(v: &mut Vec<u8>, x: i32) {+        v.extend_from_slice(&x.to_le_bytes());+    }+    fn uvarint(v: &mut Vec<u8>, mut x: u64) {+        loop {+            let b = (x & 0x7f) as u8;+            x >>= 7;+            if x != 0 {+                v.push(b | 0x80);+            } else {+                v.push(b);+                break;+            }+        }+    }+    fn zigzag_varint(v: &mut Vec<u8>, x: i64) {+        uvarint(v, ((x << 1) ^ (x >> 63)) as u64);+    }++    impl Pack {+        /// Serialize to a TRX2 blob at `version`. Overridable so both a+        /// stale-pack rejection and the v3-still-parses guard can be tested;+        /// below v4 the shape sections are omitted entirely.+        fn build_with_version(&self, version: u32) -> Vec<u8> {+            let mut pool = Pool::new();+            let pack_name_off = pool.intern("testpack");++            let n_stops = self.stops.len();+            let mut sec_stops = Vec::new();+            let (mut min_lat, mut min_lon) = (i32::MAX, i32::MAX);+            let (mut max_lat, mut max_lon) = (i32::MIN, i32::MIN);+            let lat_e7: Vec<i32> = self.stops.iter().map(|s| (s.lat * 1e7) as i32).collect();+            let lon_e7: Vec<i32> = self.stops.iter().map(|s| (s.lon * 1e7) as i32).collect();+            for i in 0..n_stops {+                min_lat = min_lat.min(lat_e7[i]);+                min_lon = min_lon.min(lon_e7[i]);+                max_lat = max_lat.max(lat_e7[i]);+                max_lon = max_lon.max(lon_e7[i]);+            }+            for (i, s) in self.stops.iter().enumerate() {+                i32b(&mut sec_stops, lat_e7[i]);+                i32b(&mut sec_stops, lon_e7[i]);+                let n = pool.intern(s.name);+                let c = pool.intern(s.code);+                u32b(&mut sec_stops, n);+                u32b(&mut sec_stops, c);+            }++            // Profiles, deduplicated by encoded body exactly as the writer does.+            let mut profile_bytes: Vec<u8> = Vec::new();+            let mut profile_offsets: Vec<u32> = Vec::new();+            let mut profile_ids: HashMap<Vec<u8>, u32> = HashMap::new();+            let mut intern_profile = |sts: &[(u32, u32)]| -> u32 {+                let mut body = Vec::new();+                uvarint(&mut body, sts.len() as u64);+                let (arr0, dep0) = sts[0];+                uvarint(&mut body, dep0.saturating_sub(arr0) as u64);+                let mut prev_dep = dep0;+                for &(arr, dep) in &sts[1..] {+                    uvarint(&mut body, arr.saturating_sub(prev_dep) as u64);+                    uvarint(&mut body, dep.saturating_sub(arr) as u64);+                    prev_dep = dep;+                }+                if let Some(&id) = profile_ids.get(&body) {+                    return id;+                }+                let id = profile_offsets.len() as u32;+                profile_offsets.push(profile_bytes.len() as u32);+                profile_bytes.extend_from_slice(&body);+                profile_ids.insert(body, id);+                id+            };++            let mut sec_routes = Vec::new();+            let mut sec_route_stops = Vec::new();+            let mut sec_route_trips = Vec::new();+            let mut sec_route_stop_shape = Vec::new();+            let mut sec_route_shape_idx = Vec::new();+            let mut shape_bytes: Vec<u8> = Vec::new();+            // Deduplicated by encoded body, standing in for the real writer's+            // dedup by `shape_id`.+            let mut shape_offsets: HashMap<Vec<u8>, u32> = HashMap::new();+            let mut stop_routes: Vec<Vec<(u32, u32)>> = vec![Vec::new(); n_stops];+            let mut trip_total = 0usize;++            for (ridx, r) in self.routes.iter().enumerate() {+                let first_route_stop = (sec_route_stops.len() / 4) as u32;+                for (pos, &s) in r.pattern.iter().enumerate() {+                    u32b(&mut sec_route_stops, s);+                    let vertex = r+                        .shape+                        .as_ref()+                        .and_then(|sh| sh.stop_vertices.get(pos).copied())+                        .unwrap_or(NONE);+                    u32b(&mut sec_route_stop_shape, vertex);+                    let sr = &mut stop_routes[s as usize];+                    if !sr.iter().any(|&(rr, _)| rr == ridx as u32) {+                        sr.push((ridx as u32, pos as u32));+                    }+                }+                let shape_off = match &r.shape {+                    None => NONE,+                    Some(sh) => {+                        let mut body = Vec::new();+                        u32b(&mut body, sh.points.len() as u32);+                        let (mut plat, mut plon) = (0i64, 0i64);+                        for &(lat, lon) in &sh.points {+                            let lat_e7 = (lat * 1e7).round() as i64;+                            let lon_e7 = (lon * 1e7).round() as i64;+                            zigzag_varint(&mut body, lat_e7 - plat);+                            zigzag_varint(&mut body, lon_e7 - plon);+                            plat = lat_e7;+                            plon = lon_e7;+                        }+                        match shape_offsets.get(&body) {+                            Some(&off) => off,+                            None => {+                                let off = shape_bytes.len() as u32;+                                shape_bytes.extend_from_slice(&body);+                                shape_offsets.insert(body, off);+                                off+                            }+                        }+                    }+                };+                u32b(&mut sec_route_shape_idx, shape_off);+                let trips_off = sec_route_trips.len() as u32;+                let mut ordered: Vec<&Trip> = r.trips.iter().collect();+                ordered.sort_by_key(|t| t.start);+                let mut prev_start = 0u32;+                for t in &ordered {+                    let pid = intern_profile(&t.stoptimes);+                    uvarint(&mut sec_route_trips, t.start.saturating_sub(prev_start) as u64);+                    uvarint(&mut sec_route_trips, pid as u64);+                    uvarint(&mut sec_route_trips, t.service as u64);+                    let h = pool.intern(t.headsign);+                    uvarint(&mut sec_route_trips, h as u64);+                    prev_start = t.start;+                    trip_total += 1;+                }+                let name_off = pool.intern(r.name);+                u32b(&mut sec_routes, name_off);+                u32b(&mut sec_routes, r.color);+                u32b(&mut sec_routes, r.route_type);+                u32b(&mut sec_routes, r.feed);+                u32b(&mut sec_routes, r.pattern.len() as u32);+                u32b(&mut sec_routes, first_route_stop);+                u32b(&mut sec_routes, ordered.len() as u32);+                u32b(&mut sec_routes, trips_off);+            }++            let mut sec_profiles_idx = Vec::new();+            for &o in &profile_offsets {+                u32b(&mut sec_profiles_idx, o);+            }+            u32b(&mut sec_profiles_idx, profile_bytes.len() as u32);++            let mut sec_stop_routes = Vec::new();+            let mut sec_stop_routes_idx = Vec::new();+            let mut sec_stop_route_pos = Vec::new();+            let mut acc = 0u32;+            for sr in &stop_routes {+                u32b(&mut sec_stop_routes_idx, acc);+                for &(r, pos) in sr {+                    u32b(&mut sec_stop_routes, r);+                    u32b(&mut sec_stop_route_pos, pos);+                }+                acc += sr.len() as u32;+            }+            u32b(&mut sec_stop_routes_idx, acc);++            // Footpath transfers: every pair within MAX_TRANSFER_M.+            let mut sec_transfers = Vec::new();+            let mut sec_transfers_idx = Vec::new();+            let mut tacc = 0u32;+            for i in 0..n_stops {+                u32b(&mut sec_transfers_idx, tacc);+                for j in 0..n_stops {+                    if i == j {+                        continue;+                    }+                    let d = dist_m(+                        self.stops[i].lat,+                        self.stops[i].lon,+                        self.stops[j].lat,+                        self.stops[j].lon,+                    );+                    if d <= MAX_TRANSFER_M {+                        u32b(&mut sec_transfers, j as u32);+                        u32b(&mut sec_transfers, (d / WALK_SPEED_M_S).ceil() as u32);+                        tacc += 1;+                    }+                }+            }+            u32b(&mut sec_transfers_idx, tacc);++            let mut sec_services = Vec::new();+            for s in &self.services {+                sec_services.push(s.mask);+                sec_services.extend_from_slice(&[0u8, 0, 0]);+                u32b(&mut sec_services, s.start);+                u32b(&mut sec_services, s.end);+            }++            // Sorted by (service, date) with a CSR index, as v3 requires.+            let mut exc = self.exceptions.clone();+            exc.sort_by_key(|&(s, d, _)| (s, d));+            let mut sec_exceptions = Vec::new();+            let mut sec_exceptions_idx = Vec::new();+            let mut eacc = 0u32;+            let mut ei = 0usize;+            for s in 0..self.services.len() as u32 {+                u32b(&mut sec_exceptions_idx, eacc);+                while exc.get(ei).is_some_and(|&(sidx, _, _)| sidx == s) {+                    let (sidx, date, added) = exc[ei];+                    u32b(&mut sec_exceptions, sidx);+                    u32b(&mut sec_exceptions, date);+                    u32b(&mut sec_exceptions, added);+                    eacc += 1;+                    ei += 1;+                }+            }+            u32b(&mut sec_exceptions_idx, eacc);++            // Sparse grid, keyed by cell id, ascending.+            let cell_col = |lon: i32| ((lon as i64 - min_lon as i64) / GRID_CELL_E7 as i64).max(0);+            let cell_row = |lat: i32| ((lat as i64 - min_lat as i64) / GRID_CELL_E7 as i64).max(0);+            let grid_cols = (cell_col(max_lon) + 1) as u32;+            let grid_rows = (cell_row(max_lat) + 1) as u32;+            let mut grid: HashMap<u32, Vec<u32>> = HashMap::new();+            for i in 0..n_stops {+                let cid = cell_row(lat_e7[i]) as u32 * grid_cols + cell_col(lon_e7[i]) as u32;+                grid.entry(cid).or_default().push(i as u32);+            }+            let mut cell_ids: Vec<u32> = grid.keys().copied().collect();+            cell_ids.sort_unstable();+            let mut sec_grid_cell_ids = Vec::new();+            let mut sec_grid_cell_off = Vec::new();+            let mut sec_grid_stops = Vec::new();+            let mut gacc = 0u32;+            for &cid in &cell_ids {+                u32b(&mut sec_grid_cell_ids, cid);+                u32b(&mut sec_grid_cell_off, gacc);+                for &s in &grid[&cid] {+                    u32b(&mut sec_grid_stops, s);+                }+                gacc += grid[&cid].len() as u32;+            }+            u32b(&mut sec_grid_cell_off, gacc);++            let mut sec_feeds = Vec::new();+            let mut sec_feed_tz = Vec::new();+            for &(name, tz) in &self.feeds {+                let n = pool.intern(name);+                let t = pool.intern(tz);+                u32b(&mut sec_feeds, n);+                u32b(&mut sec_feed_tz, t);+            }++            let mut sections: Vec<&[u8]> = vec![+                &pool.bytes,+                &sec_stops,+                &sec_routes,+                &sec_route_stops,+                &sec_route_trips,+                &profile_bytes,+                &sec_profiles_idx,+                &sec_stop_routes,+                &sec_stop_routes_idx,+                &sec_transfers,+                &sec_transfers_idx,+                &sec_services,+                &sec_exceptions,+                &sec_grid_cell_ids,+                &sec_grid_cell_off,+                &sec_grid_stops,+                &sec_feeds,+                &sec_feed_tz,+                &sec_exceptions_idx,+                &sec_stop_route_pos,+            ];+            // The shape sections exist only from v4, so a v3 blob is byte-identical+            // to what the previous format produced.+            if version >= 4 {+                u32b(&mut sec_route_shape_idx, shape_bytes.len() as u32);+                sections.push(&shape_bytes);+                sections.push(&sec_route_shape_idx);+                sections.push(&sec_route_stop_shape);+            }+            let section_count = sections.len();++            let align = |o: usize| (o + 7) & !7;+            let mut data_off = HEADER_LEN + section_count * 16;+            let mut dir: Vec<(u64, u64)> = Vec::new();+            for s in sections.iter() {+                data_off = align(data_off);+                dir.push((data_off as u64, s.len() as u64));+                data_off += s.len();+            }++            let mut out = Vec::with_capacity(data_off);+            u32b(&mut out, MAGIC);+            u32b(&mut out, version);+            u32b(&mut out, section_count as u32);+            u32b(&mut out, n_stops as u32);+            u32b(&mut out, self.routes.len() as u32);+            u32b(&mut out, trip_total as u32);+            u32b(&mut out, self.services.len() as u32);+            u32b(&mut out, profile_offsets.len() as u32);+            u32b(&mut out, self.feeds.len() as u32);+            u32b(&mut out, cell_ids.len() as u32);+            u32b(&mut out, pack_name_off);+            i32b(&mut out, min_lat);+            i32b(&mut out, min_lon);+            i32b(&mut out, max_lat);+            i32b(&mut out, max_lon);+            i32b(&mut out, min_lat);+            i32b(&mut out, min_lon);+            u32b(&mut out, GRID_CELL_E7);+            u32b(&mut out, grid_cols);+            u32b(&mut out, grid_rows);+            assert_eq!(out.len(), HEADER_LEN);+            for (off, len) in &dir {+                out.extend_from_slice(&off.to_le_bytes());+                out.extend_from_slice(&len.to_le_bytes());+            }+            for s in sections.iter() {+                out.resize(align(out.len()), 0);+                out.extend_from_slice(s);+            }+            out+        }++        fn index(&self) -> TransitIndex {+            TransitIndex::from_bytes(self.build_with_version(VERSION)).expect("index loads")+        }+    }++    /// Weekdays Mon-Fri, all of 2024.+    fn weekdays() -> Service {+        Service { mask: 0b0011_1111 & 0b0001_1111, start: 20_240_101, end: 20_241_231 }+    }++    /// Three stops ~1 km apart on one route, with an 08:00 and an 09:00 trip.+    fn one_route_pack() -> Pack {+        Pack {+            stops: vec![+                Stop { lat: 37.700, lon: -122.400, name: "Alpha", code: "A1" },+                Stop { lat: 37.710, lon: -122.400, name: "Beta", code: "B2" },+                Stop { lat: 37.720, lon: -122.400, name: "Gamma", code: "C3" },+            ],+            routes: vec![Route {+                name: "N",+                color: 0x0000FF,+                route_type: 0,+                feed: 0,+                pattern: vec![0, 1, 2],+                trips: vec![+                    Trip {+                        start: 28_800,+                        stoptimes: vec![(28_800, 28_800), (29_100, 29_160), (29_400, 29_400)],+                        service: 0,+                        headsign: "Downtown",+                    },+                    Trip {+                        start: 32_400,+                        stoptimes: vec![(32_400, 32_400), (32_700, 32_760), (33_000, 33_000)],+                        service: 0,+                        headsign: "Downtown",+                    },+                ],+                shape: None,+            }],+            services: vec![weekdays()],+            exceptions: Vec::new(),+            feeds: vec![("sfmuni", "America/Los_Angeles")],+        }+    }++    /// [`one_route_pack`] plus a `shapes.txt` polyline that detours east between+    /// each pair of stops, so shaped geometry is distinguishable from a straight+    /// line through the stops by both vertex count and length.+    fn shaped_route_pack() -> Pack {+        let mut pack = one_route_pack();+        pack.routes[0].shape = Some(Shape {+            points: vec![+                (37.700, -122.400),+                (37.705, -122.390),+                (37.710, -122.400),+                (37.715, -122.390),+                (37.720, -122.400),+            ],+            stop_vertices: vec![0, 2, 4],+        });+        pack+    }++    /// 2024-01-03 was a Wednesday.+    fn wednesday() -> QueryDay {+        QueryDay {+            weekday: 2,+            date: 20_240_103,+            prev_weekday: 1,+            prev_date: 20_240_102,+        }+    }++    fn sched(day: QueryDay) -> Schedule<'static> {+        Schedule { day, overlay: None }+    }++    #[test]+    fn plans_a_ride_between_two_stops() {+        let pack = one_route_pack();+        let idx = pack.index();+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");++        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.name, "N");+        assert_eq!(ride.headsign, "Downtown");+        assert_eq!(ride.route_color, 0x0000FF);+        assert_eq!(ride.feed, "sfmuni");+        // Stop *names*, not codes — the UI presents these as names.+        assert_eq!(ride.from_stop, "Alpha");+        assert_eq!(ride.to_stop, "Gamma");+        // Ready at 25000 < 28800, so it takes the 08:00 trip.+        assert_eq!(ride.dep_secs, 28_800);+        assert_eq!(ride.arr_secs, 29_400);+        assert_eq!(ride.stop_count, 2);+    }++    #[test]+    fn emits_a_wait_leg_before_a_ride() {+        let pack = one_route_pack();+        let idx = pack.index();+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let wait = legs.iter().find(|l| l.kind == LegKind::Wait).expect("a wait leg");+        // No access-walk leg is emitted here (the origin is on the stop), so the+        // wait covers the whole idle period from the query time.+        assert_eq!(wait.dep_secs, 25_000);+        assert_eq!(wait.arr_secs, 28_800);+        assert_eq!(wait.name, "N");+    }++    #[test]+    fn a_sub_minute_wait_is_not_its_own_step() {+        let mut pack = one_route_pack();+        // Departs ~30 s after the traveller is ready: real, but not worth a step.+        pack.routes[0].trips = vec![Trip {+            start: 25_030,+            stoptimes: vec![(25_030, 25_030), (25_330, 25_330), (25_630, 25_630)],+            service: 0,+            headsign: "Downtown",+        }];+        let idx = pack.index();+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        assert!(legs.iter().any(|l| l.kind == LegKind::Ride));+        assert!(+            !legs.iter().any(|l| l.kind == LegKind::Wait),+            "a sub-MIN_WAIT_SECS wait must not become its own step"+        );+    }++    #[test]+    fn walk_legs_carry_their_timings() {+        let pack = one_route_pack();+        let idx = pack.index();+        // Offset from the stops so there is a real access and egress walk.+        let legs = plan(&idx, 37.6994, -122.4004, 37.7206, -122.4004, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let walks: Vec<&TransitLeg> = legs.iter().filter(|l| l.kind == LegKind::Walk).collect();+        assert_eq!(walks.len(), 2, "an access and an egress walk");+        for leg in walks {+            assert!(leg.arr_secs > leg.dep_secs, "walk leg has no timing");+            assert!(leg.dep_secs > 0, "walk leg departs at 0");+        }+    }++    #[test]+    fn finds_a_trip_stored_past_midnight() {+        let mut pack = one_route_pack();+        // A single 24:30:00 trip: GTFS files it under the previous service day.+        pack.routes[0].trips = vec![Trip {+            start: 88_200,+            stoptimes: vec![(88_200, 88_200), (88_500, 88_500), (88_800, 88_800)],+            service: 0,+            headsign: "Owl",+        }];+        let idx = pack.index();++        // 00:20 on Thursday: the trip belongs to Wednesday's service day and runs+        // at 00:30 in Thursday's frame.+        let day = QueryDay {+            weekday: 3,+            date: 20_240_104,+            prev_weekday: 2,+            prev_date: 20_240_103,+        };+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 1_200, sched(day))+            .expect("the 24:30 trip is reachable at 00:20");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.dep_secs, 1_800, "shifted into the query day's frame");+        assert_eq!(ride.arr_secs, 2_400);+    }++    #[test]+    fn a_calendar_dates_removal_cancels_the_day() {+        let mut pack = one_route_pack();+        // exception_type 2 (removed) for the query date.+        pack.exceptions = vec![(0, 20_240_103, 0)];+        let idx = pack.index();+        assert!(+            plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday())).is_none(),+            "service removed for this date, so no journey"+        );+        // The neighbouring date is unaffected — the CSR range is date-keyed.+        let thursday = QueryDay {+            weekday: 3,+            date: 20_240_104,+            prev_weekday: 2,+            prev_date: 20_240_103,+        };+        assert!(plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(thursday)).is_some());+    }++    #[test]+    fn a_calendar_dates_addition_runs_off_schedule() {+        let mut pack = one_route_pack();+        // Saturday is not in the weekday mask, but an exception adds it.+        pack.exceptions = vec![(0, 20_240_106, 1)];+        let idx = pack.index();+        let saturday = QueryDay {+            weekday: 5,+            date: 20_240_106,+            prev_weekday: 4,+            prev_date: 20_240_105,+        };+        assert!(plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(saturday)).is_some());+    }++    #[test]+    fn the_overlay_skips_a_cancelled_trip() {+        let pack = one_route_pack();+        let idx = pack.index();+        // Cancel the 08:00 departure from Alpha (route 0, stop position 0).+        let overlay = DelayOverlay::build(+            &idx,+            &[DelayEntry {+                lat: 37.700,+                lon: -122.400,+                route_name: "N".to_string(),+                sched_secs: 28_800,+                delay_secs: 0,+                cancelled: true,+            }],+        );+        let legs = plan(+            &idx,+            37.700,+            -122.400,+            37.720,+            -122.400,+            25_000,+            Schedule { day: wednesday(), overlay: Some(&overlay) },+        )+        .expect("the 09:00 trip is still available");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.dep_secs, 32_400, "fell through to the 09:00 trip");+    }++    #[test]+    fn the_overlay_delays_a_trip() {+        let pack = one_route_pack();+        let idx = pack.index();+        let overlay = DelayOverlay::build(+            &idx,+            &[DelayEntry {+                lat: 37.700,+                lon: -122.400,+                route_name: "N".to_string(),+                sched_secs: 28_800,+                delay_secs: 300,+                cancelled: false,+            }],+        );+        let legs = plan(+            &idx,+            37.700,+            -122.400,+            37.720,+            -122.400,+            25_000,+            Schedule { day: wednesday(), overlay: Some(&overlay) },+        )+        .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        // The delay propagates to every downstream time on that trip.+        assert_eq!(ride.dep_secs, 29_100);+        assert_eq!(ride.arr_secs, 29_700);+    }++    #[test]+    fn an_unmatched_overlay_entry_leaves_the_schedule_alone() {+        let pack = one_route_pack();+        let idx = pack.index();+        // Right stop, wrong route name -> must not be applied.+        let overlay = DelayOverlay::build(+            &idx,+            &[DelayEntry {+                lat: 37.700,+                lon: -122.400,+                route_name: "38R".to_string(),+                sched_secs: 28_800,+                delay_secs: 600,+                cancelled: false,+            }],+        );+        let legs = plan(+            &idx,+            37.700,+            -122.400,+            37.720,+            -122.400,+            25_000,+            Schedule { day: wednesday(), overlay: Some(&overlay) },+        )+        .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.dep_secs, 28_800);+    }++    #[test]+    fn an_early_running_trip_still_wins_despite_the_scan_break() {+        // Regression: the scan breaks once start_time passes best_dep, which is+        // only sound if realtime can't pull a departure *earlier*. A vehicle+        // running early has a negative delay, so the bound must be widened.+        let mut pack = one_route_pack();+        pack.routes[0].trips.push(Trip {+            start: 36_000,+            stoptimes: vec![(36_000, 36_000), (36_300, 36_360), (36_600, 36_600)],+            service: 0,+            headsign: "Downtown",+        });+        let idx = pack.index();+        // The 10:00 trip is running 80 min early, so it actually leaves at 08:40 —+        // after the 08:00 trip has gone, but before the scheduled 09:00 one.+        let overlay = DelayOverlay::build(+            &idx,+            &[DelayEntry {+                lat: 37.700,+                lon: -122.400,+                route_name: "N".to_string(),+                sched_secs: 36_000,+                delay_secs: -4_800,+                cancelled: false,+            }],+        );+        let legs = plan(+            &idx,+            37.700,+            -122.400,+            37.720,+            -122.400,+            30_600,+            Schedule { day: wednesday(), overlay: Some(&overlay) },+        )+        .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(+            ride.dep_secs, 31_200,+            "the early-running 10:00 trip departs at 08:40, beating the scheduled 09:00"+        );+    }++    #[test]+    fn a_previous_day_trip_that_never_crosses_midnight_is_ignored() {+        // A plain 08:00 trip belongs wholly to its own service day. Swept as+        // "yesterday" it must be dropped, not clamped to 00:00:00 and offered as+        // a departure at midnight.+        let pack = one_route_pack();+        let idx = pack.index();+        let midnight = QueryDay {+            weekday: 3,+            date: 20_240_104,+            prev_weekday: 2,+            prev_date: 20_240_103,+        };+        let board = stop_departures(&idx, 37.700, -122.400, 0, sched(midnight), 10);+        assert!(+            board.iter().all(|d| d.dep_secs > 0),+            "yesterday's daytime trips must not surface at 00:00:00, got {:?}",+            board.iter().map(|d| d.dep_secs).collect::<Vec<_>>()+        );+        assert_eq!(board.len(), 2, "only today's two trips");+    }++    #[test]+    fn resolves_each_feeds_timezone_by_coordinate() {+        // Two feeds in two zones, far enough apart that the grid separates them.+        let pack = Pack {+            stops: vec![+                Stop { lat: 37.700, lon: -122.400, name: "West1", code: "W1" },+                Stop { lat: 37.710, lon: -122.400, name: "West2", code: "W2" },+                Stop { lat: 40.700, lon: -74.000, name: "East1", code: "E1" },+                Stop { lat: 40.710, lon: -74.000, name: "East2", code: "E2" },+            ],+            routes: vec![+                Route {+                    name: "N",+                    color: 0,+                    route_type: 0,+                    feed: 0,+                    pattern: vec![0, 1],+                    trips: vec![Trip {+                        start: 28_800,+                        stoptimes: vec![(28_800, 28_800), (29_400, 29_400)],+                        service: 0,+                        headsign: "West",+                    }],+                    shape: None,+                },+                Route {+                    name: "A",+                    color: 0,+                    route_type: 1,+                    feed: 1,+                    pattern: vec![2, 3],+                    trips: vec![Trip {+                        start: 28_800,+                        stoptimes: vec![(28_800, 28_800), (29_400, 29_400)],+                        service: 0,+                        headsign: "East",+                    }],+                    shape: None,+                },+            ],+            services: vec![weekdays()],+            exceptions: Vec::new(),+            feeds: vec![+                ("sfmuni", "America/Los_Angeles"),+                ("mta", "America/New_York"),+            ],+        };+        let idx = pack.index();+        assert_eq!(idx.timezone_at(37.700, -122.400), "America/Los_Angeles");+        assert_eq!(idx.timezone_at(40.700, -74.000), "America/New_York");+        // Nothing within range -> empty, so the caller keeps the device zone.+        assert_eq!(idx.timezone_at(0.0, 0.0), "");+    }++    #[test]+    fn rejects_a_stale_pack_version() {+        let pack = one_route_pack();+        assert!(+            TransitIndex::from_bytes(pack.build_with_version(VERSION_MIN - 1)).is_none(),+            "a v2 pack must be rejected so Kotlin falls back to MOTIS"+        );+    }++    #[test]+    fn a_v3_pack_still_parses_and_plans() {+        // The rollout guard: a device on the v4 reader must keep serving offline+        // transit from a v3 pack instead of silently falling back to MOTIS.+        let pack = shaped_route_pack();+        let idx = TransitIndex::from_bytes(pack.build_with_version(VERSION_MIN))+            .expect("a v3 pack still loads");+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(+            ride.coords.len(),+            6,+            "v3 carries no shape sections, so the ride draws one vertex per stop"+        );+    }++    #[test]+    fn a_ride_leg_follows_the_gtfs_shape() {+        let pack = shaped_route_pack();+        let idx = pack.index();+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");++        assert_eq!(ride.coords.len(), 10, "all five shape vertices, as [lon, lat] pairs");+        let lons: Vec<f64> = ride.coords.chunks(2).map(|c| c[0]).collect();+        assert!(+            lons.iter().any(|&lon| (lon - -122.390).abs() < 1e-9),+            "the eastward detour vertices are drawn, got {lons:?}"+        );+        // Stop-to-stop is 0.02 deg of latitude; the detour must be longer.+        let crow = dist_m(37.700, -122.400, 37.720, -122.400);+        assert!(+            ride.dist_m > crow,+            "shape distance {} must exceed the crow-flies {crow}",+            ride.dist_m+        );+        assert_eq!(ride.stop_count, 2, "stop_count still counts stops, not vertices");+    }++    #[test]+    fn a_ride_leg_slices_the_shape_to_the_boarded_span() {+        let pack = shaped_route_pack();+        let idx = pack.index();+        // Alpha -> Beta only: vertices 0..=2, not the whole polyline.+        let legs = plan(&idx, 37.700, -122.400, 37.710, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.coords.len(), 6, "vertices 0, 1, 2");+        assert!((ride.coords[0] - -122.400).abs() < 1e-9);+        assert!((ride.coords[1] - 37.700).abs() < 1e-9);+        assert!((ride.coords[4] - -122.400).abs() < 1e-9);+        assert!((ride.coords[5] - 37.710).abs() < 1e-9);+    }++    #[test]+    fn a_route_without_a_shape_draws_stop_to_stop() {+        // A v4 pack whose feed had no usable shape for this route: NONE offsets,+        // and the leg falls back to one vertex per stop.+        let pack = one_route_pack();+        let idx = pack.index();+        assert!(idx.route_shape_off(0).is_none());+        let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+            .expect("a journey exists");+        let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("a ride leg");+        assert_eq!(ride.coords.len(), 6, "Alpha, Beta, Gamma");+        let crow = dist_m(37.700, -122.400, 37.720, -122.400);+        assert!((ride.dist_m - crow).abs() < 1.0);+    }++    #[test]+    fn routes_sharing_a_shape_share_one_blob() {+        let mut pack = shaped_route_pack();+        let twin = Route {+            name: "N-express",+            color: 0,+            route_type: 0,+            feed: 0,+            pattern: vec![0, 2],+            trips: vec![Trip {+                start: 28_800,+                stoptimes: vec![(28_800, 28_800), (29_400, 29_400)],+                service: 0,+                headsign: "Downtown",+            }],+            shape: pack.routes[0].shape.take().map(|sh| Shape {+                points: sh.points.clone(),+                stop_vertices: vec![0, 4],+            }),+        };+        pack.routes[0].shape = twin.shape.as_ref().map(|sh| Shape {+            points: sh.points.clone(),+            stop_vertices: vec![0, 2, 4],+        });+        pack.routes.push(twin);+        let idx = pack.index();+        assert_eq!(+            idx.route_shape_off(0),+            idx.route_shape_off(1),+            "identical polylines must be stored once"+        );+        assert!(idx.route_shape_off(0).is_some());+    }++    #[test]+    fn stop_route_pos_matches_the_route_pattern() {+        // A loop route visiting a stop twice: STOP_ROUTE_POS must record the+        // FIRST occurrence, matching the scan it replaced.+        let mut pack = one_route_pack();+        pack.routes[0].pattern = vec![0, 1, 2, 1];+        pack.routes[0].trips = vec![Trip {+            start: 28_800,+            stoptimes: vec![+                (28_800, 28_800),+                (29_100, 29_100),+                (29_400, 29_400),+                (29_700, 29_700),+            ],+            service: 0,+            headsign: "Loop",+        }];+        let idx = pack.index();+        let (s, e) = idx.stop_routes_range(1);+        assert_eq!(e - s, 1, "one route serves stop 1");+        assert_eq!(idx.stop_route_pos(s), 1, "first occurrence, not the last");+    }++    #[test]+    fn departure_board_lists_upcoming_departures_with_realtime() {+        let pack = one_route_pack();+        let idx = pack.index();+        let board = stop_departures(&idx, 37.700, -122.400, 25_000, sched(wednesday()), 10);+        assert_eq!(board.len(), 2, "both trips are upcoming");+        assert_eq!(board[0].dep_secs, 28_800);+        assert_eq!(board[0].route_name, "N");+        assert_eq!(board[0].headsign, "Downtown");+        assert!(!board[0].real_time, "no overlay, so scheduled only");+        assert_eq!(board[0].delay_secs, 0);++        let overlay = DelayOverlay::build(+            &idx,+            &[DelayEntry {+                lat: 37.700,+                lon: -122.400,+                route_name: "N".to_string(),+                sched_secs: 28_800,+                delay_secs: 120,+                cancelled: false,+            }],+        );+        let live = stop_departures(+            &idx,+            37.700,+            -122.400,+            25_000,+            Schedule { day: wednesday(), overlay: Some(&overlay) },+            10,+        );+        let delayed_dep = live.iter().find(|d| d.dep_secs == 28_800).expect("the 08:00 trip");+        assert!(delayed_dep.real_time);+        assert_eq!(delayed_dep.delay_secs, 120);+        assert!(!delayed_dep.cancelled);+    }++    #[test]+    fn departure_board_excludes_the_terminus() {+        let pack = one_route_pack();+        let idx = pack.index();+        // Gamma is the last stop on the only route, so nothing departs from it.+        assert!(stop_departures(&idx, 37.720, -122.400, 0, sched(wednesday()), 10).is_empty());+    }++    #[test]+    fn returns_none_when_nothing_runs_on_the_query_day() {+        let pack = one_route_pack();+        let idx = pack.index();+        // Sunday is not in the weekday mask and there is no exception.+        let sunday = QueryDay {+            weekday: 6,+            date: 20_240_107,+            prev_weekday: 5,+            prev_date: 20_240_106,+        };+        assert!(plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(sunday)).is_none());+    }+}
scripts/maps/TRANSIT_PACK_NOTES.md
diff --git a/scripts/maps/TRANSIT_PACK_NOTES.md b/scripts/maps/TRANSIT_PACK_NOTES.mdindex c016eef4f7..54c3369599 100644--- a/scripts/maps/TRANSIT_PACK_NOTES.md+++ b/scripts/maps/TRANSIT_PACK_NOTES.md@@ -21,8 +21,15 @@ pmtiles part alone, so map downloads never block on transit. On device, `OfflineRouter` (P11d) discovers every `*.transit` file in the base dir and asks the Rust planner (`transit.rs`) to load each and check whether its bounding box covers the route endpoints, so the on-disk file name does not have-to encode the feed id — the feed id lives *inside* the index (used for-`present_feeds` and route colors).+to encode the feed id - the feed id lives *inside* the index (used for route+provenance and colours).++Packs carry a format version (`TRX2` v3), which the reader checks along with the+section count. A pack built by an older `gtfs_ingest` is therefore **rejected+outright** rather than misread: `TransitIndex::load` returns `None`,+`findTransitRouteNative` returns null, and the app falls back to the online MOTIS+planner. So bumping the format is safe to ship ahead of re-publishing packs -+transit routing degrades to online-only until the new pack lands.  ## Publishing @@ -45,16 +52,33 @@ cp ./out/sf_bay.transit zone_7.transit        # see "feed -> zone" below stage existed in the repo (it was part of an un-checked-in `native-lib.cpp` toolchain), so freshly generated road data could not be loaded. -**P16 fixes this.** `generator.cpp` now emits the **single global** graph in the-exact layout `graph.rs` loads (`nodes.bin`/`edges.bin`/`transit_voyages.bin`/-`transit_attributes.bin`/`lanes.bin`/`metadata.bin`) in one pass — no per-zone-artifacts, no separate merge stage. See-[`README.md` → Single global routing graph](README.md#single-global-routing-graph-p16)+**P16 fixes this.** The graph builder now emits the **single global** graph in+the exact layout `graph.rs` loads (`nodes.bin`/`edges.bin`/`lanes.bin`/+`metadata.bin`/`road_names.bin`) in one pass - no per-zone+artifacts, no separate merge stage. (The builder itself was later ported from+`generator.cpp` to `scripts/maps/osm_ingest`; the on-disk layout did not change.)+See+[`README.md`  Single global routing graph](README.md#single-global-routing-graph-p16) for the on-disk contract and the app download path-(`ZoneDownloadManager.startGraphDownload`). This did **not** touch offline-transit: the transit index is still fully self-contained and independent of the-road graph (access/egress/transfer legs use a straight-line walk heuristic in-`transit.rs`, not the road graph).+(`ZoneDownloadManager.startGraphDownload`). The road graph no longer carries+transit at all - the fake 15-minute-headway synthesizer, `transit_voyages.bin`,+`transit_attributes.bin` and the duplicated per-OSM-node transit nodes are gone.+Offline transit was always independent of it (the transit index is+self-contained, and access/egress/transfer legs are *planned* against a+straight-line walk heuristic in `transit.rs`), so nothing was lost;+`TravelMode.PUBLIC_TRANSIT` in the road graph now simply means walking.++The straight lines are, however, no longer what gets *drawn*. `lib.rs`+post-processes every `LegKind::Walk` leg through the road graph's WALK-mode A\*+and replaces its polyline and distance, and TRX2 v4 carries GTFS `shapes.txt`+geometry so ride legs follow the vehicle's real path. Only the geometry changes:+the legs keep the timings RAPTOR planned them with, because a road-routed walk is+longer than the crow-flies estimate the journey was built around and re-timing it+would desynchronise the journey from the departure it was planned for. A shown+ETA therefore stays slightly optimistic — the same heuristic the pack's+`TRANSFERS` table already rests on — and a road path more than 2.5x the straight+line is rejected as a bad snap, keeping the straight line, so the drawn error is+bounded.  ## Gap (2): zone (Morton) vs feed (metro) boundaries 
scripts/maps/gtfs_ingest/README.md
diff --git a/scripts/maps/gtfs_ingest/README.md b/scripts/maps/gtfs_ingest/README.mdindex 5746571cd5..c4c32e7fa3 100644--- a/scripts/maps/gtfs_ingest/README.md+++ b/scripts/maps/gtfs_ingest/README.md@@ -13,7 +13,10 @@ graph). See `scripts/maps/build_world_transit.sh` for the world pipeline. ## Why Rust + directory input  - **Rust-first (LANGUAGE RULE):** GTFS ingest is done in Rust, not Python. No-  `normalize_gtfs.py`.+  `normalize_gtfs.py`. Its sibling host tool, `scripts/maps/osm_ingest`, follows+  the same rule for the OSM side — it replaced the libosmium `generator.cpp` /+  `poi_extract.cpp`, so no hand-written C++ is left in the Maps pipeline and both+  tools run on Windows. - **Zero dependencies / offline builds:** the tool is `std`-only and detached   from the repo-root Cargo workspace (see the empty `[workspace]` in   `Cargo.toml`), so `cargo build` here resolves without the network and without@@ -47,15 +50,18 @@ device (used for route colours via `GTFSProvider`).  - `<pack>.transit` — the binary TRX2 index. On-disk layout is documented at the   top of `src/index.rs` and **must stay in sync** with `transit.rs`. It holds an-  interned string pool, stops, a FEEDS table, RAPTOR routes (trips grouped by-  identical stop pattern) with **varint-packed per-route trip arrays**,-  **deduplicated timetable profiles** (per-stop run-time shape, varint-delta-  encoded), a stop→routes index, footpath transfers (≤400 m, cross-feed), a+  interned string pool, stops, a FEEDS table (with each feed's IANA timezone from+  `agency.txt`), RAPTOR routes (trips grouped by identical stop pattern) with+  **varint-packed per-route trip arrays**, **deduplicated timetable profiles**+  (per-stop run-time shape, varint-delta encoded), a stop→routes index (with each+  stop's position in the pattern), footpath transfers (≤400 m, cross-feed), a   **sparse spatial grid** (CSR by cell for O(cell) nearest/bbox), and calendar-  service masks + `calendar_dates` exceptions.+  service masks + a CSR-indexed, date-sorted `calendar_dates` exception table, and+  **`shapes.txt` ride geometry** fitted to each route's stop pattern. - `<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.+  stop-times) is visible, plus how many routes got ride geometry.+  `format_version` is 4.  ## Why TRX2 (v2) @@ -67,16 +73,91 @@ same run-time shape — killing both the per-trip stop-time table and the ceilin Section offsets in the directory are u64 so the file may exceed 4 GB. Expected world size drops to roughly **~1.5–4 GB** while staying on u32 indices. +## What v3 added++v3 appends three sections after v2's section 16, so sections 0–16 are+byte-identical and only `VERSION` (3) and `SECTION_COUNT` (20) change. All three+exist so the on-device planner can be *correct* and *fast* on a world pack:++| Section | Payload | Why |+|---|---|---|+| 17 `FEED_TZ` | `u32[feed_count]` string offsets | Each feed's `agency_timezone`. The planner routes in the **feed's** local time; without this a world-merged pack is queried in the device's zone and picks trips hours off. |+| 18 `EXCEPTIONS_IDX` | `u32[service_count + 1]` CSR offsets | `EXCEPTIONS` is now sorted by `(service, date)` with one row per pair, so a `calendar_dates` lookup is a range + binary search instead of a full scan of the pack **per trip**. |+| 19 `STOP_ROUTE_POS` | `u32[]` parallel to `STOP_ROUTES` | A stop's position in each serving route's pattern, replacing a linear scan of the pattern in the RAPTOR hot loop. |++The device reader accepts **v3 and v4**, so an app update and a pack rebuild can+land in either order without offline transit silently degrading to the online+planner in between. A version it does not know is cleanly rejected+(`TransitIndex::load` returns `None`) and the app falls back to the online MOTIS+planner rather than misreading the file.++## What v4 added++v4 appends three more sections, so sections 0–19 are byte-identical to v3 and+only `VERSION` (4) and `SECTION_COUNT` (23) change. They carry GTFS+`shapes.txt` geometry, so a ride leg draws the path the vehicle actually takes+instead of a line through its stops — which also makes its reported distance+truthful, where stop-to-stop under-reports every ride.++| Section | Payload | Why |+|---|---|---|+| 20 `SHAPE_COORDS` | Concatenated blobs: `u32 point_count` then zigzag-varint delta lat/lon | The polylines. Zigzag varints, **not** the `i16` deltas `graph.rs` uses for road geometry: consecutive `shapes.txt` points are routinely far enough apart (highway running) to overflow an `i16` at 1e-7°. |+| 21 `ROUTE_SHAPE_IDX` | `u32[route_count + 1]` byte offsets | Route → blob. `NONE` means "no shape", and the last entry bounds the section. **Not** a prefix sum: routes producing identical geometry share one blob. |+| 22 `ROUTE_STOP_SHAPE` | `u32[]` parallel to `ROUTE_STOPS` | Each pattern stop's vertex index in its route's shape, non-decreasing, so the device slices `shape[vertex(board)..=vertex(alight)]`. |++Fitting a shape to a pattern (`src/shapes.rs`):++1. Take the **modal `shape_id`** across the pattern's trips. Direction+   differences already form distinct patterns, so what lands here is versioned+   shapes or rare express variants; the modal one keeps the common case exact.+2. **Project each stop onto the shape and insert that projection as a vertex**,+   so a boarded span begins and ends exactly on its stop.+3. **Simplify (Douglas–Peucker, ~2.5 m) only between those pinned vertices**, so+   it can never move or drop one, and trim to `[first stop, last stop]`.+4. `shape_dist_traveled` is used when present on **both** `shapes.txt` and+   `stop_times.txt`, strictly as a monotone *ordering* key — it disambiguates a+   route that passes one stop twice. Its units are feed-defined (km, mi, ft) and+   are never read as metres. Otherwise stops are projected by nearest point,+   forced monotonically non-decreasing.+5. **Validate, then fall back.** A stop further than ~150 m from the shape drops+   the whole fit, and the route stores `NONE` so the device draws stop-to-stop as+   before. The tool reports per-run counts of shaped routes, validation drops,+   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.+ ## Testing  `cargo test` runs a round-trip harness (`src/index.rs` `#[cfg(test)]`) that builds a two-feed index and decodes the blob back, asserting profile encoding reconstructs the original arr/dep times, feeds/ids are namespaced without-collision, and the grid nearest-stop lookup is correct.+collision, the grid nearest-stop lookup is correct, per-feed timezones survive,+exceptions are date-sorted and collapsed to one row per `(service, date)`, and+`STOP_ROUTE_POS` agrees with `ROUTE_STOPS`. The v4 cases cover+`shape_dist_traveled` on both files, shapes without it, no `shapes.txt` at all, a+mismatched shape that must fail validation, a pattern whose trips carry two+`shape_id`s, deltas that would overflow an `i16`, and a shape shared by two+routes — asserting monotone, in-bounds vertex indices in every case.++The reader half is tested independently in+`maps/src/main/rust/src/transit.rs`, whose `#[cfg(test)]` module hand-builds TRX2+blobs and plans over them. The two crates cannot link to each other, so each+codec is exercised by an independent counterpart — which is what catches drift in+a format whose spec lives in a doc comment.  ## Known limitations  - Transfers use a straight-line ≤400 m footpath heuristic (not the road graph);-  merging feeds makes these cross-agency for free.-- Service masks cover `calendar.txt` weekdays + `calendar_dates.txt` exceptions;-  per-feed timezone handling is left to the on-device planner's query time.+  merging feeds makes these cross-agency for free. The *drawn* walk legs are+  re-routed along the road graph on device, but their timings stay as RAPTOR+  planned them, so a shown ETA is slightly optimistic.+- A route whose trips genuinely use different roads draws whichever the modal+  `shape_id` describes. Stops, timings and transfers stay correct.+- A feed with no `shapes.txt`, or a route whose shape fails validation, draws its+  ride legs stop-to-stop as before.+- GTFS permits several agencies per feed; `FEED_TZ` takes row 0 of `agency.txt`+  and assumes one timezone per feed. A feed with no `agency.txt` gets no+  timezone, and the device falls back to its own zone (the tool warns).+- A journey spanning two timezones is planned entirely in the origin feed's zone.
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 cc8cc25dd4..b198e48647 100644--- a/scripts/maps/gtfs_ingest/src/gtfs.rs+++ b/scripts/maps/gtfs_ingest/src/gtfs.rs@@ -1,11 +1,17 @@ //! Minimal, dependency-free GTFS reader: an RFC 4180-ish CSV parser plus typed //! loaders for the GTFS files the offline transit index needs-//! (`stops`, `routes`, `trips`, `stop_times`, `calendar`, `calendar_dates`).+//! (`stops`, `routes`, `trips`, `stop_times`, `calendar`, `calendar_dates`,+//! `shapes`). //! //! 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`.  use std::collections::HashMap;+use std::io::BufRead; use std::path::Path;  /// A parsed CSV table: the header row plus data rows (each a `Vec<String>`).@@ -124,3 +130,120 @@ pub fn parse_gtfs_date(s: &str) -> Option<u32> {     }     s.parse().ok() }++/// 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>>,+}++/// Split one CSV line into fields, honouring quotes and `""` escapes. Unlike+/// [`parse_csv`] this cannot span newlines, which `shapes.txt` never needs — all+/// five of its columns are numbers or an id.+fn split_line(line: &str) -> Vec<String> {+    let mut out = Vec::new();+    let mut field = String::new();+    let mut in_quotes = false;+    let mut chars = line.chars().peekable();+    while let Some(c) = chars.next() {+        if in_quotes {+            if c == '"' {+                if chars.peek() == Some(&'"') {+                    field.push('"');+                    let _ = chars.next();+                } else {+                    in_quotes = false;+                }+            } else {+                field.push(c);+            }+        } else if c == '"' {+            in_quotes = true;+        } else if c == ',' {+            out.push(std::mem::take(&mut field));+        } else {+            field.push(c);+        }+    }+    out.push(field);+    out+}++/// A `shapes.txt` row before ordering: `(sequence, lat_e7, lon_e7, dist)`.+type RawShapePoint = (i64, i32, i32, Option<f64>);++/// 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.+pub fn read_shapes(dir: &Path) -> Option<HashMap<String, Shape>> {+    let file = std::fs::File::open(dir.join("shapes.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']));+    let col = |name: &str| {+        header.iter().position(|h| h.trim().trim_start_matches('\u{feff}') == name)+    };+    let (c_id, c_lat, c_lon, c_seq) =+        (col("shape_id")?, col("shape_pt_lat")?, col("shape_pt_lon")?, col("shape_pt_sequence")?);+    let c_dist = col("shape_dist_traveled");++    // (sequence, lat_e7, lon_e7, dist) per shape, sorted once at the end.+    let mut acc: HashMap<String, Vec<RawShapePoint>> = HashMap::new();+    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 f = split_line(line);+        let get = |i: usize| f.get(i).map(|s| s.trim()).unwrap_or("");+        let id = get(c_id);+        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 seq: i64 = get(c_seq).parse().unwrap_or(0);+        let dist = c_dist.and_then(|i| get(i).parse::<f64>().ok());+        acc.entry(id.to_string()).or_default().push((+            seq,+            (lat * 1e7) as i32,+            (lon * 1e7) as i32,+            dist,+        ));+    }++    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());+        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())+                } else {+                    None+                },+            },+        );+    }+    Some(out)+}
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 e80748f7c4..08949bed20 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -1,10 +1,23 @@ //! Build the compact **world** transit index from parsed GTFS tables (possibly //! merged from many feeds) and serialize it to the on-disk `.transit` format. //!-//! ON-DISK FORMAT v2 ("TRX2", little-endian, mmap-friendly, read via+//! ON-DISK FORMAT v4 ("TRX2", little-endian, mmap-friendly, read via //! `read_unaligned` on device). THIS LAYOUT MUST STAY IN SYNC WITH //! `maps/src/main/rust/src/transit.rs`. //!+//! v4 is v3 plus three purely additive sections (20-22) carrying GTFS+//! `shapes.txt` geometry, so a ride leg draws the path the vehicle actually+//! takes — and reports a truthful distance — instead of a line through its+//! stops. The device reader accepts v3 and v4, so a pack rebuild and an app+//! update can land in either order.+//!+//! v3 is v2 plus three purely additive sections (17-19); sections 0-16 are+//! byte-identical. They exist so the on-device planner can be correct and fast+//! on a world pack: `FEED_TZ` lets it route in the *feed's* timezone rather than+//! the device's, `EXCEPTIONS_IDX` turns the `calendar_dates` lookup from a full+//! scan per trip into a CSR range + binary search, and `STOP_ROUTE_POS` removes+//! the per-stop linear scan over a route's stop pattern.+//! //! The v2 redesign exists to make a single global (world) pack feasible. v1 //! stored `(arr,dep)` u32 per stop *per trip* (8 B) and referenced them via a //! `u32 first_stoptime`, so a worldwide pack was ~10–20 GB and bumped the 4.29 B@@ -20,7 +33,7 @@ //!     one pack without id collisions (ids are namespaced per feed at build). //! //! Header (80 bytes; all u32/i32 little-endian):-//!   u32 magic (MAGIC), u32 version (VERSION=2), u32 section_count,+//!   u32 magic (MAGIC), u32 version (VERSION=4), u32 section_count, //!   u32 stop_count, u32 route_count, u32 trip_count, u32 service_count, //!   u32 profile_count, u32 feed_count, u32 grid_cell_count, u32 feed_name_off, //!   i32 min_lat_e7, i32 min_lon_e7, i32 max_lat_e7, i32 max_lon_e7,@@ -59,6 +72,7 @@ //!                        u8[3] _pad, u32 start_date, u32 end_date }. //!  12  EXCEPTIONS      ExcRec[] = { u32 service_idx, u32 date, u32 added } //!                        (added: 1 = service added on date, 0 = removed).+//!                        Sorted by (service_idx, date), one row per pair. //!  13  GRID_CELL_IDS   u32[grid_cell_count] non-empty cell ids, ascending. //!                        cell_id = row*grid_cols + col, row/col from the header //!                        grid origin + grid_cell_e7.@@ -66,14 +80,38 @@ //!  15  GRID_STOPS      u32[stop_count] stop indices grouped by cell (in the //!                        GRID_CELL_IDS order). //!  16  FEEDS           FeedRec[feed_count] = { u32 name_off }.+//!  17  FEED_TZ         u32[feed_count] STRINGS offsets holding each feed's IANA+//!                        timezone from `agency.txt` (`agency_timezone`, row 0),+//!                        or NONE when the feed has no `agency.txt`.+//!  18  EXCEPTIONS_IDX  u32[service_count + 1] prefix offsets into EXCEPTIONS,+//!                        so one service's exceptions are a contiguous,+//!                        date-ascending range.+//!  19  STOP_ROUTE_POS  u32[] parallel to STOP_ROUTES: the position of that stop+//!                        within that route's stop pattern (first occurrence).+//!  20  SHAPE_COORDS    Concatenated polyline blobs. Each blob is `u32+//!                        point_count` then, per point, a zigzag-varint lat+//!                        delta and lon delta (1e-7 deg, cumulative from zero).+//!                        Blobs are self-delimiting and deduplicated, so routes+//!                        producing identical geometry share one.+//!  21  ROUTE_SHAPE_IDX u32[route_count + 1]. For route i, the byte offset of+//!                        its blob in SHAPE_COORDS, or NONE when the feed had no+//!                        usable shape for it. NOT a prefix sum: offsets repeat+//!                        where routes share a blob. The final entry is+//!                        SHAPE_COORDS' byte length, which the reader uses as a+//!                        bound.+//!  22  ROUTE_STOP_SHAPE u32[] parallel to ROUTE_STOPS: that pattern stop's+//!                        vertex index within its route's shape (NONE when the+//!                        route has none). Non-decreasing within a route, so the+//!                        device can slice `shape[vertex(board)..=vertex(alight)]`. -use crate::gtfs::{parse_gtfs_date, parse_gtfs_time, Csv};+use crate::gtfs::{parse_gtfs_date, parse_gtfs_time, Csv, Shape};+use crate::shapes; use std::collections::HashMap;  pub const MAGIC: u32 = 0x5452_4958; // "TRIX"-pub const VERSION: u32 = 2;+pub const VERSION: u32 = 4; pub const NONE: u32 = 0xFFFF_FFFF;-pub const SECTION_COUNT: usize = 17;+pub const SECTION_COUNT: usize = 23; pub const HEADER_LEN: usize = 80;  const MAX_TRANSFER_M: f64 = 400.0;@@ -133,6 +171,8 @@ struct StopTime {     seq: i64,     arr: u32,     dep: u32,+    /// `shape_dist_traveled`, in the feed's own units. An ordering key only.+    dist: Option<f64>, }  /// One input GTFS feed (already parsed). Multiple feeds merge into one pack;@@ -145,6 +185,12 @@ pub struct FeedInput<'a> {     pub stop_times: &'a Csv,     pub calendar: Option<&'a Csv>,     pub calendar_dates: Option<&'a Csv>,+    /// `agency.txt`, read only for `agency_timezone`. GTFS permits several+    /// agencies per feed; we take row 0 and assume one timezone per feed.+    pub agency: Option<&'a Csv>,+    /// `shapes.txt` keyed by `shape_id`. Optional: without it every route in this+    /// feed falls back to stop-to-stop ride geometry on device.+    pub shapes: Option<&'a HashMap<String, Shape>>, }  /// Summary counts reported to the caller / manifest.@@ -162,6 +208,12 @@ pub struct BuildStats {     pub size_bytes: usize,     /// (section name, byte length) for the size-breakdown report.     pub section_sizes: Vec<(&'static str, usize)>,+    /// Routes that got `shapes.txt` ride geometry.+    pub shaped_routes: usize,+    /// Routes whose trips disagreed on `shape_id`; the modal one was used.+    pub multi_shape_routes: usize,+    /// Routes whose shape failed validation and fell back to stop-to-stop.+    pub dropped_shape_routes: usize, }  fn append_u32(v: &mut Vec<u8>, x: u32) {@@ -198,6 +250,10 @@ struct BuiltTrip {     headsign_off: u32,     start_time: u32,             // departure at the first stop     stoptimes: Vec<(u32, u32)>,  // (arr, dep) aligned to the route's stop_pattern+    /// Feed-namespaced `shape_id`, empty when the trip references none.+    shape_key: String,+    /// `shape_dist_traveled` per pattern stop, when every stop has one.+    stop_dists: Option<Vec<f64>>, }  /// Register a service id that appears (e.g. only in calendar_dates), returning@@ -245,12 +301,23 @@ pub fn build_index(     let mut exceptions: Vec<(u32, u32, u32)> = Vec::new();      let mut feed_name_offs: Vec<u32> = Vec::new();+    let mut feed_tz_offs: Vec<u32> = Vec::new();     let mut raptor_routes: Vec<RaptorRoute> = Vec::new();     let mut built_trips: Vec<BuiltTrip> = Vec::new();+    // `shapes.txt` polylines from every feed, keyed "feed|shape_id" so ids from+    // different agencies cannot collide. Only referenced shapes are kept.+    let mut shapes_by_key: HashMap<String, &Shape> = HashMap::new();      for feed in feeds {         let feed_idx = feed_name_offs.len() as u32;         feed_name_offs.push(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+            .agency+            .and_then(|a| a.rows.first().map(|row| a.get(row, "agency_timezone").trim()))+            .unwrap_or("");+        feed_tz_offs.push(pool.intern(tz));          // --- Stops (this feed) -> global indices ---         let mut stop_id_to_idx: HashMap<String, u32> = HashMap::new();@@ -309,6 +376,7 @@ pub fn build_index(             route_id: String,             service_id: String,             headsign_off: u32,+            shape_id: String,         }         let mut trip_meta: HashMap<String, TripMeta> = HashMap::new();         for row in &feed.trips.rows {@@ -323,6 +391,7 @@ pub fn build_index(                     route_id: feed.trips.get(row, "route_id").to_string(),                     service_id: feed.trips.get(row, "service_id").to_string(),                     headsign_off: pool.intern(headsign),+                    shape_id: feed.trips.get(row, "shape_id").trim().to_string(),                 },             );         }@@ -348,10 +417,11 @@ pub fn build_index(                 (None, Some(d)) => (d, d),                 (None, None) => continue,             };+            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 });+                .push(StopTime { stop_idx, seq, arr, dep, dist });         }          // --- Services (calendar.txt) namespaced by feed ---@@ -450,6 +520,21 @@ pub fn build_index(                 headsign_off: tmeta.headsign_off,                 start_time: sts.first().map(|s| s.dep).unwrap_or(0),                 stoptimes: sts.iter().map(|s| (s.arr, s.dep)).collect(),+                shape_key: if tmeta.shape_id.is_empty() {+                    String::new()+                } else {+                    let key = feed_key(&tmeta.shape_id);+                    if let Some(sh) = feed.shapes.and_then(|m| m.get(&tmeta.shape_id)) {+                        shapes_by_key.insert(key.clone(), sh);+                        key+                    } else {+                        String::new()+                    }+                },+                stop_dists: sts+                    .iter()+                    .map(|s| s.dist)+                    .collect::<Option<Vec<f64>>>(),             };             let ti = built_trips.len();             built_trips.push(bt);@@ -507,16 +592,95 @@ pub fn build_index(     let mut sec_route_stops = Vec::new();     let mut sec_route_trips = Vec::new();     let mut stop_routes: Vec<Vec<u32>> = vec![Vec::new(); stop_count];+    // Parallel to `stop_routes`: the stop's position in that route's pattern.+    let mut stop_route_pos: Vec<Vec<u32>> = vec![Vec::new(); stop_count];      let mut trip_total: usize = 0;     let route_count = raptor_routes.len();+    // --- v4 ride geometry ---+    let mut sec_shape_coords: Vec<u8> = Vec::new();+    let mut sec_route_shape_idx = Vec::new();+    let mut sec_route_stop_shape = Vec::new();+    // Deduplicated by encoded blob, so routes producing identical geometry+    // (patterns sharing a `shape_id` and stop list) store it once.+    let mut shape_blob_offsets: HashMap<Vec<u8>, u32> = HashMap::new();+    let mut shaped_routes = 0usize;+    let mut multi_shape_routes = 0usize;+    let mut dropped_shape_routes = 0usize;+     for (ridx, rr) in raptor_routes.iter().enumerate() {+        // Trips of one pattern normally share a `shape_id`. Where they do not+        // (versioned shapes, rare express variants) the modal one keeps the+        // common case exact; direction differences already form distinct+        // patterns, so they never land here.+        let mut votes: HashMap<&str, usize> = HashMap::new();+        for &ti in &rr.trips {+            let k = built_trips[ti].shape_key.as_str();+            if !k.is_empty() {+                *votes.entry(k).or_insert(0) += 1;+            }+        }+        if votes.len() > 1 {+            multi_shape_routes += 1;+        }+        let mut ranked: Vec<(&str, usize)> = votes.into_iter().collect();+        ranked.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));+        let modal = ranked.first().map(|&(k, _)| k.to_string());+        let fitted = modal.as_ref().and_then(|key| {+            let shape = shapes_by_key.get(key.as_str())?;+            let stop_ll: Vec<(i32, i32)> = rr+                .stop_pattern+                .iter()+                .map(|&s| (stop_lat[s as usize], stop_lon[s as usize]))+                .collect();+            // `shape_dist_traveled` only helps when both files carry it, so take+            // it from a trip that actually uses the modal shape.+            let dists = rr+                .trips+                .iter()+                .filter(|&&ti| built_trips[ti].shape_key == *key)+                .find_map(|&ti| built_trips[ti].stop_dists.as_ref())+                .filter(|d| d.len() == rr.stop_pattern.len());+            shapes::fit(shape, &stop_ll, dists.map(|d| d.as_slice()))+        });+        if modal.is_some() {+            if fitted.is_some() {+                shaped_routes += 1;+            } else {+                dropped_shape_routes += 1;+            }+        }+        let shape_off = match &fitted {+            None => NONE,+            Some(f) => {+                let blob = shapes::encode(&f.points);+                match shape_blob_offsets.get(&blob) {+                    Some(&off) => off,+                    None => {+                        let off = sec_shape_coords.len() as u32;+                        sec_shape_coords.extend_from_slice(&blob);+                        shape_blob_offsets.insert(blob, off);+                        off+                    }+                }+            }+        };+        append_u32(&mut sec_route_shape_idx, shape_off);+         let first_route_stop = (sec_route_stops.len() / 4) as u32;-        for &s in &rr.stop_pattern {+        for (pos, &s) in rr.stop_pattern.iter().enumerate() {             append_u32(&mut sec_route_stops, s);+            let vertex = fitted+                .as_ref()+                .and_then(|f| f.stop_vertices.get(pos).copied())+                .unwrap_or(NONE);+            append_u32(&mut sec_route_stop_shape, vertex);             let rv = &mut stop_routes[s as usize];             if rv.last() != Some(&(ridx as u32)) && !rv.contains(&(ridx as u32)) {                 rv.push(ridx as u32);+                // First occurrence only, matching the reader's `break`-on-match+                // scan that this section replaces.+                stop_route_pos[s as usize].push(pos as u32);             }         }         let n_stops = rr.stop_pattern.len() as u32;@@ -548,6 +712,8 @@ pub fn build_index(         append_u32(&mut sec_routes, n_trips);         append_u32(&mut sec_routes, trips_off);     }+    // Terminating bound the reader validates offsets against.+    append_u32(&mut sec_route_shape_idx, sec_shape_coords.len() as u32);      // Profiles index (byte offset per id, plus terminating length).     let mut sec_profiles_idx = Vec::new();@@ -557,14 +723,16 @@ pub fn build_index(     append_u32(&mut sec_profiles_idx, profile_bytes.len() as u32);     let profile_count = profile_offsets.len(); -    // --- stop_routes flattened + index ---+    // --- stop_routes flattened + index (+ parallel stop positions) ---     let mut sec_stop_routes = Vec::new();     let mut sec_stop_routes_idx = Vec::new();+    let mut sec_stop_route_pos = Vec::new();     let mut acc: u32 = 0;-    for sr in &stop_routes {+    for (s, sr) in stop_routes.iter().enumerate() {         append_u32(&mut sec_stop_routes_idx, acc);-        for &r in sr {+        for (k, &r) in sr.iter().enumerate() {             append_u32(&mut sec_stop_routes, r);+            append_u32(&mut sec_stop_route_pos, stop_route_pos[s][k]);         }         acc += sr.len() as u32;     }@@ -629,12 +797,37 @@ pub fn build_index(         append_u32(&mut sec_services, svc_start[i]);         append_u32(&mut sec_services, svc_end[i]);     }+    // --- Exceptions: sorted by (service_idx, date), one row per pair, with a+    // CSR index so the device does a range lookup + binary search instead of a+    // full scan per trip. Sorting is stable, so for duplicate (service, date)+    // rows the last one in CSV order wins — matching the old reader, which+    // scanned every exception without breaking out. ---+    exceptions.sort_by_key(|&(sidx, date, _)| (sidx, date));+    let mut exc_unique: Vec<(u32, u32, u32)> = Vec::with_capacity(exceptions.len());+    for e in exceptions {+        match exc_unique.last_mut() {+            Some(last) if last.0 == e.0 && last.1 == e.1 => *last = e,+            _ => exc_unique.push(e),+        }+    }     let mut sec_exceptions = Vec::new();-    for &(sidx, date, added) in &exceptions {-        append_u32(&mut sec_exceptions, sidx);-        append_u32(&mut sec_exceptions, date);-        append_u32(&mut sec_exceptions, added);+    let mut sec_exceptions_idx = Vec::new();+    let mut eacc: u32 = 0;+    let mut ei = 0usize;+    for s in 0..svc_mask.len() as u32 {+        append_u32(&mut sec_exceptions_idx, eacc);+        while let Some(&(sidx, date, added)) = exc_unique.get(ei) {+            if sidx != s {+                break;+            }+            append_u32(&mut sec_exceptions, sidx);+            append_u32(&mut sec_exceptions, date);+            append_u32(&mut sec_exceptions, added);+            eacc += 1;+            ei += 1;+        }     }+    append_u32(&mut sec_exceptions_idx, eacc);      // --- Spatial grid (sparse CSR keyed by cell id) ---     let grid_lat0 = min_lat;@@ -677,6 +870,10 @@ pub fn build_index(     for &off in &feed_name_offs {         append_u32(&mut sec_feeds, off);     }+    let mut sec_feed_tz = Vec::with_capacity(feed_tz_offs.len() * 4);+    for &off in &feed_tz_offs {+        append_u32(&mut sec_feed_tz, off);+    }      // --- Assemble file: header + directory + aligned sections ---     let section_names: [&'static str; SECTION_COUNT] = [@@ -697,6 +894,12 @@ pub fn build_index(         "GRID_CELL_OFF",         "GRID_STOPS",         "FEEDS",+        "FEED_TZ",+        "EXCEPTIONS_IDX",+        "STOP_ROUTE_POS",+        "SHAPE_COORDS",+        "ROUTE_SHAPE_IDX",+        "ROUTE_STOP_SHAPE",     ];     let sections: [&[u8]; SECTION_COUNT] = [         &pool.bytes,@@ -716,6 +919,12 @@ pub fn build_index(         &sec_grid_cell_off,         &sec_grid_stops,         &sec_feeds,+        &sec_feed_tz,+        &sec_exceptions_idx,+        &sec_stop_route_pos,+        &sec_shape_coords,+        &sec_route_shape_idx,+        &sec_route_stop_shape,     ];      let dir_len = SECTION_COUNT * 16;@@ -777,6 +986,9 @@ pub fn build_index(         max_lon_e7: max_lon,         size_bytes: out.len(),         section_sizes,+        shaped_routes,+        multi_shape_routes,+        dropped_shape_routes,     };     Ok((out, stats)) }@@ -906,6 +1118,61 @@ mod tests {             let s = self.sec_bytes(16);             self.read_str(ru32(s, feed_idx as usize * 4))         }+        fn feed_tz(&self, feed_idx: u32) -> String {+            let s = self.sec_bytes(17);+            self.read_str(ru32(s, feed_idx as usize * 4))+        }+        /// (service_idx, date, added) exceptions for one service, via the CSR.+        fn service_exceptions(&self, service_idx: u32) -> Vec<(u32, u32, u32)> {+            let idx = self.sec_bytes(18);+            let s = self.sec_bytes(12);+            let lo = ru32(idx, service_idx as usize * 4) as usize;+            let hi = ru32(idx, (service_idx as usize + 1) * 4) as usize;+            (lo..hi)+                .map(|i| (ru32(s, i * 12), ru32(s, i * 12 + 4), ru32(s, i * 12 + 8)))+                .collect()+        }+        /// (route_idx, stop_pos) pairs serving `stop`, via STOP_ROUTES(+_POS).+        fn stop_routes(&self, stop: u32) -> Vec<(u32, u32)> {+            let idx = self.sec_bytes(8);+            let routes = self.sec_bytes(7);+            let pos = self.sec_bytes(19);+            let lo = ru32(idx, stop as usize * 4) as usize;+            let hi = ru32(idx, (stop as usize + 1) * 4) as usize;+            (lo..hi).map(|i| (ru32(routes, i * 4), ru32(pos, i * 4))).collect()+        }+        /// Byte offset of route `r`'s shape blob, or `None` when it has none.+        fn route_shape_off(&self, r: u32) -> Option<usize> {+            let idx = self.sec_bytes(21);+            let route_count = self.h(4) as usize;+            assert_eq!(idx.len(), (route_count + 1) * 4, "ROUTE_SHAPE_IDX size");+            let off = ru32(idx, r as usize * 4);+            if off == NONE {+                return None;+            }+            let bound = ru32(idx, route_count * 4) as usize;+            assert_eq!(bound, self.sec_bytes(20).len(), "ROUTE_SHAPE_IDX bound");+            assert!(off as usize + 4 <= bound, "shape offset {off} out of SHAPE_COORDS");+            Some(off as usize)+        }+        /// Decode the whole polyline at byte offset `off` in SHAPE_COORDS.+        fn shape_points(&self, off: usize) -> Vec<(i32, i32)> {+            let s = self.sec_bytes(20);+            let n = ru32(s, off) as usize;+            let mut pos = off + 4;+            let (mut lat, mut lon) = (0i64, 0i64);+            (0..n)+                .map(|_| {+                    lat += zigzag(read_uvarint(s, &mut pos));+                    lon += zigzag(read_uvarint(s, &mut pos));+                    (lat as i32, lon as i32)+                })+                .collect()+        }+        /// Vertex index for ROUTE_STOPS entry `i`.+        fn route_stop_shape(&self, i: u32) -> u32 {+            ru32(self.sec_bytes(22), i as usize * 4)+        }         // Sparse-grid nearest stop to (lat, lon).         fn nearest(&self, lat: f64, lon: f64) -> Option<u32> {             let lat0 = self.h(15) as i32; // grid_lat0_e7 (index 15)@@ -964,6 +1231,61 @@ mod tests {         }     } +    fn agency(tz: &str) -> Csv {+        parse_csv(&format!("agency_id,agency_name,agency_timezone\nA,Agency,{tz}\n"))+    }++    fn zigzag(u: u64) -> i64 {+        ((u >> 1) as i64) ^ -((u & 1) as i64)+    }++    /// `(shape_id, points as (lat, lon), optional shape_dist_traveled)`.+    type ShapeSpec<'a> = (&'a str, Vec<(f64, f64)>, Option<Vec<f64>>);++    fn shape_map(entries: Vec<ShapeSpec>) -> HashMap<String, Shape> {+        entries+            .into_iter()+            .map(|(id, pts, dist)| {+                (+                    id.to_string(),+                    Shape {+                        lat_e7: pts.iter().map(|&(la, _)| (la * 1e7) as i32).collect(),+                        lon_e7: pts.iter().map(|&(_, lo)| (lo * 1e7) as i32).collect(),+                        dist,+                    },+                )+            })+            .collect()+    }++    /// Every route's vertex indices must be non-decreasing and inside its blob,+    /// or the device's `shape[vertex(board)..=vertex(alight)]` slice is garbage.+    fn assert_shape_invariants(r: &Reader) {+        for route in 0..r.h(4) {+            let rec = r.route(route);+            let (n_stops, first) = (rec[4], rec[5]);+            let vertices: Vec<u32> =+                (0..n_stops).map(|p| r.route_stop_shape(first + p)).collect();+            match r.route_shape_off(route) {+                None => assert!(+                    vertices.iter().all(|&v| v == NONE),+                    "route {route} has no shape but carries vertices {vertices:?}"+                ),+                Some(off) => {+                    let n = r.shape_points(off).len() as u32;+                    assert!(+                        vertices.windows(2).all(|w| w[1] >= w[0]),+                        "route {route} vertices not monotone: {vertices:?}"+                    );+                    assert!(+                        vertices.iter().all(|&v| v < n),+                        "route {route} vertices {vertices:?} exceed {n} points"+                    );+                }+            }+        }+    }+     fn feed_a() -> (Csv, Csv, Csv, Csv, Csv) {         let stops = parse_csv(             "stop_id,stop_name,stop_lat,stop_lon,stop_code\n\@@ -1026,6 +1348,16 @@ mod tests {     fn merges_two_feeds_and_roundtrips_profiles() {         let (as_, ar, at, ast, ac) = feed_a();         let (bs, br, bt, bst, bc) = feed_b();+        let aa = age

Diff truncated.