Modern Apps git

← Modern-Apps.git

maps: pack format v4 - edge_count in metadata, length checks, --stats

Commit
d146208c85216e96a13da0ccf5a60e7395d4845a
Author
vayun-mathur <[email protected]>
When
2026-08-23 02:23 UTC (3 months ago)
Parents
841be6c

Diff

maps/src/main/rust/examples/route_diff.rs
diff --git a/maps/src/main/rust/examples/route_diff.rs b/maps/src/main/rust/examples/route_diff.rsindex a77a465588..135d32dc93 100644--- a/maps/src/main/rust/examples/route_diff.rs+++ b/maps/src/main/rust/examples/route_diff.rs@@ -19,6 +19,9 @@ //! cargo run --release --example route_diff -- gen-pairs --graph DIR --out pairs.txt [--count N] //! cargo run --release --example route_diff -- report    --graph DIR --pairs pairs.txt --out report.txt //! cargo run --release --example route_diff -- compare   --baseline a.txt --candidate b.txt [--tol-mm N]+//! cargo run --release --example route_diff -- bench     --graph DIR --pairs pairs.txt [--passes N]+//! cargo run --release --example route_diff -- dump      --graph DIR --out dump.bin+//! cargo run --release --example route_diff -- dump-compare --baseline a.bin --candidate b.bin //! ``` //! //! `Graph::load` mmaps, and `MmapRegion::map` is `#[cfg(unix)]`, so this must@@ -29,7 +32,7 @@ use std::fmt::Write as _; use std::io::Write as _;  use offlinerouter::geometry::{accurate_dist_mm, TrafficSpeeds};-use offlinerouter::graph::{get_pt_at, Graph, LatLon, BICYCLE, DRIVING, WALK};+use offlinerouter::graph::{get_pt_at, Graph, LatLon, BICYCLE, DRIVING, NO_NAME, WALK}; use offlinerouter::routing::{perform_search_loop, prepare_routing, reconstruct_path}; use offlinerouter::state::{RadixHeap, RoutingScratchpad}; @@ -51,6 +54,9 @@ fn main() -> std::process::ExitCode {         Some("report") => report(&args[1..]),         Some("compare") => compare(&args[1..]),         Some("geometry") => geometry(&args[1..]),+        Some("bench") => bench(&args[1..]),+        Some("dump") => dump(&args[1..]),+        Some("dump-compare") => dump_compare(&args[1..]),         _ => Err(USAGE.to_string()),     };     match r {@@ -68,7 +74,10 @@ usage:   route_diff gen-pairs --graph DIR --out FILE [--count N]   route_diff report    --graph DIR --pairs FILE --out FILE   route_diff compare   --baseline FILE --candidate FILE [--tol-mm N] [--tol-10ms N]-  route_diff geometry  --baseline DIR --candidate DIR";+  route_diff geometry  --baseline DIR --candidate DIR+  route_diff bench     --graph DIR --pairs FILE [--passes N]+  route_diff dump         --graph DIR --out FILE+  route_diff dump-compare --baseline FILE --candidate FILE [--limit N]";  fn flag(args: &[String], name: &str) -> Option<String> {     args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()@@ -308,6 +317,384 @@ fn report(args: &[String]) -> Result<bool, String> {     Ok(true) } +// ---------------------------------------------------------------------------+// dump / dump-compare+// ---------------------------------------------------------------------------++/// Magic and version of the dump format itself, so two dumps of different+/// vintages cannot be compared as if they were the same thing.+const DUMP_MAGIC: u32 = 0x5044_4752; // "RGDP"+const DUMP_VERSION: u32 = 1;+const DUMP_HEADER: usize = 24;+/// `u32 source, u32 target, u32 dist_mm, u32 name_offset, u8 type_, u8 speed_limit`.+const DUMP_EDGE: usize = 18;+/// `i32 lat_e7, i32 lon_e7, u64 edge_ptr`.+const DUMP_NODE: usize = 16;++/// Every field of every edge and every node, in one linear pass.+///+/// This is the strongest check available on a pack-format change, and the cheapest.+/// `report`/`compare` exercise whatever ~35 K vertices 999 sampled routes happen to+/// touch; this exercises all E edges and all N+1 nodes, so a record that decodes+/// wrongly one time in a million cannot hide. When it fails it names an edge index+/// rather than a route, which is the difference between an afternoon and five+/// minutes.+///+/// It reads through the *public* accessors — `edge_range`, `edge`,+/// `edge_name_offset` — precisely so that the widened view, the delta decode and+/// the sparse name table are all in the path being tested.+///+/// Fixed-width binary rather than text: California is 405 MB this way and 840 MB as+/// text, and `dump_compare` decodes it back into field names anyway.+fn dump(args: &[String]) -> Result<bool, String> {+    let dir = need(args, "--graph")?;+    let out = need(args, "--out")?;+    let g = load(&dir)?;++    let mut f = std::io::BufWriter::with_capacity(+        1 << 20,+        std::fs::File::create(&out).map_err(|e| format!("{out}: {e}"))?,+    );+    let mut w = |bytes: &[u8]| -> Result<(), String> {+        f.write_all(bytes).map_err(|e| format!("{out}: {e}"))+    };+    w(&DUMP_MAGIC.to_le_bytes())?;+    w(&DUMP_VERSION.to_le_bytes())?;+    w(&u64::from(g.node_count).to_le_bytes())?;+    w(&g.edge_count.to_le_bytes())?;++    // Edges in index order, which is also source order, so `source` comes from the+    // walk rather than from a search. Writing it down is the point: it is the one+    // field no `edges.bin` record has ever stored, and getting it wrong is exactly+    // how a delta-coded `target` fails.+    let mut written = 0u64;+    for u in 0..g.node_count {+        let (start, end) = g.edge_range(u);+        for idx in start..end {+            let e = g.edge(u, idx);+            w(&u.to_le_bytes())?;+            w(&e.target.to_le_bytes())?;+            w(&e.dist_mm.to_le_bytes())?;+            w(&g.edge_name_offset(idx).unwrap_or(NO_NAME).to_le_bytes())?;+            w(&[e.type_, e.speed_limit])?;+            written += 1;+        }+    }+    // Every edge must be reachable from exactly one node's range. If the ranges do+    // not tile `0..edge_count` the dump is short, and no field comparison would say+    // so.+    if written != g.edge_count {+        return Err(format!(+            "the node ranges cover {written} edge(s), not the {} in the pack",+            g.edge_count+        ));+    }++    // N + 1, because the sentinel record is read by every `edge_range` call and so+    // is as much a part of the contract as any real node.+    for v in 0..=g.node_count {+        let n = g.node(v);+        w(&n.lat_e7.to_le_bytes())?;+        w(&n.lon_e7.to_le_bytes())?;+        w(&n.edge_ptr.to_le_bytes())?;+    }+    f.flush().map_err(|e| format!("{out}: {e}"))?;+    println!(+        "{out}: {} edge(s) and {} node record(s)",+        g.edge_count,+        u64::from(g.node_count) + 1+    );+    Ok(true)+}++/// Compare two dumps element by element, naming the first few that differ.+///+/// Streams both files, because a Europe dump is 6.3 GB and holding two of them+/// would be the only reason this tool needed a big machine.+fn dump_compare(args: &[String]) -> Result<bool, String> {+    let base_path = need(args, "--baseline")?;+    let cand_path = need(args, "--candidate")?;+    let limit: usize = flag(args, "--limit")+        .as_deref()+        .unwrap_or("10")+        .parse()+        .map_err(|e| format!("--limit: {e}"))?;++    let mut b = DumpReader::open(&base_path)?;+    let mut c = DumpReader::open(&cand_path)?;+    let mut ok = true;+    if (b.node_count, b.edge_count) != (c.node_count, c.edge_count) {+        println!(+            "FAIL  counts differ: baseline {} node(s) {} edge(s), candidate {} / {}",+            b.node_count, b.edge_count, c.node_count, c.edge_count+        );+        return Ok(false);+    }+    println!(+        "DUMP  {} edge(s), {} node record(s)",+        b.edge_count,+        b.node_count + 1+    );++    let mut shown = 0usize;+    let mut edge_diffs = 0u64;+    for idx in 0..b.edge_count {+        let (x, y) = (b.next(DUMP_EDGE)?, c.next(DUMP_EDGE)?);+        if x == y {+            continue;+        }+        edge_diffs += 1;+        ok = false;+        if shown < limit {+            shown += 1;+            println!("  edge {idx}\n    baseline {}\n    candidate {}", fmt_edge(&x), fmt_edge(&y));+        }+    }++    let mut node_diffs = 0u64;+    shown = 0;+    for idx in 0..=b.node_count {+        let (x, y) = (b.next(DUMP_NODE)?, c.next(DUMP_NODE)?);+        if x == y {+            continue;+        }+        node_diffs += 1;+        ok = false;+        if shown < limit {+            shown += 1;+            let sentinel = if idx == b.node_count { " (sentinel)" } else { "" };+            println!(+                "  node {idx}{sentinel}\n    baseline {}\n    candidate {}",+                fmt_node(&x),+                fmt_node(&y)+            );+        }+    }++    println!(+        "  {edge_diffs} edge(s) and {node_diffs} node record(s) differ\n{}",+        if ok { "DUMPS IDENTICAL" } else { "DUMPS DIFFER" }+    );+    Ok(ok)+}++/// Fixed-width record reader over a dump file.+struct DumpReader {+    inner: std::io::BufReader<std::fs::File>,+    path: String,+    node_count: u64,+    edge_count: u64,+    buf: Vec<u8>,+}++impl DumpReader {+    fn open(path: &str) -> Result<DumpReader, String> {+        let f = std::fs::File::open(path).map_err(|e| format!("{path}: {e}"))?;+        let mut r = DumpReader {+            inner: std::io::BufReader::with_capacity(1 << 20, f),+            path: path.to_string(),+            node_count: 0,+            edge_count: 0,+            buf: Vec::new(),+        };+        let h = r.next(DUMP_HEADER)?;+        if u32::from_le_bytes(h[0..4].try_into().unwrap()) != DUMP_MAGIC+            || u32::from_le_bytes(h[4..8].try_into().unwrap()) != DUMP_VERSION+        {+            return Err(format!("{path} is not a v{DUMP_VERSION} dump"));+        }+        r.node_count = u64::from_le_bytes(h[8..16].try_into().unwrap());+        r.edge_count = u64::from_le_bytes(h[16..24].try_into().unwrap());+        Ok(r)+    }++    fn next(&mut self, n: usize) -> Result<Vec<u8>, String> {+        self.buf.resize(n, 0);+        std::io::Read::read_exact(&mut self.inner, &mut self.buf)+            .map_err(|e| format!("{}: {e}", self.path))?;+        Ok(self.buf.clone())+    }+}++fn fmt_edge(r: &[u8]) -> String {+    let u32_at = |i: usize| u32::from_le_bytes(r[i..i + 4].try_into().unwrap());+    format!(+        "source={} target={} dist_mm={} name_offset={} type={} speed_limit={}",+        u32_at(0),+        u32_at(4),+        u32_at(8),+        u32_at(12),+        r[16],+        r[17]+    )+}++fn fmt_node(r: &[u8]) -> String {+    format!(+        "lat_e7={} lon_e7={} edge_ptr={}",+        i32::from_le_bytes(r[0..4].try_into().unwrap()),+        i32::from_le_bytes(r[4..8].try_into().unwrap()),+        u64::from_le_bytes(r[8..16].try_into().unwrap())+    )+}++// ---------------------------------------------------------------------------+// bench+// ---------------------------------------------------------------------------++/// Time the real reader against a fixed pair set.+///+/// Every pack-format phase is measured against this and one of them is *gated* on+/// it, so the cold pass is reported apart from the warm ones. On a pack far larger+/// than RAM the first pass is almost entirely major page faults, and that is the+/// number that decides whether splitting one record across two arrays is+/// affordable; the warm passes measure the instruction path instead. Dropping the+/// page cache is the caller's job, so "cold" means whatever state it left the cache+/// in.+///+/// The route checksum is not decoration. A format change that broke routing would+/// otherwise show up here as a *speedup*, so the bench refuses to report a number+/// without also reporting what was computed.+fn bench(args: &[String]) -> Result<bool, String> {+    let dir = need(args, "--graph")?;+    let pairs_path = need(args, "--pairs")?;+    let passes: u32 = flag(args, "--passes")+        .as_deref()+        .unwrap_or("3")+        .parse()+        .map_err(|e| format!("--passes: {e}"))?;+    if passes == 0 {+        return Err("--passes wants at least one".to_string());+    }++    let load_started = std::time::Instant::now();+    let g = load(&dir)?;+    let load_ms = load_started.elapsed().as_secs_f64() * 1e3;++    let pairs = read_pairs(&pairs_path)?;+    let speeds: TrafficSpeeds = HashMap::new();+    let mut scratch = RoutingScratchpad::new();+    let mut heap = RadixHeap::new();++    println!("BENCH graph={dir} pairs={} passes={passes}", pairs.len());+    println!("  Graph::load            {load_ms:>10.1} ms");++    let mut first: Option<Pass> = None;+    let mut last = Pass::default();+    for pass in 0..passes {+        let mut p = Pass::default();+        let started = std::time::Instant::now();+        for pair in &pairs {+            let one = std::time::Instant::now();+            let mut ensure = |_lat_e7: i32, _lon_e7: i32| {};+            let ctx = prepare_routing(+                &g, &speeds, &mut ensure, pair.s_lat, pair.s_lon, pair.e_lat, pair.e_lon,+                pair.mode, &mut scratch, &mut heap,+            );+            if let Some(mut ctx) = ctx {+                perform_search_loop(+                    &g, &speeds, &mut ensure, pair.mode, &mut ctx, &mut scratch, &mut heap,+                );+                if ctx.target_node != 0xFFFF_FFFF || ctx.direct.is_some() {+                    let steps = reconstruct_path(&g, &speeds, pair.mode, &ctx, &mut scratch);+                    p.routed += 1;+                    for s in &steps {+                        // A cheap order-dependent mix, so a route that changes+                        // length, timing or turn order changes the digest.+                        p.checksum = p+                            .checksum+                            .rotate_left(7)+                            .wrapping_add(u64::from(s.dist_mm))+                            .wrapping_mul(0x1000_0000_1B3)+                            ^ u64::from(s.time_10ms);+                    }+                }+            }+            p.latency_ns.push(one.elapsed().as_nanos() as u64);+        }+        p.wall_s = started.elapsed().as_secs_f64();+        p.latency_ns.sort_unstable();+        let label = if pass == 0 { "cold" } else { "warm" };+        println!(+            "  pass {:<2} ({label})  {:>9.1} routes/s   p50 {:>7.2}  p90 {:>7.2}  \+             p99 {:>7.2}  max {:>8.2} ms",+            pass + 1,+            pairs.len() as f64 / p.wall_s,+            p.pct_ms(50),+            p.pct_ms(90),+            p.pct_ms(99),+            p.pct_ms(100),+        );+        if first.is_none() {+            first = Some(p);+        } else {+            last = p;+        }+    }+    let first = first.expect("at least one pass");+    let warm = if last.latency_ns.is_empty() { &first } else { &last };+    println!(+        "  routed                 {}/{} pair(s), checksum {:016x}",+        warm.routed,+        pairs.len(),+        warm.checksum+    );+    if first.checksum != warm.checksum || first.routed != warm.routed {+        println!("  FAIL  the passes disagree on what they routed");+        return Ok(false);+    }+    println!("  peak RSS               {:>10} kB", peak_rss_kb());+    // One line per pass is what a script diffs, but the summary line is what a+    // human reads, and the plan's tolerances are stated against these three.+    println!(+        "SUMMARY load_ms={load_ms:.1} cold_routes_s={:.1} warm_routes_s={:.1} \+         cold_p50_ms={:.3} cold_p99_ms={:.3} warm_p50_ms={:.3} warm_p99_ms={:.3} \+         peak_rss_kb={} checksum={:016x}",+        pairs.len() as f64 / first.wall_s,+        pairs.len() as f64 / warm.wall_s,+        first.pct_ms(50),+        first.pct_ms(99),+        warm.pct_ms(50),+        warm.pct_ms(99),+        peak_rss_kb(),+        warm.checksum+    );+    Ok(true)+}++#[derive(Default)]+struct Pass {+    latency_ns: Vec<u64>,+    wall_s: f64,+    routed: usize,+    checksum: u64,+}++impl Pass {+    /// The `p`-th percentile in milliseconds; `p = 100` is the maximum.+    fn pct_ms(&self, p: usize) -> f64 {+        if self.latency_ns.is_empty() {+            return 0.0;+        }+        let last = self.latency_ns.len() - 1;+        let i = (p * last / 100).min(last);+        self.latency_ns[i] as f64 / 1e6+    }+}++/// High-water mark of the process's resident set, in kB, or 0 where the kernel+/// does not report it.+fn peak_rss_kb() -> u64 {+    std::fs::read_to_string("/proc/self/status")+        .ok()+        .and_then(|s| {+            s.lines()+                .find(|l| l.starts_with("VmHWM:"))+                .and_then(|l| l.split_whitespace().nth(1)?.parse().ok())+        })+        .unwrap_or(0)+}+ // --------------------------------------------------------------------------- // compare // ---------------------------------------------------------------------------@@ -731,14 +1118,14 @@ fn scan_geometry(g: &Graph) -> GeomScan {      for u in 0..g.node_count {         let node_u = g.node(u);-        let end = g.node(u + 1).edge_ptr;-        for j in node_u.edge_ptr..end {-            let e = g.edge(j);+        let (start, end) = g.edge_range(u);+        for j in start..end {+            let e = g.edge(u, j);             if e.target >= g.node_count {                 continue;             }             pts.clear();-            match g.get_edge_coordinates(j, &mut coords) {+            match g.get_edge_coordinates_from(u, j, &mut coords) {                 Some((count, is_reversed)) if count >= 2 => {                     out.with_geometry += 1;                     if is_reversed {@@ -778,9 +1165,8 @@ fn twin_of(g: &Graph, source: u32, target: u32) -> Option<u64> {     if target >= g.node_count {         return None;     }-    let s = g.node(target).edge_ptr;-    let e = g.node(target + 1).edge_ptr;-    (s..e).find(|k| g.edge(*k).target == source)+    let (s, e) = g.edge_range(target);+    (s..e).find(|k| g.edge_targets(*k, target, source)) }  /// Approximate ground distance in metres (equirectangular). Only used to report
maps/src/main/rust/src/graph.rs
diff --git a/maps/src/main/rust/src/graph.rs b/maps/src/main/rust/src/graph.rsindex a9caaaf847..266bd42caf 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -72,9 +72,19 @@ pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// Version 2 narrowed `nodes.bin` to 12-byte records, made `lanes.bin` a sparse /// index and gave `intermediate.bin` two-level offsets — 50.8 GB of planet became /// 34 GB. Version 3 gave `intermediate.bin` a presence bitmap and dropped both-/// endpoints of every stored polyline, taking it to ~29 GB. There is no dual-path-/// reader: an older pack is rejected.-pub const GRAPH_VERSION: u32 = 3;+/// endpoints of every stored polyline, taking it to ~29 GB. Version 4 changes no+/// layout at all: it adds `edge_count` to `metadata.bin` so that nothing is+/// derived from a file's *length*, which is what the next round of record+/// narrowing would silently invalidate. There is no dual-path reader: an older+/// pack is rejected.+pub const GRAPH_VERSION: u32 = 4;++/// Sentinel `name_offset` meaning "this edge has no name".+///+/// `NO_NAME` in the generator, and an on-disk contract with it. Callers should+/// prefer [`Graph::edge_name_offset`], which spells absence as `None`; this exists+/// for the places that have to put a `u32` in a struct crossing the JNI boundary.+pub const NO_NAME: u32 = 0xFFFF_FFFF;  /// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table. ///@@ -94,8 +104,9 @@ pub const GEOMETRY_RANK_BLOCK_BYTES: u64 = 64;  // --- On-disk packed structs --- // `#[repr(C, packed)]` reproduces the exact byte strides the generator writes-// (notably `Edge` is 14 bytes, not the 16 a naturally-aligned layout would give).-// All reads go through `read_unaligned`, so element pointers need no alignment.+// (notably `EdgeRec` is 14 bytes, not the 16 a naturally-aligned layout would+// give). All reads go through `read_unaligned`, so element pointers need no+// alignment. The `const _` block below asserts every stride at compile time.  /// A `nodes.bin` record: 12 bytes, with `edge_ptr` narrowed to a `u32`. ///@@ -119,12 +130,38 @@ struct LaneEntry {     blob_off: u32, } +/// An `edges.bin` record as the generator writes it: 14 bytes.+///+/// Private, so a layout change stays inside this file. [`Graph::edge`] widens it+/// into [`Edge`]. #[repr(C, packed)] #[derive(Clone, Copy)]+struct EdgeRec {+    target: u32,+    dist_mm: u32,+    name_offset: u32,+    type_: u8,+    speed_limit: u8,+}++/// The in-memory view of an `edges.bin` record, the same widening+/// [`NodeRec`]/[`NodeMaster`] uses.+///+/// Nothing above [`Graph::edge`] sees [`EdgeRec`], so the on-disk record is free to+/// narrow a field, delta-encode it against the edge's source or move it into a+/// sparse side table without any call site changing. That is the whole reason the+/// two types are separate: the alternative is editing the same dozen call sites+/// once per layout change.+///+/// `name_offset` is deliberately *not* here. It is read on the instruction-emission+/// path and never in the A* relaxation, so it belongs in+/// [`Graph::edge_name_offset`] where a sparse representation costs nothing;+/// including it in the view would put every future reader of that field back on+/// the hot path.+#[derive(Clone, Copy)] pub struct Edge {     pub target: u32,     pub dist_mm: u32,-    pub name_offset: u32,     pub type_: u8,     pub speed_limit: u8, }@@ -144,6 +181,18 @@ pub struct LatLon {     pub lon_e7: i32, } +const _: () = {+    // Compile-time assertions that the fixed on-disk record sizes match the+    // writer. `#[repr(C, packed)]` is what makes them what they are; without these+    // a field reordered or widened by one byte changes every stride in the file and+    // still compiles, and the resulting pack loads and routes wrongly. The length+    // validation in `Graph::load` derives from these, so they are also what makes+    // that validation mean anything.+    assert!(std::mem::size_of::<NodeRec>() == 12);+    assert!(std::mem::size_of::<EdgeRec>() == 14);+    assert!(std::mem::size_of::<LaneEntry>() == 8);+};+ /// Owns a read-only `mmap` region and unmaps it on drop. pub(crate) struct MmapRegion {     ptr: *mut libc::c_void,@@ -264,8 +313,24 @@ unsafe impl Sync for Graph {} impl Graph {     /// Load the graph from `base` (a directory path, trailing slash optional).     /// Returns `None` if any mandatory file is absent, if `metadata.bin` is not a-    /// [`GRAPH_VERSION`] header, or if `intermediate.bin` is too short for this-    /// `edge_count` (a mixed-vintage pack directory).+    /// [`GRAPH_VERSION`] header, or if **any** file's length is not exactly what+    /// `metadata.bin`'s counts say it should be.+    ///+    /// # Why the lengths are checked, and checked exactly+    ///+    /// The version lives in `metadata.bin` while the layouts live in `nodes.bin`+    /// and `edges.bin`, so a matching version field cannot catch a pack directory+    /// assembled from two vintages — only the lengths can. `nodes.bin`'s length used+    /// not to be checked at all, and [`Graph::node`] documents that callers+    /// guarantee `id <= node_count` with no bounds test, so a short or stale file+    /// read straight past the mapping.+    ///+    /// Exactly, not "at least", because a file that is too *long* is just as much a+    /// vintage mismatch as one that is too short, and one comparison catches both.+    ///+    /// `road_names.bin` is the one file with no count to check against: it is a+    /// byte pool whose size is its own, and [`Graph::road_name`] bounds every read+    /// on it instead.     ///     /// `intermediate.bin` is mandatory, not optional. The generator collapses     /// degree-2 chains, so an edge is a whole road between junctions and its@@ -279,11 +344,11 @@ impl Graph {             base.push('/');         } -        // metadata.bin: u32 magic, u32 version, u64 node_count. Scoped so the-        // mapping is released before the big regions are mapped.-        let node_count = {+        // metadata.bin: u32 magic, u32 version, u64 node_count, u64 edge_count.+        // Scoped so the mapping is released before the big regions are mapped.+        let (node_count, edge_count) = {             let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;-            if meta.len < 16 {+            if meta.len < 24 {                 return None;             }             let magic = unsafe { read_at::<u32>(meta.base(), 0) };@@ -291,12 +356,33 @@ impl Graph {             if magic != GRAPH_MAGIC || version != GRAPH_VERSION {                 return None;             }-            (unsafe { read_at::<u64>(meta.base().add(8), 0) }) as u32+            let nodes = unsafe { read_at::<u64>(meta.base().add(8), 0) };+            let edges = unsafe { read_at::<u64>(meta.base().add(16), 0) };+            // `edge_ptr` is a `u32`, so an edge count past that ceiling would have+            // wrapped in the writer and pointed a node at another node's range. The+            // generator refuses to produce one; this refuses to read one.+            if u32::try_from(edges).is_err() {+                return None;+            }+            (u32::try_from(nodes).ok()?, edges)         }; +        // `edge_count` now comes from the header rather than from `edges.bin`'s+        // length. That is the point of version 4: every later version narrows the+        // record, and a derived count would change silently with the stride and+        // mis-size `intermediate.bin`'s trailer — which is computed from it.         let nodes_region = MmapRegion::map(&format!("{base}nodes.bin"))?;         let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?;-        let edge_count = (edges_region.len / std::mem::size_of::<Edge>()) as u64;+        // nodes.bin is `NodeRec[node_count + 1]`: one sentinel record past the real+        // nodes, whose `edge_ptr` is `edge_count`. Eight call sites read it.+        let want_nodes =+            (u64::from(node_count) + 1) * std::mem::size_of::<NodeRec>() as u64;+        if nodes_region.len as u64 != want_nodes {+            return None;+        }+        if edges_region.len as u64 != edge_count * std::mem::size_of::<EdgeRec>() as u64 {+            return None;+        }          // intermediate.bin:         //   [ blob ][ u64 rank[..] ][ u8 present[..] ][ u64 coarse[..] ]@@ -381,8 +467,10 @@ impl Graph {             // The sentinel entry's offset is the blob length, so checking it             // validates the blob as well as the index. That matters because             // `edge_lane_masks` reads at offsets taken straight from the file.+            // Exactly, not "at least": the writer emits header + index + blob and+            // nothing else, so a longer file is a vintage mismatch too.             let sentinel = unsafe { read_at::<LaneEntry>(index, n as usize) };-            if (r.len as u64) < index_bytes + u64::from(sentinel.blob_off) {+            if r.len as u64 != index_bytes + u64::from(sentinel.blob_off) {                 return None;             }             // Nothing else in this file mentions `edge_count`, so a stale-vintage@@ -487,6 +575,10 @@ impl Graph {      /// Safe node fetch: returns a zeroed node for out-of-range ids, mirroring     /// the C++ `get_node` fallback.+    ///+    /// Deliberately asymmetric with [`Graph::node`], which is unchecked: the+    /// sentinel index `node_count` is a *valid* read that this method rejects, and+    /// [`Graph::edge_range`] depends on being able to make it.     #[inline]     pub fn get_node(&self, id: u32) -> NodeMaster {         if self.nodes.is_null() || id >= self.node_count {@@ -499,9 +591,87 @@ impl Graph {         self.node(id)     } +    /// `[start, end)` of node `id`'s outgoing edges in `edges.bin`. `id` must be a+    /// real node, i.e. `id < node_count`.+    ///+    /// The only way to ask that question. Every caller that reads an `edge_ptr`+    /// wants a range, not an offset, so the pairing is expressed once here rather+    /// than transcribed at eight sites — which is also what stops a future+    /// `nodes.bin` layout from leaking out of this file.+    ///+    /// # What the sentinel record is for+    ///+    /// `nodes.bin` carries one record past the real nodes whose `edge_ptr` is+    /// `edge_count`. That is what makes this well-defined for the *last* real node:+    /// `id + 1` is read for every node, so without it the last one would read past+    /// the mapping and every other node's range would be one short of correct.+    /// `edge_range(node_count - 1).1 == edge_count` is the property, and it is+    /// load-bearing at eight sites.+    ///+    /// The sentinel index itself is the highest `id` this may be *passed plus one* —+    /// `edge_range(node_count)` would read `node_count + 1`, which does not exist.+    /// Every caller either iterates `0..node_count` or rejects `id >= node_count`+    /// first.+    ///+    /// Note that this goes through [`Graph::node`], which is unchecked, *not*+    /// [`Graph::get_node`], which would reject the sentinel index and silently+    /// return `edge_ptr = 0` — turning the last node's range into an empty one.+    #[inline]+    pub fn edge_range(&self, id: u32) -> (u64, u64) {+        debug_assert!(id < self.node_count, "node {id} is not a real node");+        (self.node(id).edge_ptr, self.node(id + 1).edge_ptr)+    }++    /// Edge `idx`, which must be one of node `source`'s outgoing edges.+    ///+    /// `source` is not needed to find the record today. It is in the signature+    /// because the record will stop storing `target` absolutely — a delta from the+    /// source is three bytes smaller — and because passing it makes the+    /// debug assertion below possible, which is the cheapest available guard+    /// against the one bug class that change introduces: decoding an edge against+    /// the wrong source produces a plausible node id, not a crash.+    #[inline]+    pub fn edge(&self, source: u32, idx: u64) -> Edge {+        debug_assert!(+            {+                let (s, e) = self.edge_range(source);+                (s..e).contains(&idx)+            },+            "edge {idx} is not in node {source}'s range {:?}",+            self.edge_range(source)+        );+        let r = unsafe { read_at::<EdgeRec>(self.edges, idx as usize) };+        Edge {+            target: r.target,+            dist_mm: r.dist_mm,+            type_: r.type_,+            speed_limit: r.speed_limit,+        }+    }++    /// Whether edge `idx` of node `source` points at `want`.+    ///+    /// Four call sites scan a node's edge range looking for the one edge that+    /// reaches a given node and never use the target as a value. Once `target` is+    /// stored as a delta they can answer that without widening the field at all, so+    /// the comparison lives here rather than being hand-inlined four times against+    /// whatever the record happens to hold.     #[inline]-    pub fn edge(&self, idx: u64) -> Edge {-        unsafe { read_at::<Edge>(self.edges, idx as usize) }+    pub fn edge_targets(&self, idx: u64, source: u32, want: u32) -> bool {+        self.edge(source, idx).target == want+    }++    /// Byte offset of edge `idx`'s name in the string pool, or `None` when it has+    /// none.+    ///+    /// Separate from [`Edge`] because 62% of a planet's edges are unnamed and this+    /// is read on the instruction-emission path, never in the A* relaxation — so the+    /// field can become a sparse side table without any hot-path cost. Being the+    /// sole reader is what makes that possible.+    #[inline]+    pub fn edge_name_offset(&self, idx: u64) -> Option<u32> {+        let r = unsafe { read_at::<EdgeRec>(self.edges, idx as usize) };+        (r.name_offset != NO_NAME).then_some(r.name_offset)     }      /// Real OSM per-lane turn-indication masks for directed edge `idx`, ordered@@ -607,7 +777,7 @@ impl Graph {     /// Borrow a NUL-terminated road/feed/stop name from the string pool at     /// `offset`. Returns `None` for the sentinel or out-of-range offsets.     pub fn road_name(&self, offset: u32) -> Option<String> {-        if offset == 0xFFFF_FFFF || (offset as usize) >= self.road_names_size {+        if offset == NO_NAME || (offset as usize) >= self.road_names_size {             return None;         }         Some(self.cstr_at(offset as usize))@@ -626,7 +796,25 @@ impl Graph {         }     } -    /// Largest node index whose `edge_ptr <= edge_idx` (edge_ptr is monotonic).+    /// The node whose edge range `edge_idx` falls in, i.e. the edge's source.+    ///+    /// Found by binary search on the monotonic `edge_ptr`, ~29 probes on a planet.+    /// Only for the one caller that genuinely has no source: an edge index arriving+    /// from Kotlin in `updateTrafficNative`. Everything else already holds the+    /// source, because it got the edge index by iterating a node's own range.+    ///+    /// # The tie-break is a contract, not an accident+    ///+    /// This returns the **largest** node index whose `edge_ptr <= edge_idx`. That is+    /// the unique owner of the edge — any larger node's `edge_ptr` is at least+    /// `edge_ptr(owner + 1)`, which is past `edge_idx` — but it is only the same+    /// thing as the *first* such node when every node has out-degree at least one.+    /// Degree-0 nodes exist (1,480 of California's 6.4 M, 0.023%), and they make+    /// runs of nodes share an `edge_ptr`. A reimplementation that returned the first+    /// of such a run would satisfy the description "a node whose `edge_ptr <=+    /// edge_idx`" and be wrong: that node's range is empty, and the result seeds+    /// [`Graph::decode_edge_coords`], so the failure is a polyline drawn from the+    /// wrong place rather than anything that reports an error.     pub fn find_node_idx_for_edge(&self, edge_idx: u64) -> u32 {         let mut low: i64 = 0;         let mut high: i64 = self.node_count as i64 - 1;@@ -643,7 +831,40 @@ impl Graph {         res     } -    /// 64-bit Morton code from lat/lon degrees (matches C++ `latlng_to_spatial`).+    /// 64-bit Morton (Z-order) code from lat/lon degrees.+    ///+    /// The node array is sorted by this, so it decides both what+    /// [`crate::routing::find_nearest_edge`]'s fixed 800-node window covers and how+    /// far apart two adjacent nodes' *indices* are. It must agree bit for bit with+    /// `latlng_to_spatial` in `scripts/maps/osm_ingest/src/spatial.rs`, which is+    /// what sorts the array; that crate has a test comparing the two+    /// transcriptions.+    ///+    /// # Hilbert was tried and is not better+    ///+    /// Z-order's known flaw is the "Z" discontinuity at every quadrant boundary:+    /// the cells either side are neighbours on the ground and up to a whole+    /// quadrant apart in index. Hilbert has no long-range jumps at all, so it looks+    /// like the obvious win for `edges.bin`, which stores `target` as an `i16`+    /// delta from its source and needs an escape table for the pairs that do not+    /// fit.+    ///+    /// Measured on California (`road_graph --stats`), it is not. The two curves+    /// cross almost exactly at the `i16` boundary:+    ///+    /// | `|target - source|` > | Morton | Hilbert |+    /// |---|---|---|+    /// | 1,024 | 2.225% | 2.155% |+    /// | 16,384 | 0.4711% | 0.4648% |+    /// | **32,767** | **0.3014%** | **0.3076%** |+    /// | 262,144 | 0.0713% | 0.0892% |+    ///+    /// Hilbert wins below ~16 k and loses above it: it concentrates the+    /// distribution rather than shortening it, trading mid-range deltas for far+    /// ones. So the quadrant discontinuities are *not* what generates the 0.3%+    /// tail — mapping a 2-D neighbourhood onto a 1-D index costs that much however+    /// it is done — and the escape table is unavoidable. Not worth a node+    /// permutation change for 2% the wrong way.     pub fn latlng_to_spatial(lat: f64, lon: f64) -> u64 {         let x = (lon + 180.0) / 360.0;         let y = (lat + 90.0) / 180.0;@@ -662,27 +883,14 @@ impl Graph {         Graph::latlng_to_spatial(node.lat_e7 as f64 * 1e-7, node.lon_e7 as f64 * 1e-7)     } -    /// Decode the delta-encoded coordinate blob for `edge_idx` into `out`.-    /// Returns `Some((count, is_reversed))`, with `count == 0` when the edge stores-    /// no polyline. `out` must hold at least 256 points.-    ///-    /// Prefer [`Graph::get_edge_coordinates_from`] wherever the source node is-    /// already known: this wrapper has to recover it with a ~29-probe binary-    /// search, and the stored blob is now interior-only, so the source is needed to-    /// decode at all rather than merely to find the twin.-    pub fn get_edge_coordinates(&self, edge_idx: u64, out: &mut [LatLon]) -> Option<(u32, bool)> {-        if self.edges.is_null() || edge_idx >= self.edge_count {-            return None;-        }-        let source = self.find_node_idx_for_edge(edge_idx);-        self.get_edge_coordinates_from(source, edge_idx, out)-    }--    /// [`Graph::get_edge_coordinates`] for a caller that already holds `edge_idx`'s-    /// source node — which every call site iterating a node's edge range does.+    /// Decode the delta-encoded coordinate blob for `edge_idx`, whose source is+    /// `source`, into `out`. Returns `Some((count, is_reversed))`, with `count == 0`+    /// when the edge stores no polyline. `out` must hold at least 256 points.     ///     /// `source` must really be the node whose range `edge_idx` falls in. It seeds     /// the decode, so a wrong one silently draws the polyline from the wrong place.+    /// Every call site iterating a node's edge range already has it; the one that+    /// does not recovers it with [`Graph::find_node_idx_for_edge`].     pub fn get_edge_coordinates_from(         &self,         source: u32,@@ -692,7 +900,7 @@ impl Graph {         if self.edges.is_null() || edge_idx >= self.edge_count {             return None;         }-        let e = self.edge(edge_idx);+        let e = self.edge(source, edge_idx);         if source >= self.node_count || e.target >= self.node_count {             return None;         }@@ -700,10 +908,9 @@ impl Graph {         if e.type_ & REVERSE_GEOMETRY_FLAG != 0 {             // The twin runs `target -> source`, so it is seeded and terminated the             // other way round. `get_pt_at` is what flips the result for callers.-            let s = self.node(e.target).edge_ptr;-            let e_ptr = self.node(e.target + 1).edge_ptr; // sentinel valid+            let (s, e_ptr) = self.edge_range(e.target);             for k in s..e_ptr {-                if self.edge(k).target == source {+                if self.edge_targets(k, e.target, source) {                     let cnt = self.decode_edge_coords(k, e.target, source, out);                     return Some((cnt, true));                 }
maps/src/main/rust/src/lib.rs
diff --git a/maps/src/main/rust/src/lib.rs b/maps/src/main/rust/src/lib.rsindex 2c4111cd5a..3214bd4754 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -927,10 +927,13 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_updateTraffi         let edge_id = ids[i] as u64;         let speed = sp[i] as u8;         if edge_id < g.edge_count {-            let edge = g.edge(edge_id);             if speed < 255 {                 speeds_w.insert(edge_id, speed);-                let node_u = g.node(g.find_node_idx_for_edge(edge_id));+                // The only entry point with no source node in hand: the id comes+                // from Kotlin. Recovered first, because reading the record needs it.+                let source = g.find_node_idx_for_edge(edge_id);+                let edge = g.edge(source, edge_id);+                let node_u = g.node(source);                 if edge.target < g.node_count {                     let node_v = g.node(edge.target);                     let ratio = if edge.speed_limit > 0 {
maps/src/main/rust/src/routing.rs
diff --git a/maps/src/main/rust/src/routing.rs b/maps/src/main/rust/src/routing.rsindex bf3b45c03b..7dd3e208a1 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -211,8 +211,7 @@ fn junction_lanes(         return Vec::new();     }     let jnode = g.node(junction);-    let s = jnode.edge_ptr;-    let e_ptr = g.node(junction + 1).edge_ptr; // sentinel valid+    let (s, e_ptr) = g.edge_range(junction);     let jlat = jnode.lat_e7;     let jlon = jnode.lon_e7; @@ -221,7 +220,7 @@ fn junction_lanes(     let mut opts: Vec<(f64, i32)> = Vec::new();      for k in s..e_ptr {-        let edge = g.edge(k);+        let edge = g.edge(junction, k);         if !is_mode_allowed(edge.type_, DRIVING) {             continue;         }@@ -313,9 +312,9 @@ pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdg     for i in lo..=hi {         let u_global = i as u32;         let node_u = g.node(u_global);-        let e_ptr = g.node(u_global + 1).edge_ptr; // sentinel valid-        for j in node_u.edge_ptr..e_ptr {-            let e = g.edge(j);+        let (e_start, e_ptr) = g.edge_range(u_global);+        for j in e_start..e_ptr {+            let e = g.edge(u_global, j);             if !is_mode_allowed(e.type_, mode) {                 continue;             }@@ -342,7 +341,7 @@ pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdg                             best.proj_lon = proj.lon_e7;                             best.type_ = e.type_;                             best.speed_limit = e.speed_limit;-                            best.name_offset = e.name_offset;+                            best.name_offset = g.edge_name_offset(j).unwrap_or(NO_NAME);                             best.edge_idx = j;                             best.segment_idx = p; @@ -373,7 +372,7 @@ pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdg                 best.dist_b_mm = fast_dist_mm(g, p.lat_e7, p.lon_e7, node_v.lat_e7, node_v.lon_e7);                 best.type_ = e.type_;                 best.speed_limit = e.speed_limit;-                best.name_offset = e.name_offset;+                best.name_offset = g.edge_name_offset(j).unwrap_or(NO_NAME);                 best.edge_idx = j;                 best.segment_idx = 0;             }@@ -417,7 +416,6 @@ pub fn prepare_routing(             let entry = scratch.get_entry(node);             entry.g_fwd = t_actual;             entry.g_bwd = t_actual;-            entry.last_type = start.type_;         }         let n_data = g.get_node(node);         let h = heuristic_time_10ms(g, n_data.lat_e7, n_data.lon_e7, end.proj_lat, end.proj_lon, mode);@@ -473,11 +471,10 @@ fn twin_edge(g: &Graph, source: u32, target: u32) -> Option<u64> {     if target >= g.node_count || source == target {         return None;     }-    let s = g.node(target).edge_ptr;-    let e = g.node(target + 1).edge_ptr; // sentinel valid+    let (s, e) = g.edge_range(target);     let mut found = None;     for k in s..e {-        if g.edge(k).target == source {+        if g.edge_targets(k, target, source) {             if found.is_some() {                 return None;             }@@ -550,10 +547,15 @@ fn direct_path(     let e_at = locate_on(g, &poly, e_pt.lat_e7, e_pt.lon_e7);      // Going backwards along the polyline means driving the twin, which only-    // exists when the road is not one-way.+    // exists when the road is not one-way. The twin leaves the *other* end, so the+    // source has to be chosen with the edge, not recovered afterwards.     let forward = s_at <= e_at;-    let edge_idx = if forward { start.edge_idx } else { twin? };-    let e = g.edge(edge_idx);+    let (edge_idx, edge_source) = if forward {+        (start.edge_idx, start.node_a)+    } else {+        (twin?, start.node_b)+    };+    let e = g.edge(edge_source, edge_idx);     if !is_mode_allowed(e.type_, mode) {         return None;     }@@ -576,7 +578,7 @@ fn direct_path(         time_10ms: get_edge_time_10ms(g, traffic, edge_idx, dist_mm, type_, e.speed_limit, mode),         coords,         dist_mm,-        name_offset: e.name_offset,+        name_offset: g.edge_name_offset(edge_idx).unwrap_or(NO_NAME),         type_,         speed_limit: e.speed_limit,         edge_idx,@@ -642,11 +644,10 @@ pub fn perform_search_loop(         if mode == DRIVING {             ensure_traffic(n_u.lat_e7, n_u.lon_e7);         }-        let s = n_u.edge_ptr;-        let e_ptr = g.node(u + 1).edge_ptr; // sentinel valid+        let (s, e_ptr) = g.edge_range(u);          for i in s..e_ptr {-            let edge = g.edge(i);+            let edge = g.edge(u, i);             if !is_mode_allowed(edge.type_, mode) {                 continue;             }@@ -662,8 +663,6 @@ pub fn perform_search_loop(                     entry_v.g_fwd = new_g;                     entry_v.g_bwd = new_g;                     entry_v.p_fwd = u;-                    entry_v.last_type = edge.type_;-                    entry_v.last_name_off = edge.name_offset;                     true                 } else {                     false@@ -981,12 +980,11 @@ pub fn reconstruct_path(         let node_u = g.node(u);         let node_v = g.get_node(v); -        let s = node_u.edge_ptr;-        let e_ptr = g.node(u + 1).edge_ptr;+        let (s, e_ptr) = g.edge_range(u);          let mut best_e_idx = INVALID_EDGE;         for k in s..e_ptr {-            if g.edge(k).target == v {+            if g.edge_targets(k, u, v) {                 best_e_idx = k;                 break;             }@@ -995,7 +993,8 @@ pub fn reconstruct_path(             continue;         } -        let e = g.edge(best_e_idx);+        let e = g.edge(u, best_e_idx);+        let e_name = g.edge_name_offset(best_e_idx).unwrap_or(NO_NAME);         let mut d = e.dist_mm;         if d == 0 {             d = accurate_dist_mm(node_u.lat_e7, node_u.lon_e7, node_v.lat_e7, node_v.lon_e7);@@ -1024,14 +1023,14 @@ pub fn reconstruct_path(                 b.add_segment(                     p1.lat_e7 as f64 * 1e-7, p1.lon_e7 as f64 * 1e-7,                     p2.lat_e7 as f64 * 1e-7, p2.lon_e7 as f64 * 1e-7,-                    e.name_offset, e.type_, e.speed_limit, seg_dist, best_e_idx,+                    e_name, e.type_, e.speed_limit, seg_dist, best_e_idx,                 );             }         } else {             b.add_segment(                 node_u.lat_e7 as f64 * 1e-7, node_u.lon_e7 as f64 * 1e-7,                 node_v.lat_e7 as f64 * 1e-7, node_v.lon_e7 as f64 * 1e-7,-                e.name_offset, e.type_, e.speed_limit, d, best_e_idx,+                e_name, e.type_, e.speed_limit, d, best_e_idx,             );         }     }
maps/src/main/rust/src/state.rs
diff --git a/maps/src/main/rust/src/state.rs b/maps/src/main/rust/src/state.rsindex 302d760f34..3dcbc0e88e 100644--- a/maps/src/main/rust/src/state.rs+++ b/maps/src/main/rust/src/state.rs@@ -98,21 +98,17 @@ pub struct Entry {     pub p_fwd: u32,     #[allow(dead_code)]     pub p_bwd: u32,-    pub last_name_off: u32,-    pub last_type: u8, }  impl Entry {-    /// Freshly-allocated pages are memset to 0xFF then `last_type` zeroed,-    /// matching the C++ page initializer.+    /// Freshly-allocated pages are memset to 0xFF, matching the C++ page+    /// initializer.     const FRESH: Entry = Entry {         node_id: 0xFFFF_FFFF,         g_fwd: 0xFFFF_FFFF,         g_bwd: 0xFFFF_FFFF,         p_fwd: 0xFFFF_FFFF,         p_bwd: 0xFFFF_FFFF,-        last_name_off: 0xFFFF_FFFF,-        last_type: 0,     }; } 
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex 79d55cfb20..fcb07f1bf6 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -129,16 +129,16 @@ changing its reader produces a graph that loads as garbage, which is why  | File | Layout | Reader | |---|---|---|-| `metadata.bin` | `u32 magic "MARG"`, `u32 version 3`, `u64 node_count` (16 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` |+| `metadata.bin` | `u32 magic "MARG"`, `u32 version 4`, `u64 node_count`, `u64 edge_count` (24 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` | | `nodes.bin` | `NodeRec[node_count + 1]`, **12 bytes**: `i32 lat_e7, i32 lon_e7, u32 edge_ptr`; Morton-sorted, trailing sentinel whose `edge_ptr == edge_count` | `graph.rs` — widened into `NodeMaster` by `node()` |-| `edges.bin` | `Edge[edge_count]`, **14 bytes**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` | `graph.rs` — `edge_count` comes from the *file size*, so this must be an exact multiple of 14 |+| `edges.bin` | `EdgeRec[edge_count]`, **14 bytes**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` | `graph.rs` — widened into `Edge` by `edge()`; `name_offset` reached only through `edge_name_offset()` | | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) × (n + 1)` ascending by `edge_idx`, then the packed `u16` per-lane turn masks. **Sparse**: only lane-bearing edges appear | `graph.rs` `edge_lane_masks` | | `intermediate.bin` | the delta-encoded polyline blob at **offset 0** — per storing edge, `i16 dlat, i16 dlon` per *interior* point — then a trailer: `u64 rank[E.div_ceil(512) + 1]`, `u8 present[E.div_ceil(8)]`, `u64 coarse[G.div_ceil(32) + 1]`, `u16 within[G + 1]`, `u64 G`. `off(g) = coarse[g / 32] + within[g]` where `g = rank(k)` | `graph.rs` `intermediate_range` / `decode_edge_coords` — **mandatory**, see below | | `road_names.bin` | deduped NUL-terminated UTF-8 pool; a name offset is a byte offset | `graph.rs` | | `poi_index.bin` | 14-byte records: `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type`, Morton-sorted | `PoiIndex.kt` | | `poi_names.bin` | same pool convention as `road_names.bin` | `PoiIndex.kt` | -`GRAPH_VERSION` is **3**. Version 1 stored a 16-byte node record and a dense+`GRAPH_VERSION` is **4**. Version 1 stored a 16-byte node record and a dense `u64` offset per edge in both blob files; version 2 fixed that, and version 3 gave `intermediate.bin` a presence bitmap and dropped both endpoints of every stored polyline. See [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and@@ -146,6 +146,39 @@ polyline. See [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and it. There is no dual-path reader — an older pack is rejected — so the app and the pack have to be updated together, as they already did across the v0→v1 boundary. +Version 4 changes **no layout at all**. It adds `edge_count` to `metadata.bin`, so+that the reader stops deriving it from `edges.bin`'s file size, and with it+[exact length validation](#every-files-length-is-checked) of every other file.+That has to land before any record narrows: the moment the stride changes, a+derived `edge_count` changes silently — and it is what sizes `intermediate.bin`'s+trailer, so the mis-parse would be of a *different file*.++### Every file's length is checked++Every mandatory file's length is now an exact function of the two counts in+`metadata.bin`, and `Graph::load` checks each one:++| File | Expected length |+|---|---|+| `metadata.bin` | ≥ 24 B, with the right magic and version |+| `nodes.bin` | exactly `(node_count + 1) × 12` |+| `edges.bin` | exactly `edge_count × 14` |+| `lanes.bin` | exactly `4 + (n + 1) × 8 + blob`, from its own header, plus every `edge_idx < edge_count` |+| `intermediate.bin` | trailer sized from `edge_count` and `G`, with `coarse[G/32] + within[G] == ` the blob length |++Exactly, not "at least": a file that is too long is as much a vintage mismatch as+one that is too short, and one comparison catches both. `nodes.bin`'s length used+not to be checked at all — `node()` documents that callers guarantee+`id <= node_count` and does no bounds test — so a stale or truncated file read+straight past the mapping. `road_names.bin` is the one exception: it is a byte pool+with no count of its own, and `road_name()` bounds each read against its size+instead.++Together these catch what a matching version field cannot. The version lives in+`metadata.bin` while the layouts live in `nodes.bin` and `edges.bin`, so a pack+directory assembled from two builds of the *same* version is invisible to it and+obvious to the lengths.+ The POI Morton sort key is computed from the *stored* `lat_e7`/`lon_e7`, not from the pre-rounding `f64` centroid the C++ used, so the order matches the key a reader recomputes from the file. On California that removed 9 ordering@@ -566,6 +599,92 @@ with no resolvable geometry. It does not skip them: it falls through to chord itself, as do the other six `get_edge_coordinates` call sites. So chord recovery was never the missing piece, and nothing here changes snapping coverage. +## Getting it under 25: what the census says++v3 projects a planet pack at ~29.0 GB. The next question was whether 25 GB is+reachable, and the answer had to come from measurement rather than from guessing+which field looked wasteful — so `road_graph` gained a `--stats` mode that reports+what a narrower record would cost, computed by **the encoder's own escape+predicate** rather than by an analysis script that could disagree with it by one.++```+road_graph california-latest.osm.pbf --out DIR --stats+```++Measured on California, reference path (E = 16,785,702, N = 6,418,361):++| | |+|---|---|+| `edges.bin` share of the pack | **52%** |+| `\|target − source\|` fits an `i16` | 99.699% (**50,591** escapes) |+| `dist_mm` at or above `0xFFFFFF` (16.78 km) | **166** edges, 0.001% |+| named edges | 37.72% — so 62.28% of `name_offset` is a sentinel |+| `speed_limit` zero | 91.76% |+| max out-degree | **24** |+| degree-0 nodes | **1,480** (0.023%) |+| name pool | 5,481,848 B in 323,443 names |++Three of `edges.bin`'s five fields are therefore mostly redundant, and `dist_mm`+should be a `u24` in **millimetres** rather than centimetres: only 0.001% of edges+exceed the ceiling, so the escape table is ~85 KB planet-wide and the field stays+*exact* rather than quantising 1.07 G edges to save a table.++### `c` is the number that transfers, not the escape rate++An escape rate measured on one extract says nothing about a planet 22× larger. What+should transfer is the constant in++```+P(|target − source| > n) ≈ c · n^(−1/2)+```++because a level-*k* quadrant boundary produces a delta of order `N / 4^k` and is+crossed with probability proportional to `2^k`; substituting `n = N / 4^k` gives+`P = (L·√N / W) / √n`, and `L·√N / W` is the ratio of edge length to node spacing —+a local, physical quantity that does not depend on `N`. California gives+**c ≈ 0.546** at the `i16` boundary. `--stats` prints `c` at every power of two so+the shape of the curve is visible, not just one point on it.++### Hilbert was tried, and loses++Z-order's known flaw is the discontinuity at every quadrant boundary, which is+exactly the mechanism above, so Hilbert — which has no long-range jumps at all —+looked like a free win. It is not. Both curves, same extract, same predicate:++| `\|target − source\|` > | Morton | Hilbert |+|---|---|---|+| 1,024 | 2.2254% | 2.1553% |+| 16,384 | 0.4711% | 0.4648% |+| **32,767** | **0.30139%** | **0.30756%** |+| 262,144 | 0.0713% | 0.0892% |++Hilbert wins below ~16 k and loses above it: it *concentrates* the distribution+rather than shortening it, trading mid-range deltas for far ones, and the crossover+falls almost exactly on the `i16` boundary. So the quadrant discontinuities are not+what generates the 0.3% tail — mapping a 2-D neighbourhood onto a 1-D index costs+about that much however it is done — and the escape table is unavoidable either way.+Morton stays, and `spatial.rs` now pins the discontinuity in a test so the next+person reads the measurement instead of repeating it.++### Delta-coded coordinates stay rejected++The other candidate v3 named. Longitude deltas along the Morton order fit an `i16`+only 91.4% of the time, and `find_nearest_edge` binary-searches the coordinate array+by spatial key, so it needs O(1) random access — which delta coding destroys.++### Version 4 is the de-risking step++No byte of any data file moves. What lands is the machinery every later phase needs:+`edge_count` in `metadata.bin`, [exact length validation](#every-files-length-is-checked)+of every file, compile-time record-size assertions, `Graph::edge_range` as the only+way to ask for a node's edge range, the `EdgeRec`/`Edge` widening that keeps a+layout change inside `graph.rs`, and `route_diff dump` — a per-element equivalence+dump over **all** E edges and N+1 node records, which is what later phases are+verified against instead of the ~35 K vertices 999 sampled routes happen to touch.++`route_diff` also gained a `bench` mode, so the phases that are gated on latency+rather than correctness have a baseline to be gated against.+ ## Build-time memory  The output has fitted a planet for a while; the build did not. California peaked
scripts/maps/osm_ingest/src/bin/road_graph.rs
diff --git a/scripts/maps/osm_ingest/src/bin/road_graph.rs b/scripts/maps/osm_ingest/src/bin/road_graph.rsindex a2d176cd94..1af2b9d9e1 100644--- a/scripts/maps/osm_ingest/src/bin/road_graph.rs+++ b/scripts/maps/osm_ingest/src/bin/road_graph.rs@@ -6,9 +6,82 @@ use std::process::ExitCode;  const USAGE: &str = "Usage: road_graph IN.osm.pbf [--out DIR] [--within-way-chains] \-                     [--rounds N] [--spill-dir DIR] [--spill-pts-dir DIR]   \+                     [--rounds N] [--spill-dir DIR] [--spill-pts-dir DIR] [--stats]   \                      (default --out map_data, --rounds 1)"; +/// Print what a narrower `edges.bin` record would cost on this extract.+///+/// The `c` column is the point of the table. A single escape rate measured on one+/// region says nothing about a planet 22x larger, but for nodes ordered along a+/// space-filling curve the tail decays as `P(|delta| > n) = c * n^(-1/2)`: a level-k+/// quadrant boundary produces a delta of order `N / 4^k` and is crossed with+/// probability proportional to `2^k`, and the constant is the ratio of edge length+/// to node spacing, which does not depend on `N`. So `c` is what transfers between+/// extracts, and a `c` column that is flat down the rows is the evidence that the+/// model holds at all.+fn print_census(stats: &osm_ingest::graph_build::Stats) {+    let c = &stats.census;+    let e = stats.edge_count.max(1) as f64;+    println!();+    println!("=== edges.bin narrowing census ===");+    println!("directed edges          {}", stats.edge_count);+    println!("nodes                   {}", stats.node_count);+    println!();+    println!("|target - source| tail (a level-k quadrant boundary costs ~N/4^k):");+    println!("        n        edges > n      fraction         c = P*sqrt(n)");+    for k in 0..32u32 {+        let n = 1u64 << k;+        let tail = c.delta_tail(k);+        // Once the tail empties the row says nothing, and the whole point is the+        // rows either side of the +-32767 boundary.+        if tail == 0 {+            println!("  {n:>15}  {tail:>15}  (tail empty)");+            break;+        }+        let p = tail as f64 / e;+        println!(+            "  {n:>15}  {tail:>15}  {:>12.6}%  {:>12.4}",+            p * 100.0,+            p * (n as f64).sqrt()+        );+    }+    println!();+    println!("max |target - source|   {}", c.max_delta);+    println!(+        "i16 delta escapes       {} ({:.4}% of edges)",+        c.delta_escapes,+        c.delta_escapes as f64 / e * 100.0+    );+    println!(+        "u24 dist_mm escapes     {} ({:.6}% of edges), max dist_mm {} mm",+        c.dist_escapes,+        c.dist_escapes as f64 / e * 100.0,+        c.max_dist_mm+    );+    println!(+        "merged escape rows      {} ({:.4}% of edges, {} bytes of table)",+        c.escapes,+        c.escapes as f64 / e * 100.0,+        c.escapes * 12+    );+    println!();+    println!("max out-degree          {}", c.max_degree);+    println!(+        "degree-0 nodes          {} ({:.4}% of nodes)",+        c.degree_zero_nodes,+        c.degree_zero_nodes as f64 / stats.node_count.max(1) as f64 * 100.0+    );+    println!(+        "named edges             {} ({:.4}% of edges)",+        c.named_edges,+        c.named_edges as f64 / e * 100.0+    );+    println!(+        "name pool               {} byte(s) in {} unique name(s)",+        stats.name_bytes, stats.unique_names+    );+}+ fn main() -> ExitCode {     let args: Vec<String> = std::env::args().skip(1).collect();     let (input, out_dir, opts) = match osm_ingest::graph_build::parse_args(&args) {@@ -20,6 +93,7 @@ fn main() -> ExitCode {     };      let started = std::time::Instant::now();+    let want_stats = opts.stats;     match osm_ingest::graph_build::build_with(&input, &out_dir, opts) {         Ok(stats) => {             println!(@@ -57,6 +131,9 @@ fn main() -> ExitCode {             );             println!("Peak RSS: {}", osm_ingest::mem::peak_rss_report());             println!("Wrote {}", out_dir.display());+            if want_stats {+                print_census(&stats);+            }             ExitCode::SUCCESS         }         Err(e) => {
scripts/maps/osm_ingest/src/graph_build.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build.rs b/scripts/maps/osm_ingest/src/graph_build.rsindex 28a643c673..b72c8e4998 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -7,15 +7,16 @@ //! //! | File | Layout | //! |---|---|-//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count` (16 B) |+//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count`, `u64 edge_count` (24 B) | //! | `nodes.bin` | `NodeRec[node_count + 1]`, **12 bytes each**: `i32 lat_e7, i32 lon_e7, u32 edge_ptr`; the trailing sentinel's `edge_ptr` is `edge_count` | //! | `edges.bin` | `Edge[edge_count]`, **14 bytes each**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` | //! | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) x (n + 1)` ascending by `edge_idx`, then the packed `u16` mask blob — **sparse**, only lane-bearing edges appear | //! | `intermediate.bin` | the delta-encoded polyline blob ([`crate::geom`]) at offset 0, then a trailer: `u64 rank[..]`, `u8 present[..]` (one bit per directed edge), `u64 coarse[..]`, `u16 within[..]` over the *geometry* edges, and `u64 G`. See [`GeomFile`] | //! | `road_names.bin` | deduped NUL-terminated string pool | //!-//! `edge_count` is derived on device from `edges.bin`'s *file size*, so that file-//! must stay an exact multiple of 14 bytes.+//! Every file's length is now an exact function of `metadata.bin`'s two counts, and+//! the reader checks each one. `road_names.bin` is the exception: it is a byte pool+//! with no count of its own, and reads into it are bounds-checked instead. //! //! Three behavioural notes where this differs from the C++: //!@@ -74,7 +75,11 @@ pub const BITSET_SIZE: u64 = 20_000_000_000;  /// `"MARG"` little-endian — `GRAPH_MAGIC` in `graph.rs`. const GRAPH_MAGIC: u32 = 0x4752_414D;-const GRAPH_VERSION: u32 = 3;+/// Version 4 adds `edge_count` to `metadata.bin`. No layout changed; the point is+/// that the reader stops deriving the edge count from `edges.bin`'s *length*, which+/// the next round of record narrowing would silently invalidate — and which sizes+/// `intermediate.bin`'s trailer.+const GRAPH_VERSION: u32 = 4;  /// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table /// — `INTERMEDIATE_BLOCK` in `graph.rs`, and the two must agree.@@ -119,6 +124,136 @@ const REVERSE_GEOMETRY_FLAG: u8 = 0x40; /// Fallback stop code for a transit stop node with no `name`. const UNNAMED_STOP: &[u8] = b"OSM_STOP"; +/// Sentinel in a narrowed `target` delta meaning "this record's `target` and+/// `dist_mm` both live in the escape table".+///+/// A future `edges.bin` record stores `target` as an `i16` delta from the edge's+/// own source rather than absolutely, which is only possible because the nodes are+/// sorted by a space-filling curve and an edge is short: [`Census`] measures how+/// often that fails. `i16::MIN` is reserved rather than used, so the representable+/// range is symmetric at ±32767.+const TARGET_DELTA_ESCAPE: i16 = i16::MIN;++/// Sentinel in a narrowed `u24 dist_mm` meaning the same thing.+///+/// 0xFFFFFF mm is 16.78 km, which a collapsed degree-2 chain can exceed in empty+/// country. One sentinel shared with [`TARGET_DELTA_ESCAPE`] means a single escape+/// table serves both fields, so a `dist_mm` outlier costs no extra branch and no+/// extra table.+const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;++/// `target - source` when it fits the `i16` a narrowed record stores, `None` when+/// the edge has to escape.+///+/// This is *the* escape predicate: [`Census`] counts with it and the encoder will+/// narrow with it, so the two cannot disagree by one and produce a pack that loads+/// while reading the wrong node.+#[inline]+fn target_delta(source: u32, target: u32) -> Option<i16> {+    let d = i64::from(target) - i64::from(source);+    i16::try_from(d).ok().filter(|d| *d != TARGET_DELTA_ESCAPE)+}++/// True when either field of this edge is unrepresentable inline.+#[inline]+fn edge_escapes(source: u32, target: u32, dist_mm: u32) -> bool {+    target_delta(source, target).is_none() || dist_mm >= DIST_MM_ESCAPE+}++/// One bucket per possible bit width of `|target - source|`, from a zero delta up+/// to a full `u32`. A named type only because arrays this long do not derive+/// `Default`.+pub struct DeltaBits([u64; 33]);++impl Default for DeltaBits {+    fn default() -> DeltaBits {+        DeltaBits([0u64; 33])+    }+}++impl std::ops::Deref for DeltaBits {+    type Target = [u64; 33];+    fn deref(&self) -> &[u64; 33] {+        &self.0+    }+}++impl std::ops::DerefMut for DeltaBits {+    fn deref_mut(&mut self) -> &mut [u64; 33] {+        &mut self.0+    }+}++/// What a narrower `edges.bin` record would cost, measured by the encoder itself+/// rather than by a script that might disagree with it by one.+///+/// Reported by `road_graph --stats`. Everything here is a *property of one+/// extract*, and the design that consumes it extrapolates to a planet 22x larger,+/// so the histogram matters more than any single rate: for nodes ordered by a+/// space-filling curve the tail should decay as `P(|delta| > n) ~ c * n^(-1/2)`,+/// and `c` is what transfers between extracts, not the escape rate itself.+#[derive(Default)]+pub struct Census {+    /// `delta_bits[b]` counts edges needing exactly `b` bits to be exceeded, i.e.+    /// for which `b` is the number of `k` with `2^k < |target - source|`. Suffix+    /// sums of it are the tail counts; see [`Census::delta_tail`].+    pub delta_bits: DeltaBits,+    /// Edges whose `|target - source|` will not fit an `i16`.+    pub delta_escapes: u64,+    /// Edges whose `dist_mm` reaches [`DIST_MM_ESCAPE`].+    pub dist_escapes: u64,+    /// Edges either sentinel forces into the escape table. Not the sum of the two+    /// above: an edge can fail both tests and still be one row.+    pub escapes: u64,+    pub max_delta: u32,+    pub max_dist_mm: u32,+    /// Largest out-degree of any node, which bounds a per-node `u8 degree` field.+    pub max_degree: u32,+    /// Nodes with no outgoing edge. These make several nodes share an `edge_ptr`,+    /// which is what makes `find_node_idx_for_edge`'s tie-break observable.+    pub degree_zero_nodes: u64,+    pub named_edges: u64,+}++impl Census {+    /// Edges whose `|target - source|` exceeds `1 << k`, for `k` in `0..32`.+    pub fn delta_tail(&self, k: u32) -> u64 {+        self.delta_bits[(k as usize + 1).min(32)..].iter().sum()+    }++    /// Record one directed edge.+    #[inline]+    fn edge(&mut self, source: u32, target: u32, dist_mm: u32, named: bool) {+        let delta = source.abs_diff(target);+        // The bucket is the count of `k` with `2^k < delta`, so a plain suffix sum+        // turns the histogram into the tail without a per-edge loop.+        let bits = if delta == 0 { 0 } else { 32 - (delta - 1).leading_zeros() };+        self.delta_bits[bits as usize] += 1;+        self.max_delta = self.max_delta.max(delta);+        self.max_dist_mm = self.max_dist_mm.max(dist_mm);+        if target_delta(source, target).is_none() {+            self.delta_escapes += 1;+        }+        if dist_mm >= DIST_MM_ESCAPE {+            self.dist_escapes += 1;+        }+        if edge_escapes(source, target, dist_mm) {+            self.escapes += 1;+        }+        if named {+            self.named_edges += 1;+        }+    }++    #[inline]+    fn node(&mut self, degree: u32) {+        self.max_degree = self.max_degree.max(degree);+        if degree == 0 {+            self.degree_zero_nodes += 1;+        }+    }+}+ pub struct Stats {     pub node_count: u64,     pub edge_count: u64,@@ -141,6 +276,9 @@ pub struct Stats {     /// Edges deferring to their twin's polyline.     pub reversed_edges: u64,     pub intermediate_bytes: u64,+    /// What a narrower record would cost. Always collected — it is a handful of+    /// adds per edge — and reported by `--stats`.+    pub census: Census, }  /// Bytes per rank block. 64 bytes is 512 bits and one cache line, so a rank@@ -347,6 +485,8 @@ pub struct Options {     /// but it is only ever streamed from the front, so it can live somewhere roomy     /// and slow while the randomly-read points go somewhere fast and small.     pub spill_pts_dir: Option<PathBuf>,+    /// Print the [`Census`] report after the build. Changes no output file.+    pub stats: bool, }  impl Options {@@ -573,6 +713,7 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats>         geometry_edges: written.geometry_edges,         reversed_edges: written.reversed_edges,         intermediate_bytes: written.intermediate_bytes,+        census: written.census,     }) } @@ -1279,6 +1420,7 @@ struct Written {     geometry_edges: u64,     reversed_edges: u64,     intermediate_bytes: u64,+    census: Census, }  /// Write the pack in `rounds` source-partitioned rounds.@@ -1340,6 +1482,7 @@ fn write_graph(     let mut edge_ptr: u64 = 0;     let mut geometry_edges: u64 = 0;     let mut reversed_edges: u64 = 0;+    let mut census = Census::default();      for round in 0..rounds {         // Split by node count. Contiguous and ascending, so the four output streams@@ -1404,8 +1547,10 @@ fn write_graph(         for v in lo..hi {             let node = node_coords[v as usize];             write_node(&mut nodes_out, node.0, node.1, edge_ptr as u32).map_err(io_err)?;+            let degree_base = edge_ptr;             while cursor < buffer.len() && buffer[cursor].source == v {                 let e = &buffer[cursor];+                census.edge(e.source, e.target, e.dist_mm, e.name_offset != NO_NAME);                  // --- geometry ---                 let mut type_ = e.type_;@@ -1465,6 +1610,7 @@ fn write_graph(                 edge_ptr += 1;                 cursor += 1;             }+            census.node((edge_ptr - degree_base) as u32);         }         debug_assert_eq!(cursor, buffer.len(), "the round left edges unwritten");     }@@ -1484,11 +1630,13 @@ fn write_graph(     lanes.finish()?;      // metadata.bin's magic + version let the device refuse a pack directory-    // holding files from two different vintages instead of misreading it.+    // holding files from two different vintages instead of misreading it, and its+    // counts are what every other file's length is validated against.     let mut meta = create(&out_dir.join("metadata.bin"))?;     meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;     meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;     meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;+    meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;     meta.flush().map_err(io_err)?;      Ok(Written {@@ -1496,6 +1644,7 @@ fn write_graph(         geometry_edges,         reversed_edges,         intermediate_bytes,+        census,     }) } @@ -1861,7 +2010,7 @@ fn io_err(e: std::io::Error) -> Error {  /// Parse the tool's command line: /// `road_graph IN.osm.pbf [--out DIR] [--within-way-chains] [--rounds N]-/// [--spill-dir DIR] [--spill-pts-dir DIR]`.+/// [--spill-dir DIR] [--spill-pts-dir DIR] [--stats]`. pub fn parse_args(     args: &[String], ) -> std::result::Result<(PathBuf, PathBuf, Options), String> {@@ -1877,6 +2026,7 @@ pub fn parse_args(                 out = PathBuf::from(dir);             }             "--within-way-chains" => opts.within_way_chains = true,+            "--stats" => opts.stats = true,             "--spill-dir" => {                 i += 1;                 let dir = args@@ -2218,8 +2368,9 @@ mod tests {         assert_eq!(o.meta, {             let mut want = Vec::new();             want.extend(0x4752_414Du32.to_le_bytes());-            want.extend(3u32.to_le_bytes());+            want.extend(GRAPH_VERSION.to_le_bytes());             want.extend(4u64.to_le_bytes());+            want.extend(stats.edge_count.to_le_bytes());             want         }); 
scripts/maps/osm_ingest/src/spatial.rs
diff --git a/scripts/maps/osm_ingest/src/spatial.rs b/scripts/maps/osm_ingest/src/spatial.rsindex f557252c74..bb33104ff8 100644--- a/scripts/maps/osm_ingest/src/spatial.rs+++ b/scripts/maps/osm_ingest/src/spatial.rs@@ -13,6 +13,9 @@ pub const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0; const R_MM: f64 = 6_371_000_800.0;  /// 64-bit Morton (Z-order) code of a lat/lon pair.+///+/// Hilbert was measured as the alternative and is not better at the scale that+/// matters — see `Graph::latlng_to_spatial`, which carries the numbers. pub fn latlng_to_spatial(lat: f64, lon: f64) -> u64 {     let x = (lon + 180.0) / 360.0;     let y = (lat + 90.0) / 180.0;@@ -68,7 +71,7 @@ mod tests {     }      #[test]-    fn morton_key_matches_the_router() {+    fn spatial_key_matches_the_router() {         let coords = [             (0.0, 0.0),             (37.7749, -122.4194),   // San Francisco@@ -104,6 +107,32 @@ mod tests {         assert!(a < b, "increasing longitude must increase the key");     } +    /// Z-order's defining flaw, pinned rather than merely commented: two cells that+    /// touch on the ground can be a whole quadrant apart in key, so two *adjacent+    /// nodes* can be far apart in the node array.+    ///+    /// This is why `edges.bin` cannot store `target` as a small delta from its+    /// source without an escape table, and it is what `road_graph --stats` measures+    /// the cost of. Hilbert removes this jump and still does not help at the `i16`+    /// boundary — see `Graph::latlng_to_spatial` for the measurement — so the+    /// discontinuity is documented here instead of designed away.+    #[test]+    fn morton_jumps_a_whole_quadrant_at_a_quadrant_boundary() {+        // Two points either side of the equator at the same longitude, a hair+        // apart: the y bit at the top level flips, so the keys differ in bit 63.+        let below = latlng_to_spatial(-0.0000001, 10.0);+        let above = latlng_to_spatial(0.0000001, 10.0);+        assert!(+            above.abs_diff(below) > 1 << 62,+            "expected a top-level jump, got {}",+            above.abs_diff(below)+        );+        // Whereas the same separation away from any boundary is tiny.+        let a = latlng_to_spatial(10.0, 10.0);+        let b = latlng_to_spatial(10.0000001, 10.0);+        assert!(a.abs_diff(b) < 1 << 20, "got {}", a.abs_diff(b));+    }+     #[test]     fn haversine_matches_known_city_pairs() {         // Distances are within 0.5% of the published great-circle values, which