maps: TRIX v8 compresses only cold sections, flagged per section (#planet5)
- Commit
90d72f35cf1a1426749cf57cef7e21950e3d1aed- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-14 01:55 UTC (22 days ago)
- Parents
7a2bfd9
The first planet5 transit layout (every section ZSEC, 1.19 GB) made a world-pack journey plan ~35x slower than raw v7 (28.2 s vs 0.79 s for 13 queries): RAPTOR reads stops, routes, patterns, trips, profiles and transfers at random across the planet's tables, and each miss in the 16 MiB per-thread block cache inflates a 64 KiB block. That is not shippable on a phone. v8 now marks a ZSEC section with bit 63 of its directory length (tilecodec TRANSIT_ZSEC_FLAG) instead of "every non-empty section", so the writer chooses per section. transit_planet5 compresses by default the sections a plan only reads to describe its result -- names, feed metadata, polylines and their indexes, MOTIS ids -- plus the calendar exceptions; --zsec cold|all|none|i,j,.. overrides. Measured plan time against raw v7 on the planet pack (12 queries): cold only 2.94 GB 1.04x cold + exceptions 2.45 GB 1.30x <- default + stop routes 2.3x + transfers 2.6x + profiles 5.2x everything 1.19 GB ~35x Reader: per-section block size taken from the ZSEC header (tests use 64-byte blocks), and a per-section last-block fast path so interleaved sequential walks do not thrash a single shared slot. transit_parity now counts "same departure and arrival via another itinerary" apart from real differences: the planner itself is not deterministic between runs on equal-cost journeys (v7 against the same v7 pack: 27 identical, 4 such alternatives, 1 different of 32 routed), so only arrival changes are a parity failure. Verified: cargo test -p offlinerouter (93 pass; every transit test runs through flagged 64-byte-block ZSEC sections); tilecodec 195 pass; transit_parity on the planet pack (report).
Diff
library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rsindex b52ae2321e..5035d1c00e 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/consts.rs@@ -68,10 +68,15 @@ pub const GRAPH_META_LEN: u64 = 40; pub const TRANSIT_MAGIC: u32 = 0x5452_4958; /// Newest transit version accepted. v7 adds a host-only section the app never reads. pub const TRANSIT_VERSION: u32 = 8;-/// Planet5: every section of a v8 pack is a [`crate::zsec`] block-compressed section, its-/// directory length the stored length (the raw length is in the ZSEC header). v8 also drops the-/// unread ROUTE_TRIPS varint stream and thins SHAPE_COORDS.+/// Planet5: a v8 pack may store any section as a [`crate::zsec`] block-compressed section,+/// marked by [`TRANSIT_ZSEC_FLAG`] in its directory length (the raw length is in the ZSEC+/// header). The writer compresses the sections the planner does not touch per relaxation+/// (names, polylines, ids); the RAPTOR tables stay raw. v8 also drops the unread ROUTE_TRIPS+/// varint stream and thins SHAPE_COORDS. pub const TRANSIT_VERSION_ZSEC: u32 = 8;+/// Bit 63 of a v8 directory length: the section is ZSEC. A v7 reader never sees it (it refuses+/// v8); real lengths never come near 2^63.+pub const TRANSIT_ZSEC_FLAG: u64 = 1 << 63; /// Oldest transit version accepted. pub const TRANSIT_VERSION_MIN: u32 = 3; /// POI index record stride.
library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs
diff --git a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rsindex 36f00a943c..02e3f39628 100644--- a/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs+++ b/library/tilecodec/src/main/rust/src/mamaps/archive/mod.rs@@ -105,7 +105,7 @@ pub use consts::{ ARCHIVE_KIND_POI_ADMIN, ARCHIVE_KIND_POI_INDEX, ARCHIVE_KIND_POI_NAMES, ARCHIVE_KIND_POI_REGION, ARCHIVE_KIND_POI_SPATIAL, ARCHIVE_KIND_POI_WORDS, ARCHIVE_KIND_TRANSIT, GRAPH_MAGIC, GRAPH_META_LEN, GRAPH_VERSION, GRAPH_VERSION_BLOCKED, GRAPH_VERSION_MIN, GRAPH_VERSION_VARINT,- POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, TRANSIT_VERSION_ZSEC,+ POI_RECORD_BYTES, TRANSIT_MAGIC, TRANSIT_VERSION, TRANSIT_VERSION_MIN, TRANSIT_VERSION_ZSEC, TRANSIT_ZSEC_FLAG, }; pub use entry::{is_known_kind, ArchiveEntry}; pub use footer::ArchiveFooter;
maps/src/main/rust/examples/transit_parity.rs
diff --git a/maps/src/main/rust/examples/transit_parity.rs b/maps/src/main/rust/examples/transit_parity.rsindex 60c3dbdda9..ee159f4e08 100644--- a/maps/src/main/rust/examples/transit_parity.rs+++ b/maps/src/main/rust/examples/transit_parity.rs@@ -49,6 +49,9 @@ fn main() -> std::process::ExitCode { (seed >> 11) as f64 / (1u64 << 53) as f64 }; let (mut same, mut diff, mut none_both, mut routed) = (0usize, 0usize, 0usize, 0usize);+ // Same final arrival through a different itinerary: an equally optimal journey (tie-breaks+ // read ride distances, which shape thinning moves by centimetres). Counted apart, not failed.+ let mut alt = 0usize; let (mut boards_same, mut boards) = (0usize, 0usize); let (mut t7, mut t8) = (0.0f64, 0.0f64); let mut max_dist_diff = 0.0f64;@@ -95,10 +98,23 @@ fn main() -> std::process::ExitCode { coords7 += g7.coords.len() / 2; coords8 += g8.coords.len() / 2; }+ } else if x.last().map(|g| g.arr_secs) == y.last().map(|g| g.arr_secs)+ && x.first().map(|g| g.dep_secs) == y.first().map(|g| g.dep_secs)+ {+ alt += 1; } else { diff += 1; if diff <= 5 { println!("query {q}: plans differ");+ for (tag, l) in [("v7", x), ("v8", y)] {+ for g in l.iter() {+ println!(+ " {tag} ride={} {:?} {:?}->{:?} hs={:?} {}..{} n={} d={:.0}",+ g.kind == LegKind::Ride, g.name, g.from_stop, g.to_stop, g.headsign,+ g.dep_secs, g.arr_secs, g.stop_count, g.dist_m+ );+ }+ } } } }@@ -107,6 +123,13 @@ fn main() -> std::process::ExitCode { println!("query {q}: routable in one pack only"); } }+ eprintln!(+ "q{q}: v7 {} legs, v8 {} legs, {:.0} / {:.0} ms so far",+ p7.as_ref().map_or(0, |l| l.len()),+ p8.as_ref().map_or(0, |l| l.len()),+ t7 * 1e3,+ t8 * 1e3+ ); let b7 = stop_departures(&v7, fla, flo, dep, sched, 20); let b8 = stop_departures(&v8, fla, flo, dep, sched, 20); let bk = |b: &Vec<offlinerouter::transit::StopDeparture>| {@@ -118,7 +141,8 @@ fn main() -> std::process::ExitCode { } } println!(- "plans: {routed} routed, {none_both} unroutable in both; identical legs {same}, different {diff}\n\+ "plans: {routed} routed, {none_both} unroutable in both; identical legs {same}, same arrival via another \+ itinerary {alt}, different {diff}\n\ departure boards identical {boards_same}/{boards}\n\ ride polylines: {coords7} -> {coords8} points; max leg distance change {max_dist_diff:.2} m\n\ plan time: v7 {:.1} ms/query, v8 {:.1} ms/query",
maps/src/main/rust/src/transit_part1.rs
diff --git a/maps/src/main/rust/src/transit_part1.rs b/maps/src/main/rust/src/transit_part1.rsindex 22a95c967d..0037e720fc 100644--- a/maps/src/main/rust/src/transit_part1.rs+++ b/maps/src/main/rust/src/transit_part1.rs@@ -64,14 +64,19 @@ impl TransitIndex { let mut zsec = [None; SECTION_COUNT]; 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) };+ let len_word: u64 = unsafe { read_at::<u64>(dir_base, i * 2 + 1) };+ // v8: bit 63 of a directory length marks a ZSEC block section (see+ // TRANSIT_ZSEC_FLAG); the rest is the stored length either way.+ let zflag = version >= tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC+ && len_word & tilecodec::mamaps::archive::TRANSIT_ZSEC_FLAG != 0;+ let len = len_word & !tilecodec::mamaps::archive::TRANSIT_ZSEC_FLAG; if off as usize + len as usize > backing.len() { return None; } *s = (off as usize, len as usize);- // v8: every non-empty section is a ZSEC block section. Validate its table now and- // expose its *raw* length, which is what every bound check below compares against.- if version >= tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC && len > 0 {+ // Validate a ZSEC section's table now and expose its *raw* length, which is what+ // every bound check below compares against.+ if zflag && len > 0 { let bytes = unsafe { std::slice::from_raw_parts(base.add(off as usize), len as usize) }; let z = tilecodec::zsec::ZSec::parse(bytes).ok()?; if z.block_size() == 0 || z.block_size() > (1 << 20) {
maps/src/main/rust/src/transit_part6.rs
diff --git a/maps/src/main/rust/src/transit_part6.rs b/maps/src/main/rust/src/transit_part6.rsindex b23d5a5745..0c5124ac6f 100644--- a/maps/src/main/rust/src/transit_part6.rs+++ b/maps/src/main/rust/src/transit_part6.rs@@ -484,7 +484,8 @@ out.extend_from_slice(&z); let d = dir_at + i * 16; out[d..d + 8].copy_from_slice(&o.to_le_bytes());- out[d + 8..d + 16].copy_from_slice(&(z.len() as u64).to_le_bytes());+ let flag = if z.is_empty() { 0 } else { tilecodec::mamaps::archive::TRANSIT_ZSEC_FLAG };+ out[d + 8..d + 16].copy_from_slice(&(z.len() as u64 | flag).to_le_bytes()); } out }
maps/src/main/rust/src/transit_zsec.rs
diff --git a/maps/src/main/rust/src/transit_zsec.rs b/maps/src/main/rust/src/transit_zsec.rsindex 90eeb883da..04587784a1 100644--- a/maps/src/main/rust/src/transit_zsec.rs+++ b/maps/src/main/rust/src/transit_zsec.rs@@ -1,10 +1,12 @@ // Planet5 (TRIX v8) block-compressed sections: typed reads through a per-thread block cache. //-// Every non-empty v8 section is a `tilecodec::zsec` section. A read of `size_of::<T>()` bytes at-// a byte position decodes the one (or, straddling a boundary, two) 64 KiB blocks it touches and-// keeps them in a small per-thread cache, so the RAPTOR loops — which walk a route's trips, a-// stop's transfers and a profile's varints in order — decode each block once and then hit the-// cache. v3..v7 sections take the old raw mmap path untouched.+// A v8 section flagged ZSEC in its directory length is a `tilecodec::zsec` section. A read of+// `size_of::<T>()` bytes at a byte position decodes the one (or, straddling a boundary, two)+// 64 KiB blocks it touches and keeps them in a small per-thread cache, with a per-section+// last-block fast path for sequential walks (varint streams, polylines). The writer flags only+// the sections a plan reads to describe its result; the RAPTOR tables stay raw, because their+// random access across a world pack ran ~35x slower through the cache. Raw sections, and every+// v3..v7 section, take the old mmap path untouched. static NEXT_TRANSIT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1); @@ -14,14 +16,16 @@ const TRANSIT_BLOCK_CACHE: usize = 256; struct TransitBlockCache { map: std::collections::HashMap<(u64, u8, u32), std::rc::Rc<Vec<u8>>>, order: std::collections::VecDeque<(u64, u8, u32)>,- last: Option<((u64, u8, u32), std::rc::Rc<Vec<u8>>)>,+ /// The last block each section touched: sequential walks (a varint stream, a polyline)+ /// stay in one block for thousands of reads, interleaved across sections.+ last: Vec<Option<((u64, u8, u32), std::rc::Rc<Vec<u8>>)>>, } thread_local! { static TRANSIT_BLOCKS: std::cell::RefCell<TransitBlockCache> = std::cell::RefCell::new(TransitBlockCache { map: std::collections::HashMap::new(), order: std::collections::VecDeque::new(),- last: None,+ last: vec![None; 32], }); } @@ -31,13 +35,13 @@ impl TransitIndex { let key = (self.uid, section as u8, b); TRANSIT_BLOCKS.with(|cell| { let mut c = cell.borrow_mut();- if let Some((k, v)) = &c.last {+ if let Some(Some((k, v))) = c.last.get(section) { if *k == key { return v.clone(); } } if let Some(v) = c.map.get(&key).cloned() {- c.last = Some((key, v.clone()));+ c.last[section % 32] = Some((key, v.clone())); return v; } let (off, len, _) = self.zsec[section].expect("a ZSEC section");@@ -54,7 +58,7 @@ impl TransitIndex { } c.order.push_back(key); c.map.insert(key, v.clone());- c.last = Some((key, v.clone()));+ c.last[section % 32] = Some((key, v.clone())); v }) }
scripts/maps/tile_build/src/bin/transit_planet5.rs
diff --git a/scripts/maps/tile_build/src/bin/transit_planet5.rs b/scripts/maps/tile_build/src/bin/transit_planet5.rsindex 27ef4c66ba..397fa02ac2 100644--- a/scripts/maps/tile_build/src/bin/transit_planet5.rs+++ b/scripts/maps/tile_build/src/bin/transit_planet5.rs@@ -13,7 +13,10 @@ //! vertices (every stop's vertex of every route sharing the blob, and both ends), remapping //! ROUTE_STOP_SHAPE to the kept vertices and rebuilding ROUTE_SHAPE_IDX; a ride leg still //! slices `shape[vertex(board)..=vertex(alight)]` exactly at its stops;-//! * stores every non-empty section as a 64 KiB zstd-19 ZSEC section and stamps version 8.+//! * stores the sections the planner only reads to describe a result (names, feed metadata,+//! polylines, MOTIS ids) and the calendar exceptions as 64 KiB zstd-19 ZSEC sections+//! (`--zsec` overrides; see COLD_SECTIONS for the measured trade-off), flagged by bit 63 of+//! their directory length, and stamps version 8. //! //! The device reader (maps `transit.rs`) reads v3..=v8; a v7-only reader refuses v8 cleanly. use std::fs::File;@@ -30,6 +33,14 @@ const SEC_ROUTE_STOP_SHAPE: usize = 22; const SEC_ROUTE_TRIP_RECS: usize = 25; const SEC_ROUTE_TRIP_OFF: usize = 26; const ROUTE_REC: usize = 32;+/// Sections stored as ZSEC by default: the ones the planner reads only to describe a finished+/// journey or a stop (names 0, feed metadata 16/17/23, polylines and their indexes 20-22, MOTIS+/// ids 24), plus the calendar exceptions (12; 0.53 GB raw, ~11x smaller). The other RAPTOR+/// tables stay raw: measured on the planet pack (12 world queries, block cache 16 MiB/thread),+/// every compressed set cost this much plan time against raw v7:+/// cold only 1.04x (2.94 GB) | cold + exceptions 1.30x (2.45 GB) | + stop routes 2.3x |+/// + transfers 2.6x | + profiles 5.2x | everything ~35x (1.19 GB).+const COLD_SECTIONS: [usize; 9] = [0, 12, 16, 17, 20, 21, 22, 23, 24]; const NONE: u32 = u32::MAX; fn u32_at(b: &[u8], o: usize) -> u32 {@@ -71,6 +82,7 @@ fn seg_dist_sq(p: (f64, f64), a: (f64, f64), b: (f64, f64)) -> f64 { fn main() -> ExitCode { let args: Vec<String> = std::env::args().collect(); let mut tol = 1.0f64;+ let mut zsec: Vec<usize> = COLD_SECTIONS.to_vec(); let mut pos = Vec::new(); let mut i = 1; while i < args.len() {@@ -79,14 +91,24 @@ fn main() -> ExitCode { i += 2; continue; }+ if args[i] == "--zsec" {+ zsec = match args[i + 1].as_str() {+ "all" => (0..DEVICE_SECTIONS).collect(),+ "cold" => COLD_SECTIONS.to_vec(),+ "none" => Vec::new(),+ list => list.split(',').map(|v| v.parse().expect("--zsec section list")).collect(),+ };+ i += 2;+ continue;+ } pos.push(args[i].clone()); i += 1; } if pos.len() != 2 {- eprintln!("usage: transit_planet5 IN.transit OUT.transit [--shape-tol-m M]");+ eprintln!("usage: transit_planet5 IN.transit OUT.transit [--shape-tol-m M] [--zsec cold|all|none|i,j,..]"); return ExitCode::from(2); }- match run(&pos[0], &pos[1], tol) {+ match run(&pos[0], &pos[1], tol, &zsec) { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("transit_planet5: {e}");@@ -95,7 +117,7 @@ fn main() -> ExitCode { } } -fn run(input: &str, output: &str, tol: f64) -> Result<(), String> {+fn run(input: &str, output: &str, tol: f64, zsec: &[usize]) -> Result<(), String> { let f = File::open(input).map_err(|e| format!("open {input}: {e}"))?; let m = unsafe { memmap2::Mmap::map(&f) }.map_err(|e| e.to_string())?; if m.len() < HEADER_LEN || u32_at(&m, 0) != tilecodec::mamaps::archive::TRANSIT_MAGIC {@@ -261,26 +283,34 @@ fn run(input: &str, output: &str, tol: f64) -> Result<(), String> { sections[SEC_ROUTE_STOP_SHAPE] = new_rss; } - // ZSEC every non-empty section; v8 header and directory.+ // ZSEC the chosen non-empty sections (flagged in the directory); v8 header and directory. let raw_total: usize = sections.iter().map(|s| s.len()).sum();- let stored: Vec<Vec<u8>> = sections+ let stored: Vec<(Vec<u8>, bool)> = sections .iter()- .map(|s| if s.is_empty() { Vec::new() } else { tilecodec::zsec::write_zsec(s, tilecodec::zsec::ZSEC_BLOCK, 19) })+ .enumerate()+ .map(|(i, s)| {+ if s.is_empty() || !zsec.contains(&i) {+ (s.clone(), false)+ } else {+ (tilecodec::zsec::write_zsec(s, tilecodec::zsec::ZSEC_BLOCK, 19), true)+ }+ }) .collect(); let mut out = m[..HEADER_LEN].to_vec(); out[4..8].copy_from_slice(&tilecodec::mamaps::archive::TRANSIT_VERSION_ZSEC.to_le_bytes()); out[8..12].copy_from_slice(&(DEVICE_SECTIONS as u32).to_le_bytes()); let dir_at = out.len(); out.resize(dir_at + DEVICE_SECTIONS * 16, 0);- for (i, s) in stored.iter().enumerate() {+ for (i, (s, z)) in stored.iter().enumerate() { while out.len() % 8 != 0 { out.push(0); } let off = out.len() as u64; out.extend_from_slice(s); let at = dir_at + i * 16;+ let flag = if *z { tilecodec::mamaps::archive::TRANSIT_ZSEC_FLAG } else { 0 }; out[at..at + 8].copy_from_slice(&off.to_le_bytes());- out[at + 8..at + 16].copy_from_slice(&(s.len() as u64).to_le_bytes());+ out[at + 8..at + 16].copy_from_slice(&(s.len() as u64 | flag).to_le_bytes()); } std::fs::write(output, &out).map_err(|e| format!("write {output}: {e}"))?; println!(