maps: run archive tests on synthetic archives (#tests)
- Commit
1e08312139127e25508077fcd0403c73a5772734- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-15 17:51 UTC (20 days ago)
- Parents
aff11fe
The two real-archive tests in tests/real_archive.rs were #[ignore]d behind MAMAPS_REAL_ARCHIVE, so the default suite never exercised the router's single-archive loaders. They now build small synthetic archives in temp files and run against them by default; MAMAPS_REAL_ARCHIVE still selects the planet file, with the planet-only assertions (100M+ node count, city routes, SF Caltrain departures) kept behind that branch. The synthetic graph (tests/real_archive/graph_fixture.rs) is a 3x3 San Francisco node grid packed as graph sidecar sections: 24 bidirectional named edges with distances from their node coordinates, one edge carrying lane masks, an elevation profile, and an identity MOVL highway overlay. The tests assert the same behaviour as the planet run: Graph::load_archive accepts the container, the overlay attaches, drive/walk/bike routes resolve with plausible lengths, named steps and elevations. The synthetic transit pack (tests/real_archive/pack.rs, mirroring the src/transit_part6.rs test writer) carries three stops on one route with 08:00/09:00 trips. The test asserts the same behaviours as the planet run through TransitIndex::load_archive: coverage, a sorted departure board, the feed timezone, the MOTIS stop id, rail lines in the bbox, and a planned ride with exact times. Left ignored, deliberately: the_traffic_square_walk in traffic_update_bench.rs is a timing harness over the planet graph, a measurement by design. offlinerouter ignored 3 -> 1. Verified: cargo test --profile fast -p offlinerouter (default run) 95 passed, 0 failed, 1 ignored (was 93 passed, 3 ignored); both converted tests pass with no env var set.
Diff
maps/src/main/rust/tests/real_archive.rs
diff --git a/maps/src/main/rust/tests/real_archive.rs b/maps/src/main/rust/tests/real_archive.rsindex 3b8981d43a..1046ec0e35 100644--- a/maps/src/main/rust/tests/real_archive.rs+++ b/maps/src/main/rust/tests/real_archive.rs@@ -1,11 +1,14 @@ //! The offline router (graph + highway overlay + transit) against a REAL planet archive //! (`planet4.mamaps`, or the byte-identical local build `scripts/maps/inputs/world.mamaps`). //!-//! Ignored by default and gated on `MAMAPS_REAL_ARCHIVE`:+//! By default these tests run against small SYNTHETIC archives built+//! in-test (see `graph_fixture.rs` and `pack.rs`): the same loader,+//! routing and planning paths, without the 80 GB input. Set the env+//! var to run them against the planet instead: //! //! ```text //! MAMAPS_REAL_ARCHIVE=/path/to/world.mamaps \-//! cargo test -p offlinerouter --release --test real_archive -- --ignored --nocapture --test-threads=1+//! cargo test -p offlinerouter --test real_archive -- --nocapture --test-threads=1 //! ``` //! //! Same calls the JNI layer makes (`Graph::load_archive`, `prepare_routing` +@@ -20,6 +23,11 @@ use offlinerouter::transit::{ plan, rail_lines, stop_departures, LegKind, QueryDay, Schedule, TransitIndex, }; +#[path = "real_archive/graph_fixture.rs"]+mod graph_fixture;+#[path = "real_archive/pack.rs"]+mod pack;+ const ENV: &str = "MAMAPS_REAL_ARCHIVE"; /// (label, from (lat, lon), to (lat, lon), travel mode).@@ -28,10 +36,7 @@ type RouteCase = (&'static str, (f64, f64), (f64, f64), i32); fn archive() -> Option<String> { match std::env::var(ENV) { Ok(p) if !p.trim().is_empty() && std::path::Path::new(&p).is_file() => Some(p),- _ => {- eprintln!("{ENV} not set (or not a file): real-archive test skipped");- None- }+ _ => None, } } @@ -57,9 +62,16 @@ fn route(g: &Graph, from: (f64, f64), to: (f64, f64), mode: i32) -> Option<Vec<S } #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn graph_sections_load_and_routes_resolve() {- let Some(path) = archive() else { return };+ let (path, planet) = match archive() {+ Some(p) => (p, true),+ None => (+ graph_fixture::write_temp("graph", &graph_fixture::graph_archive())+ .to_string_lossy()+ .into_owned(),+ false,+ ),+ }; let t0 = std::time::Instant::now(); let g = Graph::load_archive(&path).expect("Graph::load_archive refused the archive"); println!(@@ -70,10 +82,16 @@ fn graph_sections_load_and_routes_resolve() { g.has_elevation(), t0.elapsed() );- assert!(g.node_count > 100_000_000, "not a planet graph");+ if planet {+ assert!(g.node_count > 100_000_000, "not a planet graph");+ } else {+ assert_eq!(g.node_count, 9, "the synthetic grid's node count");+ assert_eq!(g.edge_count, 24, "the synthetic grid's edge count");+ assert!(g.edge_lane_masks(0).is_some(), "lanes section carries edge 0");+ } assert!(g.overlay().is_some(), "highway overlay (kind 14) not attached"); - let cases: &[RouteCase] = &[+ let planet_cases: &[RouteCase] = &[ ("SF drive Ferry Bldg -> Golden Gate Park", (37.7955, -122.3937), (37.7694, -122.4862), DRIVING), ("SF walk Union Sq -> Ferry Bldg", (37.7880, -122.4075), (37.7955, -122.3937), WALK), ("SF bike Mission -> Marina", (37.7599, -122.4148), (37.8037, -122.4368), BICYCLE),@@ -82,6 +100,12 @@ fn graph_sections_load_and_routes_resolve() { ("Tokyo walk Shibuya -> Harajuku", (35.6595, 139.7005), (35.6702, 139.7027), WALK), ("Long drive SF -> LA (overlay)", (37.7749, -122.4194), (34.0522, -118.2437), DRIVING), ];+ let synthetic_cases: &[RouteCase] = &[+ ("grid drive NE -> SW", graph_fixture::node_lat_lon(8), graph_fixture::node_lat_lon(0), DRIVING),+ ("grid walk N edge", graph_fixture::node_lat_lon(6), graph_fixture::node_lat_lon(8), WALK),+ ("grid bike SW -> NE", graph_fixture::node_lat_lon(0), graph_fixture::node_lat_lon(8), BICYCLE),+ ];+ let cases = if planet { planet_cases } else { synthetic_cases }; for &(name, from, to, mode) in cases { let t = std::time::Instant::now(); let steps = route(&g, from, to, mode).unwrap_or_else(|| panic!("{name}: no route"));@@ -103,65 +127,126 @@ fn graph_sections_load_and_routes_resolve() { assert!(s.elevations.is_empty() || s.elevations.len() == s.coords.len() / 2); } }- // Lane guidance (lanes section) shows up on a long drive through big junctions.- let la = route(&g, (37.7749, -122.4194), (34.0522, -118.2437), DRIVING).unwrap();- assert!(la.iter().any(|s| !s.lanes.is_empty()), "no lane guidance on SF -> LA");+ if planet {+ // Lane guidance (lanes section) shows up on a long drive through big junctions.+ let la = route(&g, (37.7749, -122.4194), (34.0522, -118.2437), DRIVING).unwrap();+ assert!(la.iter().any(|s| !s.lanes.is_empty()), "no lane guidance on SF -> LA");+ }+ if !planet {+ std::fs::remove_file(&path).ok();+ } } #[test]-#[ignore = "needs MAMAPS_REAL_ARCHIVE (80 GB planet archive)"] fn transit_section_loads_plans_and_lists_departures() {- let Some(path) = archive() else { return };+ let (path, planet) = match archive() {+ Some(p) => (p, true),+ None => (+ graph_fixture::write_temp("transit", &graph_fixture::transit_archive(&pack::synthetic_pack()))+ .to_string_lossy()+ .into_owned(),+ false,+ ),+ }; assert!(TransitIndex::has_archive_transit(&path), "no transit section (kind 13)"); let t0 = std::time::Instant::now(); let idx = TransitIndex::load_archive(&path).expect("TransitIndex::load_archive refused the archive"); println!("transit: feed {:?}, loaded in {:?}", idx.feed_name(), t0.elapsed());- assert!(idx.covers(37.7749, -122.4194), "transit pack does not cover SF");-- // A weekday mid-morning (Wednesday 2026-11-11), the day this test was written.- let sched = Schedule { day: QueryDay::for_date(2, 20261111), overlay: None };- let nine = 9 * 3600;-- let board = stop_departures(&idx, 37.7764, -122.3943, nine, sched, 10); // SF Caltrain 4th & King- println!("departures at 4th & King: {:?}",- board.iter().map(|d| format!("{} -> {} @{}", d.route_name, d.headsign, d.dep_secs)).collect::<Vec<_>>());- assert!(!board.is_empty(), "no offline departures at SF 4th & King");- assert!(board.windows(2).all(|w| w[0].dep_secs <= w[1].dep_secs));-- let tz = idx.timezone_at(37.7749, -122.4194);- let motis = idx.nearest_stop_motis_id(37.7764, -122.3943);- println!("timezone {tz}, MOTIS stop id {motis:?}");- assert_eq!(tz, "America/Los_Angeles");-- let lines = rail_lines(&idx, 37.70, -122.50, 37.81, -122.38);- println!("rail lines in SF bbox: {}", lines.len());- assert!(!lines.is_empty());-- for (name, from, to) in [- ("SF Mission -> Downtown", (37.7599, -122.4148), (37.7880, -122.4075)),- ("NYC Brooklyn -> Midtown", (40.6782, -73.9442), (40.7580, -73.9855)),- ("London Camden -> Westminster", (51.5390, -0.1426), (51.4995, -0.1248)),- ("Tokyo Shinjuku -> Tokyo Stn", (35.6896, 139.7006), (35.6812, 139.7671)),- ] {- let legs = plan(&idx, from.0, from.1, to.0, to.1, nine, sched);- match &legs {- Some(legs) => println!(- "plan {name}: {}",- legs.iter()- .map(|l| {- let kind = match l.kind {- LegKind::Walk => "walk",- LegKind::Wait => "wait",- LegKind::Ride => "ride",- };- format!("{kind}:{}({}->{})", l.name, l.from_stop, l.to_stop)- })- .collect::<Vec<_>>()- .join(" | ")- ),- None => println!("plan {name}: no journey"),++ if planet {+ assert!(idx.covers(37.7749, -122.4194), "transit pack does not cover SF");++ // A weekday mid-morning (Wednesday 2026-11-11), the day this test was written.+ let sched = Schedule { day: QueryDay::for_date(2, 20261111), overlay: None };+ let nine = 9 * 3600;++ let board = stop_departures(&idx, 37.7764, -122.3943, nine, sched, 10); // SF Caltrain 4th & King+ println!("departures at 4th & King: {:?}",+ board.iter().map(|d| format!("{} -> {} @{}", d.route_name, d.headsign, d.dep_secs)).collect::<Vec<_>>());+ assert!(!board.is_empty(), "no offline departures at SF 4th & King");+ assert!(board.windows(2).all(|w| w[0].dep_secs <= w[1].dep_secs));++ let tz = idx.timezone_at(37.7749, -122.4194);+ let motis = idx.nearest_stop_motis_id(37.7764, -122.3943);+ println!("timezone {tz}, MOTIS stop id {motis:?}");+ assert_eq!(tz, "America/Los_Angeles");++ let lines = rail_lines(&idx, 37.70, -122.50, 37.81, -122.38);+ println!("rail lines in SF bbox: {}", lines.len());+ assert!(!lines.is_empty());++ for (name, from, to) in [+ ("SF Mission -> Downtown", (37.7599, -122.4148), (37.7880, -122.4075)),+ ("NYC Brooklyn -> Midtown", (40.6782, -73.9442), (40.7580, -73.9855)),+ ("London Camden -> Westminster", (51.5390, -0.1426), (51.4995, -0.1248)),+ ("Tokyo Shinjuku -> Tokyo Stn", (35.6896, 139.7006), (35.6812, 139.7671)),+ ] {+ let legs = plan(&idx, from.0, from.1, to.0, to.1, nine, sched);+ match &legs {+ Some(legs) => println!(+ "plan {name}: {}",+ legs.iter()+ .map(|l| {+ let kind = match l.kind {+ LegKind::Walk => "walk",+ LegKind::Wait => "wait",+ LegKind::Ride => "ride",+ };+ format!("{kind}:{}({}->{})", l.name, l.from_stop, l.to_stop)+ })+ .collect::<Vec<_>>()+ .join(" | ")+ ),+ None => println!("plan {name}: no journey"),+ }+ let legs = legs.unwrap_or_else(|| panic!("{name}: no transit journey"));+ assert!(legs.iter().any(|l| l.kind == LegKind::Ride), "{name}: journey has no ride"); }- let legs = legs.unwrap_or_else(|| panic!("{name}: no transit journey"));- assert!(legs.iter().any(|l| l.kind == LegKind::Ride), "{name}: journey has no ride");+ } else {+ // The synthetic pack: Alpha (37.700) -> Beta -> Gamma on route N,+ // 08:00 and 09:00 trips, Wednesday 2024-01-03.+ assert_eq!(idx.feed_name(), "testpack");+ assert!(idx.covers(37.710, -122.400), "transit pack does not cover Beta");+ let sched = Schedule { day: QueryDay::for_date(2, 20240103), overlay: None };++ let board = stop_departures(&idx, 37.700, -122.400, 28_000, sched, 10); // Alpha+ println!("departures at Alpha: {:?}",+ board.iter().map(|d| format!("{} -> {} @{}", d.route_name, d.headsign, d.dep_secs)).collect::<Vec<_>>());+ assert!(!board.is_empty(), "no offline departures at Alpha");+ assert!(board.windows(2).all(|w| w[0].dep_secs <= w[1].dep_secs));+ assert_eq!(board[0].dep_secs, 28_800, "first departure is the 08:00 trip");++ let tz = idx.timezone_at(37.700, -122.400);+ let motis = idx.nearest_stop_motis_id(37.700, -122.400);+ println!("timezone {tz}, MOTIS stop id {motis:?}");+ assert_eq!(tz, "America/Los_Angeles");+ assert!(motis.as_deref().is_some_and(|m| m.contains("901201")), "Alpha's MOTIS id: {motis:?}");++ let lines = rail_lines(&idx, 37.69, -122.41, 37.73, -122.39);+ println!("rail lines in synthetic bbox: {}", lines.len());+ assert!(!lines.is_empty());++ let legs = plan(&idx, 37.700, -122.400, 37.720, -122.400, 25_000, sched)+ .expect("a journey exists");+ println!(+ "plan Alpha -> Gamma: {}",+ legs.iter()+ .map(|l| {+ let kind = match l.kind {+ LegKind::Walk => "walk",+ LegKind::Wait => "wait",+ LegKind::Ride => "ride",+ };+ format!("{kind}:{}({}->{})", l.name, l.from_stop, l.to_stop)+ })+ .collect::<Vec<_>>()+ .join(" | ")+ );+ let ride = legs.iter().find(|l| l.kind == LegKind::Ride).expect("journey has no ride");+ assert_eq!(ride.name, "N");+ assert_eq!(ride.from_stop, "Alpha");+ assert_eq!(ride.to_stop, "Gamma");+ assert_eq!((ride.dep_secs, ride.arr_secs), (28_800, 29_400));+ std::fs::remove_file(&path).ok(); } }
maps/src/main/rust/tests/real_archive/graph_fixture.rs
diff --git a/maps/src/main/rust/tests/real_archive/graph_fixture.rs b/maps/src/main/rust/tests/real_archive/graph_fixture.rsnew file mode 100644index 0000000000..803ebf94d0--- /dev/null+++ b/maps/src/main/rust/tests/real_archive/graph_fixture.rs@@ -0,0 +1,293 @@+//! A tiny routable graph (plus highway overlay) packed as a+//! single-archive `.mamaps` sidecar, for the synthetic real-archive+//! tests. Mirrors the container assembly in `src/graph_part5.rs` and+//! `src/transit_part9.rs` (which integration tests cannot link).+//!+//! Layout: a 3x3 node grid over San Francisco (rows south to north,+//! columns west to east), bidirectional edges between orthogonal+//! neighbours, every edge named, one edge carrying lane masks, an+//! elevation profile, and an identity highway overlay.++use std::path::PathBuf;++use tilecodec::mamaps::archive::{+ self as sidecar, ArchiveEntry, ArchiveFooter, GRAPH_MAGIC, GRAPH_VERSION_MIN,+};+use tilecodec::mamaps::header::Header;++/// Build id stamped on every synthetic archive (and its sidecar footer).+pub const BUILD_ID: u64 = 0x5eed_5eed_5eed_5eed;+/// Grid latitudes, south to north.+pub const LATS: [f64; 3] = [37.7694, 37.7825, 37.7955];+/// Grid longitudes, west to east.+pub const LONS: [f64; 3] = [-122.4862, -122.4399, -122.3937];+/// Road name every synthetic edge carries.+pub const ROAD_NAME: &str = "Grid Street";++/// `(lat, lon)` of a grid node.+pub fn node_lat_lon(id: usize) -> (f64, f64) {+ (LATS[id / 3], LONS[id % 3])+}++fn e7(deg: f64) -> i32 {+ (deg * 1e7).round() as i32+}++fn dist_mm(a: (f64, f64), b: (f64, f64)) -> u32 {+ let (la1, lo1) = (a.0.to_radians(), a.1.to_radians());+ let (la2, lo2) = (b.0.to_radians(), b.1.to_radians());+ let h = ((la2 - la1) / 2.0).sin().powi(2)+ + la1.cos() * la2.cos() * ((lo2 - lo1) / 2.0).sin().powi(2);+ (2.0 * 6_371_000_000.0 * h.sqrt().asin()).round() as u32+}++/// `(source, target, dist_mm)` for every directed edge, grouped by+/// source in ascending target order (the `edge_ptr` layout).+fn edges() -> Vec<(u32, u32, u32)> {+ let mut out = Vec::new();+ for id in 0..9usize {+ let (row, col) = (id / 3, id % 3);+ let mut targets = Vec::new();+ if col > 0 {+ targets.push(id - 1);+ }+ if col < 2 {+ targets.push(id + 1);+ }+ if row > 0 {+ targets.push(id - 3);+ }+ if row < 2 {+ targets.push(id + 3);+ }+ targets.sort_unstable();+ for target in targets {+ out.push((+ id as u32,+ target as u32,+ dist_mm(node_lat_lon(id), node_lat_lon(target)),+ ));+ }+ }+ out+}++fn meta(node_count: u64, edge_count: u64, named: u64) -> Vec<u8> {+ let mut out = Vec::new();+ out.extend_from_slice(&GRAPH_MAGIC.to_le_bytes());+ out.extend_from_slice(&GRAPH_VERSION_MIN.to_le_bytes());+ out.extend_from_slice(&node_count.to_le_bytes());+ out.extend_from_slice(&edge_count.to_le_bytes());+ out.extend_from_slice(&0u64.to_le_bytes());+ out.extend_from_slice(&named.to_le_bytes());+ out+}++fn nodes_payload(edges: &[(u32, u32, u32)]) -> Vec<u8> {+ let mut ptr = 0u32;+ let mut out = Vec::new();+ for id in 0..9usize {+ let (lat, lon) = node_lat_lon(id);+ out.extend_from_slice(&e7(lat).to_le_bytes());+ out.extend_from_slice(&e7(lon).to_le_bytes());+ out.extend_from_slice(&ptr.to_le_bytes());+ ptr += edges.iter().filter(|&&(s, _, _)| s as usize == id).count() as u32;+ }+ // Sentinel: edge_ptr == edge_count.+ out.extend_from_slice(&0i32.to_le_bytes());+ out.extend_from_slice(&0i32.to_le_bytes());+ out.extend_from_slice(&ptr.to_le_bytes());+ out+}++fn edges_payload(edges: &[(u32, u32, u32)]) -> Vec<u8> {+ let e = edges.len() as u64;+ let mut out = Vec::new();+ for &(source, target, dist) in edges {+ out.extend_from_slice(&(target as i32 - source as i32).to_le_bytes()[..2]);+ out.extend_from_slice(&dist.to_le_bytes()[..3]);+ out.push(5); // road type: drivable, walkable, bikeable+ out.push(50); // speed limit km/h+ }+ while out.len() as u64 % 8 != 0 {+ out.push(0);+ }+ // Escape index (E/1024 + 1 entries; total == 0 escapes), no rows.+ out.extend_from_slice(&0u32.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ while out.len() as u64 % 8 != 0 {+ out.push(0);+ }+ // Name bitmap: rank [0, E] then one present bit per edge (all named).+ out.extend_from_slice(&0u64.to_le_bytes());+ out.extend_from_slice(&e.to_le_bytes());+ out.extend(std::iter::repeat_n(0xFF, e.div_ceil(8) as usize));+ // One pool offset per named edge, in rank order (all the same name).+ for _ in 0..e {+ out.extend_from_slice(&1u32.to_le_bytes());+ }+ out+}++fn intermediate_payload(edge_count: u64) -> Vec<u8> {+ // G = 0: empty blob, then the zero trailer the counts describe.+ let bitmap = (edge_count.div_ceil(512) + 1) * 8 + edge_count.div_ceil(8);+ vec![0u8; (bitmap + 8 + 2 + 8) as usize]+}++fn lanes_payload() -> Vec<u8> {+ // One entry (edge 0, two masks) plus the sentinel.+ let mut out = Vec::new();+ out.extend_from_slice(&1u32.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ out.extend_from_slice(&0u32.to_le_bytes());+ out.extend_from_slice(&4u32.to_le_bytes());+ out.extend_from_slice(&0x0002u16.to_le_bytes());+ out.extend_from_slice(&0x0004u16.to_le_bytes());+ out+}++fn elevation_payload() -> Vec<u8> {+ let mut out = Vec::new();+ for id in 0..9 {+ out.extend_from_slice(&(10 + id as i16).to_le_bytes());+ }+ out+}++fn overlay_payload(edges: &[(u32, u32, u32)]) -> Vec<u8> {+ let n = 9u64;+ let e = edges.len() as u64;+ let mut node_recs = Vec::new();+ let mut ptr = 0u32;+ for id in 0..9usize {+ let (lat, lon) = node_lat_lon(id);+ node_recs.extend_from_slice(&e7(lat).to_le_bytes());+ node_recs.extend_from_slice(&e7(lon).to_le_bytes());+ node_recs.extend_from_slice(&ptr.to_le_bytes());+ node_recs.extend_from_slice(&(id as u32).to_le_bytes());+ ptr += edges.iter().filter(|&&(s, _, _)| s as usize == id).count() as u32;+ }+ node_recs.extend_from_slice(&0i32.to_le_bytes());+ node_recs.extend_from_slice(&0i32.to_le_bytes());+ node_recs.extend_from_slice(&ptr.to_le_bytes());+ node_recs.extend_from_slice(&0u32.to_le_bytes());+ let nodes = tilecodec::blocked::write_blocked(&node_recs, 16);+ let mut edge_recs = Vec::new();+ for (idx, &(_, target, dist)) in edges.iter().enumerate() {+ edge_recs.extend_from_slice(&target.to_le_bytes());+ edge_recs.extend_from_slice(&dist.to_le_bytes());+ edge_recs.extend_from_slice(&(idx as u64).to_le_bytes());+ edge_recs.push(5);+ edge_recs.push(50);+ edge_recs.extend_from_slice(&0u16.to_le_bytes());+ }+ let overlay_edges = tilecodec::blocked::write_blocked(&edge_recs, 20);+ let mut out = Vec::new();+ out.extend_from_slice(&0x4C56_4F4Du32.to_le_bytes()); // "MOVL"+ out.extend_from_slice(&1u32.to_le_bytes());+ out.extend_from_slice(&n.to_le_bytes());+ out.extend_from_slice(&e.to_le_bytes());+ out.extend_from_slice(&n.to_le_bytes());+ out.extend_from_slice(&e.to_le_bytes());+ out.extend_from_slice(&(nodes.len() as u64).to_le_bytes());+ out.extend_from_slice(&(overlay_edges.len() as u64).to_le_bytes());+ out.extend_from_slice(&nodes);+ while out.len() as u64 % 8 != 0 {+ out.push(0);+ }+ out.extend_from_slice(&overlay_edges);+ while out.len() as u64 % 8 != 0 {+ out.push(0);+ }+ // Portals bitmap over the full nodes: every node is a portal.+ out.extend_from_slice(&0u64.to_le_bytes());+ out.extend_from_slice(&n.to_le_bytes());+ out.extend_from_slice(&[0xFF, 0x01]);+ out+}++fn test_header(file_len: u64) -> Header {+ Header {+ flags: 0,+ compression: 0,+ layer_count: 12,+ min_zoom: 0,+ max_zoom: 14,+ build_id: BUILD_ID,+ file_len,+ dict_offset: 128,+ dict_len: 64,+ leaf_entry_capacity: 4096,+ root_offset: 192,+ root_len: 32,+ leaf_count: 1,+ leaf_offset: 224,+ leaf_len: 16,+ data_offset: 240,+ data_len: 3856,+ tiles_addressed: 1,+ bodies_written: 1,+ min_lon_e7: 0,+ min_lat_e7: 0,+ max_lon_e7: 0,+ max_lat_e7: 0,+ }+}++/// Whole file: tile prefix (zeroes under a real serialized header) ++/// payloads laid out 8-aligned in kind order + directory + footer.+fn assemble(payloads: &[(u8, Vec<u8>, u64)]) -> Vec<u8> {+ let mut header = test_header(0);+ let mut out = vec![0u8; 4096];+ let mut entries = Vec::new();+ for (kind, bytes, extra) in payloads {+ while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 {+ out.push(0);+ }+ let offset = out.len() as u64;+ out.extend_from_slice(bytes);+ entries.push(ArchiveEntry { kind: *kind, flags: 0, offset, len: bytes.len() as u64, extra: *extra });+ }+ while out.len() as u64 % sidecar::ARCHIVE_ALIGN != 0 {+ out.push(0);+ }+ let dir_offset = out.len() as u64;+ let (dir, _) = sidecar::serialize_dir(&entries, BUILD_ID, dir_offset);+ out.extend_from_slice(&dir);+ let footer = ArchiveFooter { dir_offset, dir_len: dir.len() as u64, build_id: BUILD_ID };+ out.extend_from_slice(&footer.serialize());+ header.file_len = out.len() as u64;+ let head = header.serialize();+ out[..head.len()].copy_from_slice(&head);+ out+}++/// The synthetic graph archive (graph sections + overlay, no tiles).+pub fn graph_archive() -> Vec<u8> {+ let edges = edges();+ let e = edges.len() as u64;+ assemble(&[+ (sidecar::ARCHIVE_KIND_GRAPH_META, meta(9, e, e), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_NODES, nodes_payload(&edges), 9),+ (sidecar::ARCHIVE_KIND_GRAPH_EDGES, edges_payload(&edges), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_INTERMEDIATE, intermediate_payload(e), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_NAMES, format!("\0{ROAD_NAME}\0").into_bytes(), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_LANES, lanes_payload(), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_ELEVATION, elevation_payload(), 0),+ (sidecar::ARCHIVE_KIND_GRAPH_OVERLAY, overlay_payload(&edges), 0),+ ])+}++/// The synthetic transit archive (one TRIX section, no tiles).+pub fn transit_archive(pack: &[u8]) -> Vec<u8> {+ assemble(&[(sidecar::ARCHIVE_KIND_TRANSIT, pack.to_vec(), 0)])+}++/// Write `bytes` to a temp `.mamaps` file unique to this process.+pub fn write_temp(tag: &str, bytes: &[u8]) -> PathBuf {+ let path = std::env::temp_dir().join(format!("synthetic-{tag}-{}.mamaps", std::process::id()));+ std::fs::write(&path, bytes).expect("write synthetic archive");+ path+}
maps/src/main/rust/tests/real_archive/pack.rs
diff --git a/maps/src/main/rust/tests/real_archive/pack.rs b/maps/src/main/rust/tests/real_archive/pack.rsnew file mode 100644index 0000000000..178f0077ab--- /dev/null+++ b/maps/src/main/rust/tests/real_archive/pack.rs@@ -0,0 +1,483 @@+//! A minimal TRIX pack writer for the synthetic-archive tests.+//!+//! Mirrors the test writer in `src/transit_part6.rs` (which cannot be+//! linked from an integration test): if the two drift, these tests+//! fail, which is the point. Builds the same three-stop pack the unit+//! tests plan over, at raw v7 (planet4's layout).+++use std::collections::HashMap;++const NONE: u32 = 0xFFFF_FFFF;+const HEADER_LEN: usize = 80;+const MAGIC: u32 = tilecodec::mamaps::archive::TRANSIT_MAGIC;+const GRID_CELL_E7: u32 = 200_000;+const MAX_TRANSFER_M: f64 = 400.0;+const WALK_SPEED_M_S: f64 = 4.5 / 3.6;++fn dist_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {+ let dlat = (lat2 - lat1) * 111_320.0;+ let mean = ((lat1 + lat2) * 0.5).to_radians();+ let dlon = (lon2 - lon1) * 111_320.0 * mean.cos();+ (dlat * dlat + dlon * dlon).sqrt()+}++struct Stop {+ lat: f64,+ lon: f64,+ name: &'static str,+ code: &'static str,+ gtfs_id: &'static str,+}++struct Trip {+ start: u32,+ stoptimes: Vec<(u32, u32)>,+ service: u32,+ headsign: &'static str,+}++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>,+ shape: Option<Shape>,+}++struct Service {+ mask: u8,+ start: u32,+ end: u32,+}++struct Pack {+ stops: Vec<Stop>,+ routes: Vec<Route>,+ services: Vec<Service>,+ exceptions: Vec<(u32, u32, u32)>,+ feeds: Vec<(&'static str, &'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 {+ 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 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();+ 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);+ let g = pool.intern(s.gtfs_id);+ u32b(&mut sec_stop_gtfs_id, g);+ }++ 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();+ 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);+ 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);+ 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);+ 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;+ }+ 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);++ 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);+ }++ 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);++ 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();+ let mut sec_feed_motis_prefix = Vec::new();+ for &(name, tz, motis) in &self.feeds {+ let n = pool.intern(name);+ let t = pool.intern(tz);+ let m = pool.intern(motis);+ u32b(&mut sec_feeds, n);+ u32b(&mut sec_feed_tz, t);+ u32b(&mut sec_feed_motis_prefix, m);+ }++ 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,+ ];+ 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);+ }+ if version >= 5 {+ sections.push(&sec_feed_motis_prefix);+ sections.push(&sec_stop_gtfs_id);+ }+ 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;+ 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+ }+}++pub fn synthetic_pack() -> Vec<u8> {+ one_route_pack().build_with_version(7)+}++fn weekdays() -> Service {+ Service { mask: 0b0011_1111 & 0b0001_1111, start: 20_240_101, end: 20_241_231 }+}++fn one_route_pack() -> Pack {+ Pack {+ stops: vec![+ Stop { lat: 37.700, lon: -122.400, name: "Alpha", code: "A1", gtfs_id: "901201" },+ Stop { lat: 37.710, lon: -122.400, name: "Beta", code: "B2", gtfs_id: "901202" },+ Stop { lat: 37.720, lon: -122.400, name: "Gamma", code: "C3", gtfs_id: "901203" },+ ],+ 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", "us-ca-SFMTA")],+ }+}