Modern Apps git

← Modern-Apps.git

maps: make a route trips randomly addressable (TRX2 v6)

Commit
a40dcd4735d152118541fb591434c6282cf0c268
Author
vayun-mathur <[email protected]>
When
2026-08-24 21:21 UTC (3 months ago)
Parents
c675940

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 c7d9f70148..c0805401c9 100644--- a/maps/src/main/rust/src/transit.rs+++ b/maps/src/main/rust/src/transit.rs@@ -1,10 +1,15 @@ //! 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 v5 "TRX2") is+//! `scripts/maps/gtfs_ingest` (P11a). The on-disk layout (format v6 "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. //!+//! v6 adds two sections (25-26): a fixed-stride trip table and its CSR directory,+//! so a route's trips are addressable by index instead of only decodable from the+//! route's first trip. See [`Trips`] for what that buys and what it does not.+//! Packs without them fall back to the varint stream, unchanged.+//! //! v5 adds two sections (23-24) holding a per-feed Transitous id prefix and each //! stop's raw GTFS `stop_id`, which compose into a MOTIS stop id //! (`us-ca-SF-bayarea_901201`). That is what lets the realtime `/stoptimes`@@ -38,7 +43,7 @@ use std::collections::HashMap; // --- Format constants (mirror scripts/maps/gtfs_ingest/src/index.rs) --- const MAGIC: u32 = 0x5452_4958; // "TRIX" /// Newest format this reader understands.-const VERSION: u32 = 5;+const VERSION: u32 = 6; /// 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.@@ -47,7 +52,7 @@ pub const NONE: u32 = 0xFFFF_FFFF; const HEADER_LEN: usize = 80; /// Section count of the newest format. The section directory is sized to this /// and an older pack simply leaves the trailing entries empty.-const SECTION_COUNT: usize = 25;+const SECTION_COUNT: usize = 27; const SECTION_COUNT_V3: usize = 20;  const SEC_STRINGS: usize = 0;@@ -75,6 +80,13 @@ const SEC_ROUTE_SHAPE_IDX: usize = 21; const SEC_ROUTE_STOP_SHAPE: usize = 22; const SEC_FEED_MOTIS_PREFIX: usize = 23; const SEC_STOP_GTFS_ID: usize = 24;+/// v6: fixed-stride trip records, so a trip is addressable by index.+const SEC_ROUTE_TRIP_RECS: usize = 25;+/// v6: `u32[route_count + 1]` CSR prefix giving each route's first trip index.+const SEC_ROUTE_TRIP_OFF: usize = 26;++/// Bytes per v6 trip record: `u32 start_time, profile_id, service_idx, headsign_off`.+const TRIP_REC_BYTES: usize = 16;  const WALK_SPEED_M_S: f64 = 1.33; /// Access/egress radius: how far we will walk to the first / from the last stop.@@ -140,6 +152,51 @@ struct TripDec {     headsign_off: u32, } +/// A route's trips, in start-time order, however the pack stores them.+///+/// v6 keeps them in a fixed-stride table, so [`Trips::get`] is an indexed read of 16+/// bytes. That is the point of the format change: the trip scan in [`earliest_trip`]+/// breaks out as soon as a trip's `start_time` passes the bound, but until now+/// [`TransitIndex::route_trips`] had already varint-decoded and heap-allocated *every*+/// trip of the route before the scan began — per route per RAPTOR round, again per leg,+/// and again per departure board. The break could not save the work it was written to+/// save.+///+/// Note what the sorted order does **not** buy: a lower bound. A trip's departure from+/// stop position `p` is `start_time + dep_rel[p]`, and `dep_rel` grows along the route,+/// so a trip starting long before `ready` can still depart after it. Only the upper+/// bound is sound, which is why this exposes indexed access and not a binary search.+///+/// [`Trips::Decoded`] is the pre-v6 path, kept because [`VERSION_MIN`] still accepts+/// those packs; it behaves exactly as before, decode cost included.+enum Trips<'a> {+    Strided { idx: &'a TransitIndex, base: u32, len: u32 },+    Decoded(Vec<TripDec>),+}++impl Trips<'_> {+    fn len(&self) -> usize {+        match self {+            Trips::Strided { len, .. } => *len as usize,+            Trips::Decoded(v) => v.len(),+        }+    }++    fn is_empty(&self) -> bool {+        self.len() == 0+    }++    fn get(&self, i: usize) -> Option<TripDec> {+        if i >= self.len() {+            return None;+        }+        match self {+            Trips::Strided { idx, base, .. } => Some(idx.trip_at(*base + i as u32)),+            Trips::Decoded(v) => Some(v[i]),+        }+    }+}+ /// A decoded run-time profile: per-stop arrival/departure offsets relative to /// the trip's `start_time` (`dep_rel[0] == 0`, `arr_rel[0] <= 0`). struct ProfileDec {@@ -497,6 +554,43 @@ impl TransitIndex {         out     } +    /// Whether this pack carries v6's fixed-stride trip table.+    fn has_trip_table(&self) -> bool {+        self.sec[SEC_ROUTE_TRIP_RECS].1 != 0 && self.sec[SEC_ROUTE_TRIP_OFF].1 != 0+    }++    /// Trip record `i` of the strided table, by global trip index.+    fn trip_at(&self, i: u32) -> TripDec {+        let p = self.sec_ptr(SEC_ROUTE_TRIP_RECS);+        let w = i as usize * 4;+        TripDec {+            start_time: unsafe { read_at::<u32>(p, w) },+            profile_id: unsafe { read_at::<u32>(p, w + 1) },+            service_idx: unsafe { read_at::<u32>(p, w + 2) },+            headsign_off: unsafe { read_at::<u32>(p, w + 3) },+        }+    }++    /// A route's trips, however this pack happens to store them.+    fn trips_for(&self, route_idx: u32, rec: &RouteRec) -> Trips<'_> {+        if !self.has_trip_table() {+            return Trips::Decoded(self.route_trips(rec));+        }+        let off = self.sec_ptr(SEC_ROUTE_TRIP_OFF);+        let base = unsafe { read_at::<u32>(off, route_idx as usize) };+        let end = unsafe { read_at::<u32>(off, route_idx as usize + 1) };+        // A directory that disagrees with the route record would index past the table;+        // fall back rather than read out of bounds.+        let len = end.saturating_sub(base);+        if end < base+            || (end as usize) * TRIP_REC_BYTES > self.sec[SEC_ROUTE_TRIP_RECS].1+            || len != rec.n_trips+        {+            return Trips::Decoded(self.route_trips(rec));+        }+        Trips::Strided { idx: self, base, len }+    }+     /// Decode profile `pid` into per-stop offsets relative to `start_time`.     fn profile(&self, pid: u32) -> ProfileDec {         let off = unsafe { read_at::<u32>(self.sec_ptr(SEC_PROFILES_IDX), pid as usize) } as usize;@@ -1102,7 +1196,7 @@ pub fn plan(         let mut improved: Vec<u32> = Vec::new();         for (&r, &start_pos) in &route_earliest {             let route = idx.route(r);-            let trips = idx.route_trips(&route);+            let trips = idx.trips_for(r, &route);             if trips.is_empty() {                 continue;             }@@ -1115,7 +1209,7 @@ pub fn plan(                 // 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 Some(td) = trips.get(b.trip) else { continue };                     let arr_rel = {                         let p = get_profile(&mut prof_cache, idx, td.profile_id);                         p.arr_rel.get(pos as usize).copied()@@ -1143,11 +1237,18 @@ pub fn plan(                         let board_here = match cur_trip {                             None => true,                             Some(cur) => {-                                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+                                let new = trips.get(cand.trip);+                                let old = trips.get(cur.trip);+                                match (new, old) {+                                    (Some(new), Some(old)) => {+                                        let new_dep =+                                            trip_dep(idx, &mut prof_cache, &new, pos, cand);+                                        let cur_dep =+                                            trip_dep(idx, &mut prof_cache, &old, pos, cur);+                                        new_dep < cur_dep+                                    }+                                    _ => false,+                                }                             }                         };                         if board_here {@@ -1385,8 +1486,10 @@ pub fn stop_departures(             }             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 {+            let trips = idx.trips_for(r, &route);+            for ti in 0..trips.len() {+                let Some(td) = trips.get(ti) else { break };+                let td = &td;                 // 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] {@@ -1494,7 +1597,7 @@ fn earliest_trip(     idx: &TransitIndex,     cache: &mut HashMap<u32, ProfileDec>,     route_idx: u32,-    trips: &[TripDec],+    trips: &Trips,     pos: u32,     ready: u32,     sched: Schedule,@@ -1515,7 +1618,8 @@ fn earliest_trip(         // pass made it an unconditional scan of every trip on the route, each with         // a `service_runs` binary search.         let day_shift = if prev_day { SECS_PER_DAY } else { 0 };-        for (i, td) in trips.iter().enumerate() {+        for i in 0..trips.len() {+            let Some(td) = trips.get(i) else { break };             if best.is_some()                 && td.start_time >= best_dep.saturating_add(slack).saturating_add(day_shift)             {@@ -1526,7 +1630,7 @@ fn earliest_trip(             }             // 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 {+            let Some(scheduled) = trip_sched_dep(idx, cache, &td, pos, prev_day) else {                 continue;             };             let adj = sched.adjustment(route_idx, pos, scheduled);@@ -1553,8 +1657,8 @@ fn make_transit_leg(     alight_stop: u32, ) -> TransitLeg {     let route = idx.route(route_idx);-    let trips = idx.route_trips(&route);-    let td = trips.get(boarding.trip).copied().unwrap_or(TripDec {+    let trips = idx.trips_for(route_idx, &route);+    let td = trips.get(boarding.trip).unwrap_or(TripDec {         start_time: 0,         profile_id: 0,         service_idx: 0,@@ -1805,6 +1909,8 @@ mod tests {             let n_stops = self.stops.len();             let mut sec_stops = Vec::new();             let mut sec_stop_gtfs_id = Vec::new();+            let mut sec_route_trip_recs = Vec::new();+            let mut sec_route_trip_off = 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();@@ -1907,6 +2013,8 @@ mod tests {                 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);+                // The v6 CSR prefix: this route's first trip in the strided table.+                u32b(&mut sec_route_trip_off, trip_total as u32);                 let mut prev_start = 0u32;                 for t in &ordered {                     let pid = intern_profile(&t.stoptimes);@@ -1915,6 +2023,13 @@ mod tests {                     uvarint(&mut sec_route_trips, t.service as u64);                     let h = pool.intern(t.headsign);                     uvarint(&mut sec_route_trips, h as u64);+                    // Both forms are written, so a v6 blob and the v3-v5 blob it would+                    // have been carry the same trips and the two reader paths can be+                    // compared directly.+                    u32b(&mut sec_route_trip_recs, t.start);+                    u32b(&mut sec_route_trip_recs, pid);+                    u32b(&mut sec_route_trip_recs, t.service);+                    u32b(&mut sec_route_trip_recs, h);                     prev_start = t.start;                     trip_total += 1;                 }@@ -2075,6 +2190,13 @@ mod tests {                 sections.push(&sec_feed_motis_prefix);                 sections.push(&sec_stop_gtfs_id);             }+            // v6 adds the fixed-stride trip table and its CSR directory. The prefix+            // needs its final total, which is only known once every route is written.+            if version >= 6 {+                u32b(&mut sec_route_trip_off, trip_total as u32);+                sections.push(&sec_route_trip_recs);+                sections.push(&sec_route_trip_off);+            }             let section_count = sections.len();              let align = |o: usize| (o + 7) & !7;@@ -2696,6 +2818,69 @@ mod tests {         );     } +    /// The strided trip table is only a storage change, so every version of the same+    /// pack has to plan identically. Asserted across the whole version window rather+    /// than just v6-vs-v5, because [`Trips`] is the only thing keeping the two reader+    /// paths in agreement and nothing else would notice them drifting.+    #[test]+    fn every_version_of_a_pack_plans_the_same_journey() {+        let pack = one_route_pack();+        let mut baseline: Option<Vec<(u32, u32, String)>> = None;+        for version in [VERSION_MIN, 4, 5, VERSION] {+            let idx = TransitIndex::from_bytes(pack.build_with_version(version))+                .unwrap_or_else(|| panic!("v{version} loads"));+            let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched(wednesday()))+                .unwrap_or_else(|| panic!("v{version} finds a journey"));+            let shape: Vec<(u32, u32, String)> = legs+                .iter()+                .map(|l| (l.dep_secs, l.arr_secs, l.name.clone()))+                .collect();+            match &baseline {+                None => baseline = Some(shape),+                Some(want) => assert_eq!(*want, shape, "v{version} planned a different journey"),+            }+        }+    }++    #[test]+    fn every_version_of_a_pack_lists_the_same_departures() {+        let pack = one_route_pack();+        let mut baseline: Option<Vec<u32>> = None;+        for version in [VERSION_MIN, 4, 5, VERSION] {+            let idx = TransitIndex::from_bytes(pack.build_with_version(version))+                .unwrap_or_else(|| panic!("v{version} loads"));+            let board = stop_departures(&idx, 37.700, -122.400, 0, sched(wednesday()), 10);+            let times: Vec<u32> = board.iter().map(|d| d.dep_secs).collect();+            match &baseline {+                None => baseline = Some(times),+                Some(want) => assert_eq!(*want, times, "v{version} listed different departures"),+            }+        }+    }++    /// A v6 pack still carries the varint stream, so a trip table that disagrees with+    /// the route records is recoverable — and must be recovered from rather than read+    /// out of bounds.+    #[test]+    fn a_trip_table_disagreeing_with_the_route_falls_back_to_the_varint_stream() {+        let pack = one_route_pack();+        let idx = TransitIndex::from_bytes(pack.build_with_version(VERSION)).expect("v6 loads");+        let route = idx.route(0);+        assert!(idx.has_trip_table(), "the fixture writes the table");+        // What the strided path returns, to compare the fallback against.+        let want: Vec<u32> = {+            let trips = idx.trips_for(0, &route);+            (0..trips.len()).map(|i| trips.get(i).unwrap().start_time).collect()+        };+        let mut wrong = route;+        wrong.n_trips += 1;+        let trips = idx.trips_for(0, &wrong);+        assert!(matches!(trips, Trips::Decoded(_)), "a mismatched span must not be trusted");+        let got: Vec<u32> =+            (0..want.len()).map(|i| trips.get(i).unwrap().start_time).collect();+        assert_eq!(want, got, "the fallback decodes the same trips");+    }+     #[test]     fn a_v3_pack_still_parses_and_plans() {         // The rollout guard: a device on the newest reader must keep serving
scripts/maps/gtfs_ingest/README.md
diff --git a/scripts/maps/gtfs_ingest/README.md b/scripts/maps/gtfs_ingest/README.mdindex 13d51df9ed..11221d8477 100644--- a/scripts/maps/gtfs_ingest/README.md+++ b/scripts/maps/gtfs_ingest/README.md@@ -61,7 +61,7 @@ device (used for route colours via `GTFSProvider`). - `<pack>.transit.json` — a small manifest with counts, bbox and a **per-section   byte breakdown** so the compression win (profiles vs the old per-trip   stop-times) is visible, plus how many routes got ride geometry.-  `format_version` is 5.+  `format_version` is 6.  ## Why TRX2 (v2) @@ -129,6 +129,41 @@ pack. `shapes.txt` and `stop_times.txt` are the two largest files in a feed, so both are streamed (`gtfs::read_shapes`, `gtfs::stream_stop_times`) rather than parsed into a `Csv` of `String`s — see *Build-time memory* below. +## What v6 added++v6 appends two more sections, so sections 0-24 are byte-identical to v5 and only+`VERSION` (6) and `SECTION_COUNT` (27) change. They make a route's trips+**randomly addressable**.++| Section | Payload | Why |+|---|---|---|+| 25 `ROUTE_TRIP_RECS` | Fixed-stride `TripRec[trip_count]` = `{ u32 start_time, profile_id, service_idx, headsign_off }`, each route's trips contiguous and start-time ordered | A trip is an index, so a scan reads only the trips it looks at. |+| 26 `ROUTE_TRIP_OFF` | `u32[route_count + 1]` CSR prefix | Route *i*'s trips are `ROUTE_TRIP_RECS[off[i]..off[i+1]]`. |++`ROUTE_TRIPS` is still written, unchanged. Both views ship because the device+reader's `VERSION_MIN` is still 3: a pack rebuild and an app update can land in+either order, and a reader that finds no table falls back to the varint stream.+The two are written in the same loop, and a test asserts they decode to the same+trips, because a writer emitting two disagreeing views is exactly the failure the+device would inherit silently.++**What this buys, precisely.** `earliest_trip` scans a route's trips in start-time+order and breaks as soon as `start_time` passes the bound it can still improve on.+Reading the varint stream defeated that: `route_trips` decoded and heap-allocated+*every* trip of the route before the scan began - per route per RAPTOR round, again+per leg, and again per departure board, over 28.4 M trips in a planetary pack. With+the table the break actually saves the work it was written to save.++**What it does not buy: a lower bound.** A trip's departure from stop position `p`+is `start_time + dep_rel[p]`, and `dep_rel` grows along the route, so a trip+starting well before the passenger is ready can still depart after them. Only the+upper bound is sound, which is why the reader exposes indexed access and not a+binary search over start times.++The cost is size: 16 bytes per trip against roughly 11.8 for the varint encoding,+so about +120 MB on a planetary pack that already carries 335 MB of `ROUTE_TRIPS`.+Dropping the varint stream once `VERSION_MIN` moves past 5 recovers all of it.+ ## Build-time memory  A world build is bound by RAM, not by pack size. The pack is ~1.5–4 GB, but the
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 378500695b..614b0bc5a0 100644--- a/scripts/maps/gtfs_ingest/src/index.rs+++ b/scripts/maps/gtfs_ingest/src/index.rs@@ -42,7 +42,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=5), u32 section_count,+//!   u32 magic (MAGIC), u32 version (VERSION=6), 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,@@ -121,6 +121,20 @@ //!                        MOTIS stop id. Kept separate from `StopRec.code_off`, //!                        which falls back to `stop_id` only when `stop_code` is //!                        blank and so cannot be relied on.+//!  25  ROUTE_TRIP_RECS v6. Fixed-stride TripRec[trip_count] = { u32 start_time,+//!                        u32 profile_id, u32 service_idx, u32 headsign_off },+//!                        each route's trips contiguous and in start-time order.+//!                        The same trips as ROUTE_TRIPS, which is still written:+//!                        the device reader's version window accepts packs that+//!                        only have the varint stream, so both views ship.+//!                        A trip is addressable by index here, which is the point -+//!                        the varint stream has to be decoded from a route's first+//!                        trip, so a scan that breaks early still paid to decode+//!                        every trip of the route before it started.+//!  26  ROUTE_TRIP_OFF  v6. u32[route_count + 1] CSR prefix: route i's trips are+//!                        ROUTE_TRIP_RECS[off[i]..off[i+1]]. Disagreeing with+//!                        RouteRec.n_trips makes the reader fall back to the+//!                        varint stream rather than index past the table.  use crate::gtfs; use crate::gtfs::{parse_gtfs_date, Csv, Shape};@@ -130,12 +144,12 @@ use std::io::Write; use std::path::Path;  pub const MAGIC: u32 = 0x5452_4958; // "TRIX"-pub const VERSION: u32 = 5;+pub const VERSION: u32 = 6; /// Oldest version the device reader still accepts, mirrored from /// `maps/src/main/rust/src/transit.rs` so the host reader agrees on the range. pub const VERSION_MIN: u32 = 3; pub const NONE: u32 = 0xFFFF_FFFF;-pub const SECTION_COUNT: usize = 25;+pub const SECTION_COUNT: usize = 27; pub const HEADER_LEN: usize = 80;  const MAX_TRANSFER_M: f64 = 400.0;@@ -595,6 +609,13 @@ pub struct IndexBuilder {     sec_routes: Vec<u8>,     sec_route_stops: Vec<u8>,     sec_route_trips: Vec<u8>,+    /// v6: fixed-stride `u32 start_time, profile_id, service_idx, headsign_off` per+    /// trip, per route contiguous, so a trip is addressable by index. Written+    /// alongside ROUTE_TRIPS rather than replacing it, because the device reader's+    /// version window still accepts packs that only have the varint stream.+    sec_route_trip_recs: Vec<u8>,+    /// v6: `u32[route_count + 1]` CSR prefix into [`Self::sec_route_trip_recs`].+    sec_route_trip_off: Vec<u8>,     sec_route_shape_idx: Vec<u8>,     sec_route_stop_shape: Vec<u8>,     sec_stop_routes: Vec<u8>,@@ -641,6 +662,8 @@ impl IndexBuilder {             sec_routes: Vec::new(),             sec_route_stops: Vec::new(),             sec_route_trips: Vec::new(),+            sec_route_trip_recs: Vec::new(),+            sec_route_trip_off: Vec::new(),             sec_route_shape_idx: Vec::new(),             sec_route_stop_shape: Vec::new(),             sec_stop_routes: Vec::new(),@@ -692,6 +715,8 @@ impl IndexBuilder {             + self.sec_routes.len()             + self.sec_route_stops.len()             + self.sec_route_trips.len()+            + self.sec_route_trip_recs.len()+            + self.sec_route_trip_off.len()             + self.sec_route_shape_idx.len()             + self.sec_route_stop_shape.len()             + self.sec_stop_routes.len()@@ -1092,6 +1117,8 @@ impl IndexBuilder {                     .to_string()             })?;             let mut prev_start: u32 = 0;+            // The CSR prefix: this route's first trip in the strided table.+            append_u32(&mut self.sec_route_trip_off, self.trip_total as u32);             for &ti in &trip_order {                 let bt = &built_trips[ti];                 let profile_id = self.profiles.intern(&bt.stoptimes)?;@@ -1100,6 +1127,10 @@ impl IndexBuilder {                 write_uvarint(&mut self.sec_route_trips, profile_id as u64);                 write_uvarint(&mut self.sec_route_trips, bt.service_idx as u64);                 write_uvarint(&mut self.sec_route_trips, bt.headsign_off as u64);+                append_u32(&mut self.sec_route_trip_recs, bt.start_time);+                append_u32(&mut self.sec_route_trip_recs, profile_id);+                append_u32(&mut self.sec_route_trip_recs, bt.service_idx);+                append_u32(&mut self.sec_route_trip_recs, bt.headsign_off);                 prev_start = bt.start_time;                 self.trip_total += 1;             }@@ -1162,6 +1193,8 @@ impl IndexBuilder {             sec_routes,             sec_route_stops,             sec_route_trips,+            sec_route_trip_recs,+            mut sec_route_trip_off,             mut sec_route_shape_idx,             sec_route_stop_shape,             sec_stop_routes,@@ -1388,7 +1421,12 @@ impl IndexBuilder {             "ROUTE_STOP_SHAPE",             "FEED_MOTIS_PREFIX",             "STOP_GTFS_ID",+            "ROUTE_TRIP_RECS",+            "ROUTE_TRIP_OFF",         ];+        // Close the CSR prefix: one past the last route's trips, i.e. the total. Done+        // here because it is only known once every feed's routes have been written.+        append_u32(&mut sec_route_trip_off, trip_total as u32);         let sections: [&[u8]; SECTION_COUNT] = [             &pool.bytes,             &sec_stops,@@ -1415,6 +1453,8 @@ impl IndexBuilder {             &sec_route_stop_shape,             &sec_feed_motis_prefix,             &sec_stop_gtfs_id,+            &sec_route_trip_recs,+            &sec_route_trip_off,         ];          let dir_len = SECTION_COUNT * 16;@@ -1730,6 +1770,26 @@ mod tests {         // Both reference the same profile id (dedup).         assert_eq!(trips[0].profile_id, trips[1].profile_id); +        // v6's strided table must be the same trips as the varint stream, for every+        // route. Two views of one thing, written in the same loop, so a disagreement is+        // a writer bug the device reader would silently inherit.+        for route_idx in 0..r.route_count() {+            let rec = r.route(route_idx);+            let varint = r.route_trips(&rec);+            let strided = r.route_trips_strided(route_idx);+            assert_eq!(+                varint.len(),+                strided.len(),+                "route {route_idx} trip count differs between the two views"+            );+            for (a, b) in varint.iter().zip(strided.iter()) {+                assert_eq!(a.start_time, b.start_time, "route {route_idx} start_time");+                assert_eq!(a.profile_id, b.profile_id, "route {route_idx} profile_id");+                assert_eq!(a.service_idx, b.service_idx, "route {route_idx} service_idx");+                assert_eq!(a.headsign_off, b.headsign_off, "route {route_idx} headsign_off");+            }+        }+         // Reconstruct absolute arr/dep for trip T2 (start 09:00) and compare.         let prof = r.profile(trips[1].profile_id);         let start = trips[1].start_time as i64;
scripts/maps/gtfs_ingest/src/reader.rs
diff --git a/scripts/maps/gtfs_ingest/src/reader.rs b/scripts/maps/gtfs_ingest/src/reader.rsindex 7e09be85f1..fe5037eeaa 100644--- a/scripts/maps/gtfs_ingest/src/reader.rs+++ b/scripts/maps/gtfs_ingest/src/reader.rs@@ -38,6 +38,11 @@ pub const SEC_ROUTE_SHAPE_IDX: usize = 21; pub const SEC_ROUTE_STOP_SHAPE: usize = 22; pub const SEC_FEED_MOTIS_PREFIX: usize = 23; pub const SEC_STOP_GTFS_ID: usize = 24;+pub const SEC_ROUTE_TRIP_RECS: usize = 25;+pub const SEC_ROUTE_TRIP_OFF: usize = 26;++/// Bytes per v6 trip record: `u32 start_time, profile_id, service_idx, headsign_off`.+pub const TRIP_REC_BYTES: usize = 16;  fn ru32(b: &[u8], off: usize) -> u32 {     u32::from_le_bytes([b[off], b[off + 1], b[off + 2], b[off + 3]])@@ -303,6 +308,37 @@ impl Reader {         out     } +    /// A route's trips read from v6's fixed-stride table instead of the varint stream.+    ///+    /// The point of the table is that a trip is addressable by index, so the device+    /// reader can stop decoding trips its scan never looks at. Here it serves a second+    /// purpose: it is an independent decoding of the same data, so+    /// [`Self::route_trips_strided`] and [`Self::route_trips`] disagreeing means the+    /// writer emitted two views that do not match.+    pub fn route_trips_strided(&self, route_idx: u32) -> Vec<TripRec> {+        let off = self.sec_bytes(SEC_ROUTE_TRIP_OFF);+        let recs = self.sec_bytes(SEC_ROUTE_TRIP_RECS);+        if (route_idx as usize + 2) * 4 > off.len() {+            return Vec::new();+        }+        let base = ru32(off, route_idx as usize * 4) as usize;+        let end = ru32(off, (route_idx as usize + 1) * 4) as usize;+        if end < base || end * TRIP_REC_BYTES > recs.len() {+            return Vec::new();+        }+        (base..end)+            .map(|i| {+                let at = i * TRIP_REC_BYTES;+                TripRec {+                    start_time: ru32(recs, at),+                    profile_id: ru32(recs, at + 4),+                    service_idx: ru32(recs, at + 8),+                    headsign_off: ru32(recs, at + 12),+                }+            })+            .collect()+    }+     /// Profile `pid` as per-stop `(arr, dep)` offsets relative to a trip's     /// `start_time`. `arr[0]` is negative by the first dwell.     pub fn profile(&self, pid: u32) -> Vec<(i64, i64)> {