Modern Apps git

← Modern-Apps.git

maps: junction connectors reconstruct from the planet5 graph (#planet5)

Commit
9c3fe62fb15ef32f7e7d8d67d3ddbc715b47b57c
Author
Vayun Mathur <[email protected]>
When
2026-11-14 15:27 UTC (21 days ago)
Parents
fecf761
Owner: dropping the prebuilt junction layer is acceptable only if an
on-device builder stays fully possible from what planet5 keeps. This
proves it for real data.

- schema::traffic::Graph (the junction builder's graph reader) loads
  graph v8 (varint 1e-6 degree shape points, 16 geometry edges per
  coarse entry) and v9 (zstd-block blob, inflated whole; column ZBLK
  records via Blocked), besides v6/v7.
- junction_part5.rs: an env-gated test runs junctions_for_node over
  every node of the build's own v7 graph and of planet5's v9 graph
  (thinned 1 m with the +-25 m junction zone) and matches connectors.

Inputs the builder uses, all present in planet5's graph sections:
node coordinates and edge_ptr (nodes.bin), edge targets/escapes and
type -> drivable, road class, twins/two-way (edges.bin), approach and
exit polylines for headings and arm length (intermediate.bin), turn
lane masks (lanes.bin); the driving side is the tiles' marking
convention (every z14 road tile in a non-default country carries it).
The incoming-edge index is derived, not stored.

US West: 1,839,159 junction nodes, 99.93% keep their connector count;
7.24 M connectors, 93% move <= 10 cm, p50 3 mm, p99 0.30 m; 1.5%
change their sampling because an approach heading moves ~2-3 degrees
when thinning drops a first interior point beyond the junction zone
(0.74% with thinning alone, no 1e-6 rounding). A device builder
taking headings over the first >= 5 m and arm length from dist_mm
would remove most of that; spec in the planet50 report.

Verified: the test above (passes with its documented bounds); cargo
test -p mamaps_build (293 pass).

Diff

scripts/maps/mamaps_build/src/schema/junction.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction.rs b/scripts/maps/mamaps_build/src/schema/junction.rsindex 2481f744c1..48746b2825 100644--- a/scripts/maps/mamaps_build/src/schema/junction.rs+++ b/scripts/maps/mamaps_build/src/schema/junction.rs@@ -470,4 +470,5 @@ impl Turn { include!("junction_part1.rs"); include!("junction_part2.rs"); include!("junction_part3.rs");-include!("junction_part4.rs");\ No newline at end of file+include!("junction_part4.rs");+include!("junction_part5.rs");\ No newline at end of file
scripts/maps/mamaps_build/src/schema/junction_part5.rs
diff --git a/scripts/maps/mamaps_build/src/schema/junction_part5.rs b/scripts/maps/mamaps_build/src/schema/junction_part5.rsnew file mode 100644index 0000000000..d1d1f14077--- /dev/null+++ b/scripts/maps/mamaps_build/src/schema/junction_part5.rs@@ -0,0 +1,90 @@+#[cfg(test)]+mod reconstruct_from_planet5 {+    //! The planet5 (~50 GB revision) archive drops the prebuilt junction layer (no release style+    //! draws it). This pins that the connectors stay reconstructable from what planet5 keeps: the+    //! junction builder is run over the build's own graph (the unthinned v7 `road_graph` output)+    //! and over planet5's graph (thinned to 1 m with the +-25 m junction zone, varint 1e-6 degree+    //! shape points, zstd blocks: v9), and every connector is matched.+    //!+    //! Env-gated (real graphs):+    //! `MAMAPS_JUNCTION_ORIG=<v7 graph dir> MAMAPS_JUNCTION_P5=<v9 graph dir> cargo test -p+    //! mamaps_build --release reconstruct_from_planet5 -- --ignored --nocapture`+    use super::*;++    fn connectors(dir: &Path, stride: u64) -> Vec<(u64, Vec<Vec<(f64, f64)>>)> {+        let graph = Graph::load(dir).expect("graph");+        let lanes = LaneTable::load(dir).expect("lanes");+        let incoming = InEdges::build(&graph).expect("incoming");+        let conventions = Conventions::default();+        (0..graph.node_count)+            .step_by(stride as usize)+            .map(|n| (n, junctions_for_node(n, &graph, lanes.as_ref(), &incoming, &conventions)))+            .collect()+    }++    #[test]+    #[ignore = "needs MAMAPS_JUNCTION_ORIG and MAMAPS_JUNCTION_P5 (real graphs)"]+    fn connectors_reconstruct_from_the_planet5_graph() {+        let (Ok(a), Ok(b)) = (std::env::var("MAMAPS_JUNCTION_ORIG"), std::env::var("MAMAPS_JUNCTION_P5")) else {+            return;+        };+        let stride: u64 = std::env::var("MAMAPS_JUNCTION_STRIDE").ok().and_then(|v| v.parse().ok()).unwrap_or(1);+        let ca = connectors(Path::new(&a), stride);+        let cb = connectors(Path::new(&b), stride);+        assert_eq!(ca.len(), cb.len(), "the two graphs must share node numbering");+        let (mut nodes, mut junction_nodes, mut same_count, mut conn_a, mut conn_b) = (0u64, 0u64, 0u64, 0u64, 0u64);+        let mut devs: Vec<f64> = Vec::new();+        for ((n, x), (m, y)) in ca.iter().zip(cb.iter()) {+            assert_eq!(n, m);+            nodes += 1;+            conn_a += x.len() as u64;+            conn_b += y.len() as u64;+            if x.is_empty() && y.is_empty() {+                continue;+            }+            junction_nodes += 1;+            if x.len() == y.len() {+                same_count += 1;+                for (p, q) in x.iter().zip(y.iter()) {+                    let mut d = 0.0f64;+                    if p.len() != q.len() {+                        d = f64::INFINITY;+                    } else {+                        for (u, v) in p.iter().zip(q.iter()) {+                            let dy = (u.1 - v.1) * 111_320.0;+                            let dx = (u.0 - v.0) * 111_320.0 * u.1.to_radians().cos();+                            d = d.max(dx.hypot(dy));+                        }+                    }+                    devs.push(d);+                }+            }+        }+        let inf = devs.iter().filter(|d| d.is_infinite()).count();+        devs.retain(|d| d.is_finite());+        devs.sort_by(|a, b| a.total_cmp(b));+        println!("connectors with a different sample count (shape changed, e.g. turn class or sweep bucket): {inf}");+        let pct = |q: f64| devs.get(((devs.len() as f64 - 1.0) * q) as usize).copied().unwrap_or(0.0);+        let exact = devs.iter().filter(|d| **d == 0.0).count();+        let within_10cm = devs.iter().filter(|d| **d <= 0.10).count();+        println!(+            "nodes {nodes} junction nodes {junction_nodes} (same connector count at {same_count}) | connectors orig {conn_a} p5 {conn_b} | \+             matched {} : exact {exact}, <=10 cm {within_10cm}, p50 {:.3} m p99 {:.3} m max {:.3} m",+            devs.len(),+            pct(0.5),+            pct(0.99),+            pct(1.0)+        );+        assert!(conn_a > 0, "no connectors built from the original graph");+        assert!(same_count as f64 >= junction_nodes as f64 * 0.999, "junction nodes whose connector count changed");+        // Measured on US West (v7 build graph vs planet5 v9): 99.93% of junction nodes keep their+        // connector count; of the connectors, 93% move <= 10 cm, p99 0.30 m; 1.5% change their+        // sampling, from approach headings that move <= ~2-3 degrees when 1 m thinning drops a+        // first interior point beyond the 25 m junction zone (or 1e-6 degree rounding meets a+        // very short first step). Every input is present; see the planet50 report for the+        // device-builder spec (headings over the first >= 5 m and arm length from `dist_mm`).+        assert!(inf as f64 <= conn_a as f64 * 0.03, "more than 3% of connectors changed sampling");+        assert!(within_10cm as f64 >= devs.len() as f64 * 0.9, "fewer than 90% of connectors within 10 cm");+        assert!(pct(0.5) <= 0.01, "median connector deviation above 1 cm");+    }+}
scripts/maps/mamaps_build/src/schema/traffic.rs
diff --git a/scripts/maps/mamaps_build/src/schema/traffic.rs b/scripts/maps/mamaps_build/src/schema/traffic.rsindex 9123e42ea2..58b795b170 100644--- a/scripts/maps/mamaps_build/src/schema/traffic.rs+++ b/scripts/maps/mamaps_build/src/schema/traffic.rs@@ -91,8 +91,14 @@ pub fn traffic_class() -> Class { // --- v6/v7 graph on-disk constants (see traffic_id_contract.md §2 / graph.rs) -----------------  pub(crate) const MARG_MAGIC: u32 = 0x4752_414D; // "MARG"-/// Newest graph version: v7 blocked record sections.+/// First graph version with blocked record sections (v7). The build reads v7 straight out of+/// `road_graph`; v8/v9 (planet5's varint / zstd-block shape points, see [`GRAPH_VERSION_MAX`])+/// load too, for the junction-reconstruction check. pub(crate) const GRAPH_VERSION: u32 = 7;+/// Newest graph version read: v9.+pub(crate) const GRAPH_VERSION_MAX: u32 = 9;+/// v8+: 16 geometry edges per coarse intermediate entry (`graph.rs` INTERMEDIATE_BLOCK_V8).+const INTERMEDIATE_BLOCK_V8: u64 = 16; /// Oldest graph version accepted: v6 raw tables still read directly. pub(crate) const GRAPH_VERSION_MIN: u32 = 6; /// One escape block index per 1024 edges (`graph.rs` ESCAPE_BLOCK).@@ -214,6 +220,12 @@ pub(crate) struct Graph {     geom_present_off: usize,     coarse_off: usize,     within_off: usize,+    /// Geometry edges per coarse entry: 32 (v6/v7) or 16 (v8+).+    inter_block: u64,+    /// v8+: blobs are zigzag varint deltas on a 1e-6 degree grid.+    varint_v8: bool,+    /// v9: the inflated blob (the file holds a ZSEC section). Empty otherwise.+    blob_owned: Vec<u8>, }  impl Graph {@@ -251,11 +263,14 @@ impl Graph {             return err("metadata.bin is not a MARG graph header".to_string());         }         let version = u32_at(&meta, 4);-        if !(GRAPH_VERSION_MIN..=GRAPH_VERSION).contains(&version) {+        if !(GRAPH_VERSION_MIN..=GRAPH_VERSION_MAX).contains(&version) {             return err(format!(-                "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION}"+                "the graph is version {version}; the traffic layer reads v{GRAPH_VERSION_MIN}..=v{GRAPH_VERSION_MAX}"             ));         }+        let varint_v8 = version >= 8;+        let zsec_v9 = version >= 9;+        let inter_block = if varint_v8 { INTERMEDIATE_BLOCK_V8 } else { INTERMEDIATE_BLOCK };         let blocked_v7 = version >= GRAPH_VERSION;         let node_count = u64_at(&meta, 8);         let edge_count = u64_at(&meta, 16);@@ -355,7 +370,7 @@ impl Graph {             ));         }         let bitmap_bytes = edge_bitmap_bytes(edge_count);-        let coarse_bytes = ((g_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8) as usize;+        let coarse_bytes = ((g_edges.div_ceil(inter_block) + 1) * 8) as usize;         let within_bytes = ((g_edges + 1) * 2) as usize;         let trailer = bitmap_bytes + coarse_bytes + within_bytes + 8;         if inter.len() < trailer {@@ -365,6 +380,18 @@ impl Graph {             ));         }         let blob_bytes = inter.len() - trailer;+        // v9: the blob is a ZSEC section; inflate it whole (a batch tool walks it all).+        let blob_owned = if zsec_v9 {+            let z = tilecodec::zsec::ZSec::parse(&inter[..blob_bytes])+                .map_err(|e| osm_ingest::proto::Error(format!("intermediate.bin v9 blob: {e:?}")))?;+            let mut raw = Vec::with_capacity(z.raw_len() as usize);+            for b in 0..z.block_count() {+                raw.extend_from_slice(&z.block(b).map_err(|e| osm_ingest::proto::Error(format!("{e:?}")))?);+            }+            raw+        } else {+            Vec::new()+        };         let geom_rank_off = blob_bytes;         let geom_present_off = blob_bytes + present_offset(edge_count);         let coarse_off = blob_bytes + bitmap_bytes;@@ -383,6 +410,9 @@ impl Graph {             geom_present_off,             coarse_off,             within_off,+            inter_block,+            varint_v8,+            blob_owned,         })     } @@ -453,7 +483,7 @@ impl Graph {      /// The blob byte offset of the `g`th geometry edge: `coarse[g/32] + within[g]`.     fn geom_offset(&self, g: u64) -> u64 {-        let coarse = u64_at(&self.inter, self.coarse_off + (g / INTERMEDIATE_BLOCK) as usize * 8);+        let coarse = u64_at(&self.inter, self.coarse_off + (g / self.inter_block) as usize * 8);         let within = u16_at(&self.inter, self.within_off + (g as usize) * 2) as u64;         coarse + within     }@@ -476,6 +506,37 @@ impl Graph {         let mut out = Vec::with_capacity(4);         out.push((slat, slon));         if let Some((start, end)) = self.intermediate_range(idx) {+            if self.varint_v8 {+                // Mirrors graph.rs decode_edge_coords (v8/v9).+                let blob: &[u8] = if self.blob_owned.is_empty() { &self.inter } else { &self.blob_owned };+                let b = &blob[start..end.min(blob.len())];+                let q = |v: i32| (v as i64).div_euclid(10) + i64::from((v as i64).rem_euclid(10) >= 5);+                let (mut qlat, mut qlon) = (q(slat), q(slon));+                let mut at = 0usize;+                let mut uvar = |at: &mut usize| -> Option<u64> {+                    let (mut r, mut sh) = (0u64, 0u32);+                    while *at < b.len() {+                        let x = b[*at];+                        *at += 1;+                        r |= u64::from(x & 0x7f) << sh;+                        if x & 0x80 == 0 {+                            return Some(r);+                        }+                        sh += 7;+                    }+                    None+                };+                let mut count = 1usize;+                while at < b.len() && count + 1 < MAX_POINTS {+                    let (Some(a), Some(c)) = (uvar(&mut at), uvar(&mut at)) else { break };+                    qlat += ((a >> 1) as i64) ^ -((a & 1) as i64);+                    qlon += ((c >> 1) as i64) ^ -((c & 1) as i64);+                    out.push(((qlat * 10) as i32, (qlon * 10) as i32));+                    count += 1;+                }+                out.push((tlat, tlon));+                return out;+            }             let (mut lat, mut lon) = (slat, slon);             let mut off = start;             // count starts at 1 for the source; the reader stops at MAX_POINTS total, matching