maps: collapse degree-2 chains and land the v3 pack format (~29 GB planet)
- Commit
af6ba8e432cc9a0d8f779194f87ff7403223f3a2- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-23 00:35 UTC (3 months ago)
- Parents
dd7e0b3
Diff
maps/src/main/java/com/vayunmathur/maps/MainActivity.kt
diff --git a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt b/maps/src/main/java/com/vayunmathur/maps/MainActivity.ktindex 184e46e394..d81da253b3 100644--- a/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt+++ b/maps/src/main/java/com/vayunmathur/maps/MainActivity.kt@@ -87,6 +87,11 @@ class MainActivity : ComponentActivity() { Triple("https://data.vayunmathur.com/nodes.bin", "nodes.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/edges.bin", "edges.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/lanes.bin", "lanes.bin", getString(R.string.downloading_road_data)),+ // Per-edge geometry. Mandatory: the generator collapses+ // degree-2 chains, so one edge is a whole road and this file+ // is the only record of its shape. Graph.load refuses a pack+ // without it rather than snapping to straight chords.+ Triple("https://data.vayunmathur.com/intermediate.bin", "intermediate.bin", getString(R.string.downloading_road_data)), Triple("https://data.vayunmathur.com/poi_index.bin", "poi_index.bin", getString(R.string.downloading_poi_data)), Triple("https://data.vayunmathur.com/poi_names.bin", "poi_names.bin", getString(R.string.downloading_poi_data)), Triple("https://data.vayunmathur.com/world.transit", "world.transit", getString(R.string.downloading_transit_data))
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.rsnew file mode 100644index 0000000000..a77a465588--- /dev/null+++ b/maps/src/main/rust/examples/route_diff.rs@@ -0,0 +1,797 @@+//! Route-level differential oracle for road-graph changes.+//!+//! Compaction renumbers nodes and edges and changes their counts, so no output+//! file of two graphs built from the same region is comparable byte-wise. What+//! *is* comparable is what the router does with them: for a fixed list of+//! origin/destination coordinates, the total distance, the total time, the turn+//! sequence and the decoded polyline.+//!+//! This lives in the engine crate, and drives `Graph::load` ++//! `prepare_routing` + `perform_search_loop` + `reconstruct_path` directly,+//! because the point is to exercise the real reader — including+//! `decode_edge_coords` and the `REVERSE_GEOMETRY_FLAG` twin lookup — rather+//! than a host reimplementation of it.+//!+//! It is an `examples/` target, not `src/bin/`, so `cargo build` for the+//! Android lib never picks it up.+//!+//! ```text+//! 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]+//! ```+//!+//! `Graph::load` mmaps, and `MmapRegion::map` is `#[cfg(unix)]`, so this must+//! run on Linux (WSL is fine).++use std::collections::{HashMap, HashSet};+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::routing::{perform_search_loop, prepare_routing, reconstruct_path};+use offlinerouter::state::{RadixHeap, RoutingScratchpad};++/// One origin/destination probe. Coordinates, not node ids: ids move when the+/// graph is rebuilt, coordinates do not, which is the whole point.+struct Pair {+ kind: String,+ mode: i32,+ s_lat: f64,+ s_lon: f64,+ e_lat: f64,+ e_lon: f64,+}++fn main() -> std::process::ExitCode {+ let args: Vec<String> = std::env::args().skip(1).collect();+ let r = match args.first().map(String::as_str) {+ Some("gen-pairs") => gen_pairs(&args[1..]),+ Some("report") => report(&args[1..]),+ Some("compare") => compare(&args[1..]),+ Some("geometry") => geometry(&args[1..]),+ _ => Err(USAGE.to_string()),+ };+ match r {+ Ok(true) => std::process::ExitCode::SUCCESS,+ Ok(false) => std::process::ExitCode::FAILURE,+ Err(e) => {+ eprintln!("error: {e}");+ std::process::ExitCode::FAILURE+ }+ }+}++const USAGE: &str = "\+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";++fn flag(args: &[String], name: &str) -> Option<String> {+ args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned()+}++fn need(args: &[String], name: &str) -> Result<String, String> {+ flag(args, name).ok_or_else(|| format!("missing {name}\n{USAGE}"))+}++fn load(dir: &str) -> Result<Graph, String> {+ Graph::load(dir).ok_or_else(|| {+ format!("cannot load a graph from {dir} (missing/short files, or a bad metadata.bin header)")+ })+}++// ---------------------------------------------------------------------------+// gen-pairs+// ---------------------------------------------------------------------------++/// Sample probe pairs from a graph's node array and write them as coordinates.+///+/// Three length classes, because they stress different things. `long` pairs+/// exercise the search itself; `mid` pairs exercise turn-by-turn output; and+/// `near` pairs put both endpoints within a few nodes of each other, which+/// after compaction is very often the *same* collapsed edge — the case where a+/// straight-chord graph and a collapsed graph can disagree most.+fn gen_pairs(args: &[String]) -> Result<bool, String> {+ let dir = need(args, "--graph")?;+ let out = need(args, "--out")?;+ let count: u32 = flag(args, "--count")+ .as_deref()+ .unwrap_or("300")+ .parse()+ .map_err(|e| format!("--count: {e}"))?;++ let g = load(&dir)?;+ if g.node_count < 16 {+ return Err(format!("graph has only {} node(s)", g.node_count));+ }+ let n = u64::from(g.node_count);++ // Deterministic sampling: a fixed odd multiplier walked over the node+ // array. No RNG, so the pair file is reproducible from any graph of the+ // same region without carrying a seed.+ let mut buf = String::new();+ buf.push_str("# route_diff pairs: kind mode s_lat s_lon e_lat e_lon\n");+ buf.push_str(&format!("# generated from {dir} ({} nodes)\n", g.node_count));+ let mut emitted = 0u32;+ let mut k = 0u64;+ while emitted < count {+ let i = (k.wrapping_mul(2_654_435_761) % n) as u32;+ let (kind, mode, j) = match emitted % 5 {+ 0 => ("long", DRIVING, (k.wrapping_mul(40_503) % n) as u32),+ 1 => ("mid", DRIVING, ((u64::from(i) + 4_000) % n) as u32),+ 2 => ("near", DRIVING, ((u64::from(i) + 3) % n) as u32),+ 3 => ("near", WALK, ((u64::from(i) + 2) % n) as u32),+ _ => ("mid", BICYCLE, ((u64::from(i) + 500) % n) as u32),+ };+ k += 1;+ if i == j {+ continue;+ }+ let a = g.node(i);+ let b = g.node(j);+ // A node at (0, 0) means the graph has a hole where a coordinate should+ // be; probing it tests nothing.+ if (a.lat_e7 == 0 && a.lon_e7 == 0) || (b.lat_e7 == 0 && b.lon_e7 == 0) {+ continue;+ }+ // Nudge off the node itself so the probe exercises mid-edge snapping+ // rather than landing exactly on a vertex.+ buf.push_str(&format!(+ "{} {} {:.7} {:.7} {:.7} {:.7}\n",+ kind,+ mode,+ f64::from(a.lat_e7) * 1e-7 + 1e-6,+ f64::from(a.lon_e7) * 1e-7 - 1e-6,+ f64::from(b.lat_e7) * 1e-7 - 1e-6,+ f64::from(b.lon_e7) * 1e-7 + 1e-6,+ ));+ emitted += 1;+ }+ write_file(&out, buf.as_bytes())?;+ println!("wrote {emitted} pair(s) to {out}");+ Ok(true)+}++fn read_pairs(path: &str) -> Result<Vec<Pair>, String> {+ let text = std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"))?;+ let mut out = Vec::new();+ for (ln, line) in text.lines().enumerate() {+ if line.starts_with('#') || line.trim().is_empty() {+ continue;+ }+ let f: Vec<&str> = line.split_whitespace().collect();+ if f.len() != 6 {+ return Err(format!("{path}:{}: want 6 fields, got {}", ln + 1, f.len()));+ }+ let num = |s: &str| s.parse::<f64>().map_err(|e| format!("{path}:{}: {e}", ln + 1));+ out.push(Pair {+ kind: f[0].to_string(),+ mode: f[1].parse::<i32>().map_err(|e| format!("{path}:{}: {e}", ln + 1))?,+ s_lat: num(f[2])?,+ s_lon: num(f[3])?,+ e_lat: num(f[4])?,+ e_lon: num(f[5])?,+ });+ }+ Ok(out)+}++// ---------------------------------------------------------------------------+// report+// ---------------------------------------------------------------------------++/// Route every pair and write a line-oriented report.+///+/// The format is deliberately flat text: one `PAIR` line per probe carrying the+/// totals, then one `STEP` line per turn, then one `GEOM` line holding the+/// whole polyline. `compare` reads it back field by field, so totals can carry+/// a tolerance while the turn sequence and geometry are matched exactly.+fn report(args: &[String]) -> Result<bool, String> {+ let dir = need(args, "--graph")?;+ let pairs_path = need(args, "--pairs")?;+ let out = need(args, "--out")?;++ let g = load(&dir)?;+ let pairs = read_pairs(&pairs_path)?;+ let speeds: TrafficSpeeds = HashMap::new();+ let mut scratch = RoutingScratchpad::new();+ let mut heap = RadixHeap::new();++ let mut buf = String::new();+ let _ = writeln!(buf, "# route_diff report");+ let _ = writeln!(buf, "GRAPH nodes={} edges={}", g.node_count, g.edge_count);+ let _ = writeln!(buf, "PAIRS {}", pairs.len());++ let mut routed = 0usize;+ for (i, p) in pairs.iter().enumerate() {+ // No traffic on a host report: live speeds are a device-side input and+ // would make the differential depend on when it ran.+ let mut ensure = |_lat_e7: i32, _lon_e7: i32| {};+ let ctx = prepare_routing(+ &g, &speeds, &mut ensure, p.s_lat, p.s_lon, p.e_lat, p.e_lon, p.mode, &mut scratch,+ &mut heap,+ );+ let mut ctx = match ctx {+ Some(c) => c,+ None => {+ let _ = writeln!(buf, "PAIR {i} {} mode={} no_snap", p.kind, p.mode);+ continue;+ }+ };+ perform_search_loop(&g, &speeds, &mut ensure, p.mode, &mut ctx, &mut scratch, &mut heap);+ // Where the query points landed on the network, and on which edges.+ // Emitted before the routability check because a pair that stops routing+ // is usually a pair that snapped somewhere else, and that is only+ // visible if the snap is reported either way.+ //+ // Reported separately from the route because a rebuild that moves the+ // node set changes how far `find_nearest_edge`'s fixed 800-node window+ // reaches: a route that starts somewhere else is not the same question as+ // a route that takes a different path from the same place.+ let _ = writeln!(+ buf,+ "SNAP {i} s={:.7},{:.7} e={:.7},{:.7} s_off={:.1} e_off={:.1} s_road={} e_road={} direct={}",+ f64::from(ctx.start.proj_lat) * 1e-7,+ f64::from(ctx.start.proj_lon) * 1e-7,+ f64::from(ctx.end.proj_lat) * 1e-7,+ f64::from(ctx.end.proj_lon) * 1e-7,+ // How far the query point had to move to reach the network. This is+ // the measure of snap *quality*: the pairs were sampled from node+ // coordinates, so a good snap lands within centimetres.+ crow_m(p.s_lat, p.s_lon, f64::from(ctx.start.proj_lat) * 1e-7, f64::from(ctx.start.proj_lon) * 1e-7),+ crow_m(p.e_lat, p.e_lon, f64::from(ctx.end.proj_lat) * 1e-7, f64::from(ctx.end.proj_lon) * 1e-7),+ g.road_name(ctx.start.name_offset).unwrap_or_default(),+ g.road_name(ctx.end.name_offset).unwrap_or_default(),+ u8::from(ctx.direct.is_some())+ );+ let _ = writeln!(+ buf,+ "EDGE {i} s_edge={} s_ab={},{} e_edge={} e_ab={},{} twin={}",+ ctx.start.edge_idx,+ ctx.start.node_a,+ ctx.start.node_b,+ ctx.end.edge_idx,+ ctx.end.node_a,+ ctx.end.node_b,+ // Whether the road can be travelled the other way at all. When both+ // ends snap to one edge but in the wrong order, this is what decides+ // between "stay on the road" and "go around the block".+ twin_of(&g, ctx.start.node_a, ctx.start.node_b)+ .map_or(-1i64, |k| i64::try_from(k).unwrap_or(-2))+ );+ // A route that never leaves its snapped edge reaches no node, so+ // `target_node` stays unset and `ctx.direct` carries the route instead.+ if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() {+ let _ = writeln!(buf, "PAIR {i} {} mode={} no_route", p.kind, p.mode);+ continue;+ }+ let steps = reconstruct_path(&g, &speeds, p.mode, &ctx, &mut scratch);+ let dist: u64 = steps.iter().map(|s| s.dist_mm).sum();+ let time: u64 = steps.iter().map(|s| s.time_10ms).sum();+ routed += 1;+ let _ = writeln!(+ buf,+ "PAIR {i} {} mode={} ok dist_mm={dist} time_10ms={time} steps={}",+ p.kind,+ p.mode,+ steps.len()+ );+ for (k, s) in steps.iter().enumerate() {+ let name = g.road_name(s.name_off).unwrap_or_default();+ let _ = writeln!(+ buf,+ "STEP {i} {k} maneuver={} dist_mm={} time_10ms={} pts={} name={name}",+ s.maneuver,+ s.dist_mm,+ s.time_10ms,+ s.coords.len() / 2+ );+ }+ // The polyline is the claim that compaction is geometry-preserving, so+ // it is compared exactly. `coords` is flat [lon, lat, ...] from+ // `StepData`; 7 decimals is the graph's own resolution.+ let _ = write!(buf, "GEOM {i}");+ for s in &steps {+ for c in s.coords.chunks_exact(2) {+ let _ = write!(buf, " {:.7},{:.7}", c[1], c[0]);+ }+ }+ buf.push('\n');+ }+ let _ = writeln!(buf, "ROUTED {routed}/{}", pairs.len());+ write_file(&out, buf.as_bytes())?;+ println!("{out}: routed {routed}/{} pair(s)", pairs.len());+ Ok(true)+}++// ---------------------------------------------------------------------------+// compare+// ---------------------------------------------------------------------------++/// Compare two reports.+///+/// The pass criterion has to account for the fact that a rebuild which changes+/// the node set also changes *snapping*: `find_nearest_edge` scans a fixed+/// window of 800 nodes in Morton order, so with fewer, longer edges it reaches+/// further and legitimately finds a different — often nearer — road. A route from+/// a different starting edge is not a regression, it is a different question.+///+/// So pairs are split by whether both ends snapped to the same place:+///+/// * **Same snap, same distance** is the strict case: the turn sequence and the+/// polyline must match exactly. This is where a geometry or bookkeeping bug+/// would show, and it is the only class treated as a failure.+/// * **Same snap, different distance** is an alternative optimum. Reported.+/// * **Moved snap** is reported and counted, not failed.+///+/// A pair that stops being routable is always a failure; one that becomes+/// routable is not.+fn compare(args: &[String]) -> Result<bool, String> {+ let base_path = need(args, "--baseline")?;+ let cand_path = need(args, "--candidate")?;+ let tol_mm: u64 = flag(args, "--tol-mm")+ .as_deref()+ .unwrap_or("1000")+ .parse()+ .map_err(|e| format!("--tol-mm: {e}"))?;+ let tol_time: u64 = flag(args, "--tol-10ms")+ .as_deref()+ .unwrap_or("100")+ .parse()+ .map_err(|e| format!("--tol-10ms: {e}"))?;+ // How far a snap may move before the pair is no longer "the same question".+ let snap_tol_m: f64 = flag(args, "--tol-snap-m")+ .as_deref()+ .unwrap_or("1.0")+ .parse()+ .map_err(|e| format!("--tol-snap-m: {e}"))?;++ let base = std::fs::read_to_string(&base_path).map_err(|e| format!("{base_path}: {e}"))?;+ let cand = std::fs::read_to_string(&cand_path).map_err(|e| format!("{cand_path}: {e}"))?;++ let bp = index_by_key(&base, "PAIR");+ let cp = index_by_key(&cand, "PAIR");+ let bs_snap = index_by_key(&base, "SNAP");+ let cs_snap = index_by_key(&cand, "SNAP");+ let bg = index_by_key(&base, "GEOM");+ let cg = index_by_key(&cand, "GEOM");+ let bs = index_steps(&base);+ let cs = index_steps(&cand);++ let mut fails: Vec<String> = Vec::new();+ let mut lost = 0usize;+ let mut gained = 0usize;+ let mut moved_snap = 0usize;+ let mut strict = 0usize;+ let mut alt_optimum = 0usize;+ let mut worst_dist = 0i64;+ let mut worst_time = 0i64;++ let mut keys: Vec<&String> = bp.keys().collect();+ keys.sort_by_key(|k| k.parse::<u64>().unwrap_or(u64::MAX));++ for k in &keys {+ let b = &bp[*k];+ let c = match cp.get(*k) {+ Some(c) => c,+ None => {+ fails.push(format!("pair {k}: missing from the candidate report"));+ continue;+ }+ };+ let b_ok = b.contains(&"ok".to_string());+ let c_ok = c.contains(&"ok".to_string());+ // Snap movement is checked first, and outranks routability. A query point+ // that is a kilometre from any road can snap onto a nearer but+ // disconnected one after a rebuild, and calling that a lost route blames+ // the graph for an unreasonable question.+ let shift = snap_shift_m(bs_snap.get(*k), cs_snap.get(*k));+ if shift > snap_tol_m {+ moved_snap += 1;+ continue;+ }+ if b_ok && !c_ok {+ lost += 1;+ fails.push(format!("pair {k}: snapped to the same place but is no longer routable"));+ continue;+ }+ if !b_ok {+ if c_ok {+ gained += 1;+ }+ continue;+ }++ let dd = kv(c, "dist_mm").unwrap_or(0) as i64 - kv(b, "dist_mm").unwrap_or(0) as i64;+ let dt = kv(c, "time_10ms").unwrap_or(0) as i64 - kv(b, "time_10ms").unwrap_or(0) as i64;+ if dd.abs() > worst_dist.abs() {+ worst_dist = dd;+ }+ if dt.abs() > worst_time.abs() {+ worst_time = dt;+ }++ if dd.unsigned_abs() > tol_mm || dt.unsigned_abs() > tol_time {+ alt_optimum += 1;+ continue;+ }++ // Same snap, same length: the roads travelled and the path drawn must+ // match.+ strict += 1;+ let b_roads = bs.get(*k).map(road_seq).unwrap_or_default();+ let c_roads = cs.get(*k).map(road_seq).unwrap_or_default();+ if b_roads != c_roads {+ fails.push(format!(+ "pair {k}: same snap and same length, but the roads travelled differ \+ ({} vs {}, first at {:?})",+ b_roads.len(),+ c_roads.len(),+ first_mismatch(&b_roads, &c_roads)+ ));+ }+ let b_line = polyline_points(bg.get(*k));+ let c_line = polyline_points(cg.get(*k));+ if !same_path(&b_line, &c_line) {+ fails.push(format!(+ "pair {k}: same snap and same length, but the path differs \+ ({} vs {} distinct point(s))",+ b_line.len(),+ c_line.len()+ ));+ }+ }++ for k in cp.keys() {+ if !bp.contains_key(k) {+ fails.push(format!("pair {k}: only in the candidate report"));+ }+ }++ println!("{} pair(s) compared", keys.len());+ println!(" {strict:>5} same snap, same length (compared strictly)");+ println!(" {alt_optimum:>5} same snap, different length (alternative optimum)");+ println!(" {moved_snap:>5} snapped somewhere else (>{snap_tol_m} m)");+ println!(" {gained:>5} became routable");+ println!(" {lost:>5} stopped being routable");+ println!("worst dist delta {worst_dist} mm, worst time delta {worst_time} (10 ms units)");+ for f in fails.iter().take(20) {+ println!(" {f}");+ }+ if fails.len() > 20 {+ println!(" ({} further finding(s) suppressed)", fails.len() - 20);+ }+ println!(+ "{}",+ if fails.is_empty() { "DIFFERENTIAL CLEAN" } else { "DIFFERENTIAL FAILED" }+ );+ Ok(fails.is_empty())+}++/// The larger of the two ends' snap movements, in metres.+fn snap_shift_m(b: Option<&Vec<String>>, c: Option<&Vec<String>>) -> f64 {+ let point = |t: &Vec<String>, key: &str| -> Option<(f64, f64)> {+ let v = t.iter().find_map(|s| s.strip_prefix(key)?.strip_prefix('='))?;+ let (a, b) = v.split_once(',')?;+ Some((a.parse().ok()?, b.parse().ok()?))+ };+ let (b, c) = match (b, c) {+ (Some(b), Some(c)) => (b, c),+ // No SNAP line means an older report; treat it as "unknown", which is+ // safer read as moved than as identical.+ _ => return f64::INFINITY,+ };+ let mut worst = 0.0f64;+ for key in ["s", "e"] {+ match (point(b, key), point(c, key)) {+ (Some(p), Some(q)) => worst = worst.max(crow_m(p.0, p.1, q.0, q.1)),+ _ => return f64::INFINITY,+ }+ }+ worst+}++/// Collect `KIND <id> rest...` lines into id -> tokens.+fn index_by_key(text: &str, kind: &str) -> HashMap<String, Vec<String>> {+ let mut out = HashMap::new();+ for line in text.lines() {+ let mut it = line.split_whitespace();+ if it.next() != Some(kind) {+ continue;+ }+ if let Some(id) = it.next() {+ let _ = out.insert(id.to_string(), it.map(str::to_string).collect());+ }+ }+ out+}++/// `STEP <pair> <k> ...` grouped by pair, in file order.+fn index_steps(text: &str) -> HashMap<String, Vec<String>> {+ let mut out: HashMap<String, Vec<String>> = HashMap::new();+ for line in text.lines() {+ let mut it = line.split_whitespace();+ if it.next() != Some("STEP") {+ continue;+ }+ if let Some(id) = it.next() {+ out.entry(id.to_string()).or_default().push(line.to_string());+ }+ }+ out+}++fn kv(tokens: &[String], key: &str) -> Option<u64> {+ tokens+ .iter()+ .find_map(|t| t.strip_prefix(key).and_then(|r| r.strip_prefix('=')))+ .and_then(|v| v.parse().ok())+}++/// The roads a route actually travels, in order, with repeats folded together.+///+/// Deliberately not the raw step list. Steps are split on bearing change, and two+/// graphs of one region split them differently for reasons that are not route+/// changes: an uncompacted graph's reconstruction emits a spurious zero-length+/// U-turn step where the route doubles back to a node, and a compacted one does+/// not. The sequence of named roads is what a driver would recognise, and it is+/// invariant to that.+fn road_seq(lines: &Vec<String>) -> Vec<String> {+ let mut out: Vec<String> = Vec::new();+ for l in lines {+ // Zero-length steps are reconstruction artefacts, not roads.+ if kv(&l.split_whitespace().map(str::to_string).collect::<Vec<_>>(), "dist_mm")+ == Some(0)+ {+ continue;+ }+ let name = match l.find(" name=") {+ Some(i) => l[i + 6..].to_string(),+ None => String::new(),+ };+ if out.last() != Some(&name) {+ out.push(name);+ }+ }+ out+}++/// A polyline's points, with consecutive repeats folded together.+///+/// Repeats are artefacts, not shape: a route that doubles back to a node emits it+/// twice, and the reconstruction's start and end stubs repeat their joint vertex.+fn polyline_points(tokens: Option<&Vec<String>>) -> Vec<(i64, i64)> {+ let tokens = match tokens {+ Some(t) => t,+ None => return Vec::new(),+ };+ let mut pts: Vec<(i64, i64)> = Vec::with_capacity(tokens.len());+ for t in tokens {+ if let Some((a, b)) = t.split_once(',') {+ if let (Ok(lat), Ok(lon)) = (a.parse::<f64>(), b.parse::<f64>()) {+ let p = ((lat * 1e7).round() as i64, (lon * 1e7).round() as i64);+ if pts.last() != Some(&p) {+ pts.push(p);+ }+ }+ }+ }+ pts+}++/// Whether two polylines trace the same path, allowing one to be a finer+/// subdivision of the other.+///+/// The geometry encoder inserts collinear points wherever a gap exceeds the `i16`+/// delta range, so a compacted graph's polyline legitimately carries vertices an+/// uncompacted one never needed. Those extra points lie *between* the originals,+/// so the coarser polyline must appear in the finer one as an in-order+/// subsequence — which is an exact test, unlike trying to detect and drop the+/// inserted points, since collinearity is not stable under subdivision (adding a+/// point between A and P changes P's neighbours, and so changes whether P looks+/// collinear).+fn same_path(a: &[(i64, i64)], b: &[(i64, i64)]) -> bool {+ if a == b {+ return true;+ }+ is_subsequence(a, b) || is_subsequence(b, a)+}++fn is_subsequence(needle: &[(i64, i64)], haystack: &[(i64, i64)]) -> bool {+ if needle.len() > haystack.len() {+ return false;+ }+ let mut it = haystack.iter();+ needle.iter().all(|p| it.any(|q| q == p))+}++fn first_mismatch(a: &[String], b: &[String]) -> Option<usize> {+ (0..a.len().max(b.len())).find(|&i| a.get(i) != b.get(i))+}++// ---------------------------------------------------------------------------+// geometry+// ---------------------------------------------------------------------------++/// Check directly that a rebuild describes the same roads, independent of+/// routing.+///+/// This is sharper than the route differential, and it has to be: collapsing+/// nodes changes how far `find_nearest_edge`'s fixed 800-node window reaches, so+/// two graphs of one region legitimately snap to different edges and produce+/// different routes. What must not change is the road network itself.+///+/// Two invariants are checked, both chosen to be insensitive to how the geometry+/// is *divided* into points, because the encoder inserts collinear points+/// wherever a gap exceeds the `i16` delta range:+///+/// * **No vertex is lost.** Every point in the baseline's geometry must still+/// appear in the candidate's. Interpolation only ever adds points, so the+/// candidate's vertex set must be a superset. A collapsed node whose+/// coordinate vanished would mean a corner had been cut.+/// * **Total length is preserved.** Summed over every hop of every edge.+/// Subdividing a straight hop does not change its length beyond the+/// sub-centimetre rounding of the inserted points.+fn geometry(args: &[String]) -> Result<bool, String> {+ let base_dir = need(args, "--baseline")?;+ let cand_dir = need(args, "--candidate")?;+ let base = load(&base_dir)?;+ let cand = load(&cand_dir)?;++ let b = scan_geometry(&base);+ println!(+ "baseline nodes={:<10} edges={:<10} hops={:<10} vertices={:<10} length={} mm",+ base.node_count,+ base.edge_count,+ b.hops,+ b.vertices.len(),+ b.length_mm+ );+ let c = scan_geometry(&cand);+ println!(+ "candidate nodes={:<10} edges={:<10} hops={:<10} vertices={:<10} length={} mm",+ cand.node_count,+ cand.edge_count,+ c.hops,+ c.vertices.len(),+ c.length_mm+ );+ println!(+ "candidate stored geometry on {} edge(s), {} of them by reference to a twin",+ c.with_geometry, c.reversed+ );+ print!("candidate points per edge (log2 buckets):");+ for (i, n) in c.pt_hist.iter().enumerate() {+ if *n > 0 {+ print!(" 2^{i}={n}");+ }+ }+ println!();++ let missing: Vec<&(i32, i32)> = b.vertices.difference(&c.vertices).collect();+ let mut ok = true;+ if missing.is_empty() {+ println!("PASS every baseline vertex survives in the candidate");+ } else {+ ok = false;+ println!(+ "FAIL {} of {} baseline vertices are missing from the candidate",+ missing.len(),+ b.vertices.len()+ );+ for v in missing.iter().take(10) {+ println!(" {:.7},{:.7}", f64::from(v.0) * 1e-7, f64::from(v.1) * 1e-7);+ }+ }++ // A tenth of a percent covers the reconnection edges, which legitimately+ // pick different anchors once the node set changes, plus integer rounding on+ // interpolated points.+ let delta = c.length_mm as i128 - b.length_mm as i128;+ let tol = (b.length_mm / 1000).max(1_000_000) as i128;+ if delta.abs() <= tol {+ println!(+ "PASS total road length within tolerance (delta {delta} mm of {} mm, tol {tol})",+ b.length_mm+ );+ } else {+ ok = false;+ println!("FAIL total road length moved by {delta} mm (tol {tol})");+ }+ println!("{}", if ok { "GEOMETRY PRESERVED" } else { "GEOMETRY CHANGED" });+ Ok(ok)+}++struct GeomScan {+ hops: u64,+ length_mm: u128,+ vertices: HashSet<(i32, i32)>,+ with_geometry: u64,+ reversed: u64,+ pt_hist: [u64; 9],+}++/// Walk every edge and collect the geometry the device would draw: the stored+/// polyline where there is one, the straight chord otherwise.+fn scan_geometry(g: &Graph) -> GeomScan {+ let mut coords = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];+ let mut out = GeomScan {+ hops: 0,+ length_mm: 0,+ vertices: HashSet::new(),+ with_geometry: 0,+ reversed: 0,+ pt_hist: [0u64; 9],+ };+ let mut pts: Vec<LatLon> = Vec::with_capacity(256);++ 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);+ if e.target >= g.node_count {+ continue;+ }+ pts.clear();+ match g.get_edge_coordinates(j, &mut coords) {+ Some((count, is_reversed)) if count >= 2 => {+ out.with_geometry += 1;+ if is_reversed {+ out.reversed += 1;+ }+ pts.extend((0..count).map(|p| get_pt_at(&coords, count, is_reversed, p)));+ }+ _ => {+ let node_v = g.node(e.target);+ pts.push(LatLon { lat_e7: node_u.lat_e7, lon_e7: node_u.lon_e7 });+ pts.push(LatLon { lat_e7: node_v.lat_e7, lon_e7: node_v.lon_e7 });+ }+ }+ let bucket = (pts.len() as f64).log2() as usize;+ out.pt_hist[bucket.min(8)] += 1;+ for p in &pts {+ let _ = out.vertices.insert((p.lat_e7, p.lon_e7));+ }+ for w in pts.windows(2) {+ if (w[0].lat_e7, w[0].lon_e7) == (w[1].lat_e7, w[1].lon_e7) {+ continue;+ }+ out.hops += 1;+ out.length_mm += u128::from(accurate_dist_mm(+ w[0].lat_e7, w[0].lon_e7, w[1].lat_e7, w[1].lon_e7,+ ));+ }+ }+ }+ out+}++/// The other direction of the same road: the first edge from `target` back to+/// `source`. Mirrors `graph.rs`'s reverse-geometry lookup and `routing.rs`'s+/// `twin_edge`, so the tool and the engine agree on what "the twin" means.+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)+}++/// Approximate ground distance in metres (equirectangular). Only used to report+/// how far a snap moved, so an approximation is fine.+fn crow_m(lat1: f64, lon1: f64, lat2: f64, lon2: f64) -> f64 {+ let dlat = (lat2 - lat1) * 111_320.0;+ let dlon = (lon2 - lon1) * 111_320.0 * ((lat1 + lat2) * 0.5).to_radians().cos();+ (dlat * dlat + dlon * dlon).sqrt()+}++fn write_file(path: &str, bytes: &[u8]) -> Result<(), String> {+ let mut f = std::fs::File::create(path).map_err(|e| format!("{path}: {e}"))?;+ f.write_all(bytes).map_err(|e| format!("{path}: {e}"))+}
maps/src/main/rust/src/geometry.rs
diff --git a/maps/src/main/rust/src/geometry.rs b/maps/src/main/rust/src/geometry.rsindex 6ffa4098c3..e27a4f472f 100644--- a/maps/src/main/rust/src/geometry.rs+++ b/maps/src/main/rust/src/geometry.rs@@ -7,15 +7,31 @@ use std::collections::HashMap; use crate::graph::{- Graph, DEG_TO_RAD, DRIVING, INVALID_EDGE, LIVING_STREET, MAX_DRIVING_KMH, MOTORWAY, STEPS,+ Graph, DEG_TO_RAD, DRIVING, INVALID_EDGE, LIVING_STREET, MAX_DRIVING_KMH, MOTORWAY,+ REVERSE_GEOMETRY_FLAG, STEPS, }; /// Live traffic snapshot: global edge id -> speed (km/h). 0 means "unknown". pub type TrafficSpeeds = HashMap<u64, u8>; +/// Bits of an `Edge::type_` byte that carry the OSM road class. The high bits+/// are flags — [`REVERSE_GEOMETRY_FLAG`] today — so every consumer that treats+/// `type_` as a road class MUST mask them off first.+///+/// This mask used to be `0x7F`, which stripped only bit 7 and let+/// `REVERSE_GEOMETRY_FLAG` through into the range checks below. A flagged edge+/// then landed at 65..79, outside both permitted ranges, so it was rejected for+/// every mode — silently deleting it from snapping (`routing.rs`+/// `find_nearest_edge`), from A* relaxation (`perform_search_loop`) and from+/// junction lane inference. Since the generator sets the flag on one edge of+/// every bidirectional collapsed chain, that would have removed half the road+/// network. `get_edge_time_10ms` below was already immune only by accident: its+/// `& 0xF` discards bit 6 as well.+pub const ROAD_TYPE_MASK: u8 = !(REVERSE_GEOMETRY_FLAG | 0x80);+ #[inline] pub fn is_mode_allowed(road_type: u8, mode: i32) -> bool {- let ty = road_type & 0x7F;+ let ty = road_type & ROAD_TYPE_MASK; if mode == DRIVING { return (MOTORWAY..=LIVING_STREET).contains(&ty); }@@ -97,7 +113,8 @@ pub fn get_edge_time_10ms( return (dist_mm as f64 / (speed_m_s * 10.0)) as u32; } }- let multiplier = g.edge_time_multipliers[(mode & 0x3) as usize][((type_ & 0x7F) & 0xF) as usize];+ let multiplier =+ g.edge_time_multipliers[(mode & 0x3) as usize][((type_ & ROAD_TYPE_MASK) & 0xF) as usize]; ((dist_mm as u64 * multiplier) >> 32) as u32 } @@ -191,3 +208,44 @@ pub fn get_projection( dist_mm: fast_dist_mm(g, px, py, proj_lat, proj_lon), } }++#[cfg(test)]+mod tests {+ use super::*;+ use crate::graph::{BICYCLE, PUBLIC_TRANSIT, REVERSE_GEOMETRY_FLAG, WALK};++ /// The generator sets `REVERSE_GEOMETRY_FLAG` on one edge of every+ /// bidirectional collapsed chain, so permission checks must ignore it. The+ /// mask here was `0x7F`, which stripped only bit 7: a flagged residential+ /// road arrived as 71 rather than 7, fell outside every permitted range, and+ /// was dropped from snapping, from A* relaxation and from junction lane+ /// inference. That silently removed half the road network.+ #[test]+ fn the_reverse_geometry_flag_does_not_change_permissions() {+ for ty in 1..=STEPS {+ for mode in [DRIVING, WALK, BICYCLE, PUBLIC_TRANSIT] {+ assert_eq!(+ is_mode_allowed(ty, mode),+ is_mode_allowed(ty | REVERSE_GEOMETRY_FLAG, mode),+ "type {ty} mode {mode} changed when flagged"+ );+ }+ }+ }++ #[test]+ fn driving_stops_at_living_street_but_walking_reaches_steps() {+ assert!(is_mode_allowed(MOTORWAY, DRIVING));+ assert!(is_mode_allowed(LIVING_STREET, DRIVING));+ assert!(!is_mode_allowed(LIVING_STREET + 1, DRIVING));+ assert!(!is_mode_allowed(STEPS, DRIVING));+ assert!(is_mode_allowed(STEPS, WALK));+ // Transit permits exactly what walking does: its road-graph use is the+ // walking legs of a journey.+ assert!(is_mode_allowed(STEPS, PUBLIC_TRANSIT));+ // Type 0 is "not a road" and is never permitted.+ assert!(!is_mode_allowed(0, DRIVING));+ assert!(!is_mode_allowed(0, WALK));+ assert!(!is_mode_allowed(REVERSE_GEOMETRY_FLAG, WALK));+ }+}
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 73ccec5b01..a9caaaf847 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -21,6 +21,13 @@ pub const MOTORWAY: u8 = 1; pub const LIVING_STREET: u8 = 9; pub const STEPS: u8 = 15; +/// Set in an [`Edge::type_`] byte to mean "this edge stores no geometry of its+/// own; decode its twin's and read it backwards".+///+/// `type_` is therefore a bitfield, not a plain road class:+/// `[bits 0-5 road class][bit 6 reverse geometry][bit 7 reserved]`. Anything+/// interpreting it as a road class must mask with+/// [`crate::geometry::ROAD_TYPE_MASK`] first. pub const REVERSE_GEOMETRY_FLAG: u8 = 0x40; // --- OSM turn:lanes indication bits (one u16 mask per lane) ---@@ -62,19 +69,54 @@ pub const DEG_TO_RAD: f64 = std::f64::consts::PI / 180.0; /// `edge_count`, so a pack directory holding files from two vintages reads /// garbage. The magic + version make that a clean rejection instead. pub const GRAPH_MAGIC: u32 = 0x4752_414D;-pub const GRAPH_VERSION: u32 = 1;+/// 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;++/// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table.+///+/// A per-edge blob is at most 1016 bytes (4 per interior point, capped at+/// `MAX_POINTS - 2` = 254 of them by [`Graph::decode_edge_coords`]), so a block+/// spans at most 32 x 1016 = 32,512 bytes and the within-block half fits a `u16`.+/// That bound is the invariant the whole layout rests on; the generator asserts+/// it. The table is indexed by an edge's rank in the presence bitmap, so every+/// entry in a block describes a real blob.+pub const INTERMEDIATE_BLOCK: u64 = 32;++/// Bytes of presence bitmap one entry of `intermediate.bin`'s rank index covers.+/// 64 bytes is 512 edges and one cache line, so a rank costs one `u64` load plus+/// at most eight `popcount`s. `RANK_BLOCK_BYTES` in the generator, and the two+/// must agree.+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. +/// A `nodes.bin` record: 12 bytes, with `edge_ptr` narrowed to a `u32`.+///+/// Planet has 1.07 G directed edges, which leaves 4x headroom, and the four bytes+/// saved per node are 1.7 GB. [`Graph::node`] widens it into [`NodeMaster`], so+/// nothing above this file sees the narrower field. #[repr(C, packed)] #[derive(Clone, Copy)]-pub struct NodeMaster {- pub lat_e7: i32,- pub lon_e7: i32,- pub edge_ptr: u64,+struct NodeRec {+ lat_e7: i32,+ lon_e7: i32,+ edge_ptr: u32,+}++/// One `lanes.bin` index entry: the edge that carries lanes, and where its masks+/// start in the blob.+#[repr(C, packed)]+#[derive(Clone, Copy)]+struct LaneEntry {+ edge_idx: u32,+ blob_off: u32, } #[repr(C, packed)]@@ -87,6 +129,15 @@ pub struct Edge { pub speed_limit: u8, } +/// The in-memory view of a `nodes.bin` record, with `edge_ptr` widened back to a+/// `u64` so nothing above [`Graph::node`] cares that the file stores 32 bits.+#[derive(Clone, Copy)]+pub struct NodeMaster {+ pub lat_e7: i32,+ pub lon_e7: i32,+ pub edge_ptr: u64,+}+ #[derive(Clone, Copy)] pub struct LatLon { pub lat_e7: i32,@@ -172,7 +223,7 @@ pub struct Graph { // mmap regions kept alive for the lifetime of the graph. _nodes_region: MmapRegion, _edges_region: MmapRegion,- _intermediate_region: Option<MmapRegion>,+ _intermediate_region: MmapRegion, _road_names_region: Option<MmapRegion>, _lanes_region: Option<MmapRegion>, @@ -181,16 +232,22 @@ pub struct Graph { edges: *const u8, pub edge_count: u64, - intermediate_edge_offsets: *const u8, // u64[edge_count + 1] byte offsets- intermediate_data: *const u8, // delta-encoded coordinate bytes- has_intermediate: bool,-- // Real OSM turn-lane data, indexed by edge (see `edge_lane_masks`). Optional:- // absent until the graph is regenerated with lane extraction, in which case- // routing falls back to topology-inferred lanes.- lane_edge_offsets: *const u8, // u64[edge_count + 1] byte offsets into lane_data- lane_data: *const u8, // packed u16 per-lane masks- has_lanes: bool,+ // `intermediate.bin`, blob first and every table in a trailer. `off(g) =+ // coarse[g / INTERMEDIATE_BLOCK] + within[g]` for the g-th *geometry* edge,+ // where g is the edge's rank in `present`.+ intermediate_data: *const u8, // delta-encoded coordinate bytes, at offset 0+ intermediate_rank: *const u8, // u64[E.div_ceil(512) + 1]+ intermediate_present: *const u8, // u8[E.div_ceil(8)], one bit per directed edge+ intermediate_coarse: *const u8, // u64[G.div_ceil(BLOCK) + 1]+ intermediate_within: *const u8, // u16[G + 1]++ // Real OSM turn-lane data (see `edge_lane_masks`). Sparse: only the edges that+ // actually carry `turn:lanes` appear, which on a planet is 2.9 M of 1.07 G.+ // Optional as a whole too — absent until the graph is regenerated with lane+ // extraction, in which case routing falls back to topology-inferred lanes.+ lane_index: *const u8, // LaneEntry[lane_edges + 1], ascending by edge_idx+ lane_edges: u32,+ lane_data: *const u8, // packed u16 per-lane masks road_names: *const u8, pub road_names_size: usize,@@ -206,9 +263,16 @@ unsafe impl Sync for Graph {} impl Graph { /// Load the graph from `base` (a directory path, trailing slash optional).- /// Returns `None` if the mandatory nodes/edges/metadata files are 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).+ /// 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).+ ///+ /// `intermediate.bin` is mandatory, not optional. The generator collapses+ /// degree-2 chains, so an edge is a whole road between junctions and its+ /// polyline is the only record of the road's shape. Without the file,+ /// `find_nearest_edge` would project onto a straight chord spanning an entire+ /// street: snapping and drawn geometry would both be wrong, not merely+ /// coarse. Refusing to load says so instead of routing badly. pub fn load(base: &str) -> Option<Graph> { let mut base = base.to_string(); if !base.is_empty() && !base.ends_with('/') {@@ -234,21 +298,64 @@ impl Graph { let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?; let edge_count = (edges_region.len / std::mem::size_of::<Edge>()) as u64; - // intermediate.bin: [ u64 edge_offsets[edge_count + 1] ][ coord blob ].- // Length-validated: the offset array is sized from `edge_count`, so a- // stale file from a different graph vintage would be read out of bounds.- let offsets_bytes = (edge_count + 1) * std::mem::size_of::<u64>() as u64;- let intermediate_region = MmapRegion::map(&format!("{base}intermediate.bin"))- .filter(|r| r.len as u64 >= offsets_bytes);- let (intermediate_edge_offsets, intermediate_data, has_intermediate) =- match &intermediate_region {- Some(r) => {- let offsets = r.base();- let data = unsafe { r.base().add(offsets_bytes as usize) };- (offsets, data, true)- }- None => (ptr::null(), ptr::null(), false),- };+ // intermediate.bin:+ // [ blob ][ u64 rank[..] ][ u8 present[..] ][ u64 coarse[..] ]+ // [ u16 within[..] ][ u64 G ]+ // Everything is recoverable from the last 8 bytes plus `edge_count`: the+ // tables are sized from `G` and from `E`, and the blob is whatever is left+ // over at offset 0. Validated on both axes, because a stale file from a+ // different graph vintage would otherwise be read out of bounds.+ let intermediate_region = MmapRegion::map(&format!("{base}intermediate.bin"))?;+ let inter_len = intermediate_region.len as u64;+ if inter_len < 8 {+ return None;+ }+ let geometry_edges =+ unsafe { read_at::<u64>(intermediate_region.base().add((inter_len - 8) as usize), 0) };+ // `G` can never exceed the number of directed edges. Checking it before+ // anything is sized from it is also what stops a garbage trailer from+ // overflowing the table arithmetic below into a plausible-looking total.+ if geometry_edges > edge_count {+ return None;+ }+ let rank_bytes = (edge_count.div_ceil(GEOMETRY_RANK_BLOCK_BYTES * 8) + 1)+ * std::mem::size_of::<u64>() as u64;+ let present_bytes = edge_count.div_ceil(8);+ let coarse_bytes = (geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1)+ * std::mem::size_of::<u64>() as u64;+ let within_bytes = (geometry_edges + 1) * std::mem::size_of::<u16>() as u64;+ let trailer = rank_bytes + present_bytes + coarse_bytes + within_bytes + 8;+ if inter_len < trailer {+ return None;+ }+ let blob_bytes = inter_len - trailer;+ let intermediate_data = intermediate_region.base();+ let intermediate_rank = unsafe { intermediate_data.add(blob_bytes as usize) };+ let intermediate_present = unsafe { intermediate_rank.add(rank_bytes as usize) };+ let intermediate_coarse = unsafe { intermediate_present.add(present_bytes as usize) };+ let intermediate_within = unsafe { intermediate_coarse.add(coarse_bytes as usize) };+ // The two halves of the trailer have to agree with each other and with the+ // blob: the sentinel offset is the blob's length, and the rank total is+ // `G`. Both are cheap, and between them they catch a truncated file, a+ // mismatched vintage and a generator that lost count.+ let sentinel = unsafe {+ read_at::<u64>(+ intermediate_coarse,+ (geometry_edges / INTERMEDIATE_BLOCK) as usize,+ ) + u64::from(read_at::<u16>(intermediate_within, geometry_edges as usize))+ };+ if sentinel != blob_bytes {+ return None;+ }+ let rank_total = unsafe {+ read_at::<u64>(+ intermediate_rank,+ (edge_count.div_ceil(GEOMETRY_RANK_BLOCK_BYTES * 8)) as usize,+ )+ };+ if rank_total != geometry_edges {+ return None;+ } let road_names_region = MmapRegion::map(&format!("{base}road_names.bin")); let (road_names, road_names_size) = match &road_names_region {@@ -256,18 +363,41 @@ impl Graph { None => (ptr::null(), 0), }; - // lanes.bin: [ u64 edge_offsets[edge_count + 1] ][ u16 lane-mask blob ].- // Optional and validated: a truncated/mismatched file disables real- // lanes so routing falls back to topology inference.+ // lanes.bin: [ u32 n ][ LaneEntry[n + 1] ][ u16 lane-mask blob ]. The index+ // is sized by its own header rather than by `edge_count`, so it is validated+ // against that; a truncated/mismatched file disables real lanes so routing+ // falls back to topology inference. let lanes_region = MmapRegion::map(&format!("{base}lanes.bin"));- let (lane_edge_offsets, lane_data, has_lanes) = match &lanes_region {- Some(r) if r.len as u64 >= offsets_bytes => {- let offsets = r.base();- let data = unsafe { r.base().add(offsets_bytes as usize) };- (offsets, data, true)+ let lanes = lanes_region.as_ref().and_then(|r| {+ if r.len < 4 {+ return None; }- _ => (ptr::null(), ptr::null(), false),- };+ let n = unsafe { read_at::<u32>(r.base(), 0) };+ let index = unsafe { r.base().add(4) };+ let index_bytes = 4 + (u64::from(n) + 1) * std::mem::size_of::<LaneEntry>() as u64;+ if (r.len as u64) < index_bytes {+ return None;+ }+ // 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.+ let sentinel = unsafe { read_at::<LaneEntry>(index, n as usize) };+ 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+ // `lanes.bin` whose own header is self-consistent would otherwise load+ // and attribute masks to the wrong edges. Entries ascend, so bounding+ // the last one bounds them all.+ if n > 0 {+ let last = unsafe { read_at::<LaneEntry>(index, n as usize - 1) };+ if u64::from(last.edge_idx) >= edge_count {+ return None;+ }+ }+ Some((index, n, unsafe { r.base().add(index_bytes as usize) }))+ });+ let (lane_index, lane_edges, lane_data) = lanes.unwrap_or((ptr::null(), 0, ptr::null())); let nodes = nodes_region.base(); let edges = edges_region.base();@@ -326,12 +456,14 @@ impl Graph { node_count, edges, edge_count,- intermediate_edge_offsets, intermediate_data,- has_intermediate,- lane_edge_offsets,+ intermediate_rank,+ intermediate_present,+ intermediate_coarse,+ intermediate_within,+ lane_index,+ lane_edges, lane_data,- has_lanes, road_names, road_names_size, lon_to_mm_scale,@@ -345,7 +477,12 @@ impl Graph { #[inline] pub fn node(&self, id: u32) -> NodeMaster { // Callers guarantee id <= node_count (sentinel index is valid).- unsafe { read_at::<NodeMaster>(self.nodes, id as usize) }+ let r = unsafe { read_at::<NodeRec>(self.nodes, id as usize) };+ NodeMaster {+ lat_e7: r.lat_e7,+ lon_e7: r.lon_e7,+ edge_ptr: u64::from(r.edge_ptr),+ } } /// Safe node fetch: returns a zeroed node for out-of-range ids, mirroring@@ -371,19 +508,38 @@ impl Graph { /// left→right. Each `u16` is a set of `LANE_*` bits. Returns `None` when the /// graph has no lane data or this edge carries none (callers then fall back /// to topology-inferred lanes).+ ///+ /// The index is sparse, so "this edge has no lanes" is spelled as absence from+ /// it and found by binary search. `turn:lanes` is rare — 2.9 M of a planet's+ /// 1.07 G edges — and this is called once per maneuver rather than per edge,+ /// so ~22 probes buys back 8.6 GB of dense offset table. pub fn edge_lane_masks(&self, idx: u64) -> Option<Vec<u16>> {- if !self.has_lanes || idx >= self.edge_count {+ if self.lane_index.is_null() || idx >= self.edge_count { return None; }- let start = unsafe { read_at::<u64>(self.lane_edge_offsets, idx as usize) };- let end = unsafe { read_at::<u64>(self.lane_edge_offsets, idx as usize + 1) };- if end <= start {+ let want = u32::try_from(idx).ok()?;+ let entry = |i: u32| unsafe { read_at::<LaneEntry>(self.lane_index, i as usize) };+ // Lower bound over the real entries; the trailing sentinel is only ever+ // read for its offset, which is how the last edge gets a length.+ let mut lo = 0u32;+ let mut hi = self.lane_edges;+ while lo < hi {+ let mid = lo + (hi - lo) / 2;+ if entry(mid).edge_idx < want {+ lo = mid + 1;+ } else {+ hi = mid;+ }+ }+ if lo >= self.lane_edges || entry(lo).edge_idx != want { return None; }- let count = ((end - start) / std::mem::size_of::<u16>() as u64) as usize;- if count == 0 {+ let start = entry(lo).blob_off;+ let end = entry(lo + 1).blob_off;+ if end <= start { return None; }+ let count = ((end - start) as usize) / std::mem::size_of::<u16>(); let mut out = Vec::with_capacity(count); for k in 0..count { let byte_off = start as usize + k * std::mem::size_of::<u16>();@@ -393,9 +549,59 @@ impl Graph { Some(out) } + /// True when edge `idx` stores a polyline of its own.+ ///+ /// 70.4% of a planet's directed edges do not: their polyline is either their+ /// twin's (see [`REVERSE_GEOMETRY_FLAG`]) or nothing but the chord between+ /// their endpoints, which needs no bytes to say.+ #[inline]+ fn stores_geometry(&self, idx: u64) -> bool {+ let byte = unsafe { read_at::<u8>(self.intermediate_present, (idx / 8) as usize) };+ byte & (1u8 << (idx % 8)) != 0+ }++ /// How many edges below `idx` store a polyline, i.e. the offset-table index of+ /// edge `idx` itself when its own bit is set.+ ///+ /// One `u64` load for the block, then at most 64 bytes of `popcount`. Only ever+ /// meaningful for an edge whose bit *is* set, so callers must test+ /// [`Graph::stores_geometry`] first or they will read another edge's blob.+ #[inline]+ fn geometry_rank(&self, idx: u64) -> u64 {+ let byte = idx / 8;+ let block = byte / GEOMETRY_RANK_BLOCK_BYTES;+ let mut n = unsafe { read_at::<u64>(self.intermediate_rank, block as usize) };+ for b in block * GEOMETRY_RANK_BLOCK_BYTES..byte {+ n += u64::from(unsafe { read_at::<u8>(self.intermediate_present, b as usize) }.count_ones());+ }+ let partial = unsafe { read_at::<u8>(self.intermediate_present, byte as usize) };+ n + u64::from((partial & ((1u8 << (idx % 8)) - 1)).count_ones())+ }++ /// Byte offset of the `g`-th geometry edge's polyline in the intermediate blob.+ ///+ /// Two loads instead of one: a `u64` per [`INTERMEDIATE_BLOCK`] geometry edges+ /// plus a `u16` each. Same cost profile, and 1.5 GB smaller at planet scale+ /// than one `u64` apiece. #[inline]- fn intermediate_offset(&self, idx: u64) -> u64 {- unsafe { read_at::<u64>(self.intermediate_edge_offsets, idx as usize) }+ fn geometry_offset(&self, g: u64) -> u64 {+ let coarse =+ unsafe { read_at::<u64>(self.intermediate_coarse, (g / INTERMEDIATE_BLOCK) as usize) };+ let within = unsafe { read_at::<u16>(self.intermediate_within, g as usize) };+ coarse + u64::from(within)+ }++ /// `(byte offset, length)` of edge `idx`'s stored polyline, or `None` when it+ /// stores none.+ #[inline]+ fn intermediate_range(&self, idx: u64) -> Option<(u64, u32)> {+ if !self.stores_geometry(idx) {+ return None;+ }+ let g = self.geometry_rank(idx);+ let start = self.geometry_offset(g);+ let end = self.geometry_offset(g + 1);+ Some((start, (end - start) as u32)) } /// Borrow a NUL-terminated road/feed/stop name from the string pool at@@ -457,59 +663,84 @@ impl Graph { } /// Decode the delta-encoded coordinate blob for `edge_idx` into `out`.- /// Returns `Some((count, is_reversed))` when geometry is available,- /// mirroring `get_edge_coordinates`. `out` must hold at least 256 points.+ /// 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.+ ///+ /// `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.+ pub fn get_edge_coordinates_from(+ &self,+ source: u32,+ edge_idx: u64,+ out: &mut [LatLon],+ ) -> Option<(u32, bool)> { if self.edges.is_null() || edge_idx >= self.edge_count { return None; } let e = self.edge(edge_idx);+ if source >= self.node_count || e.target >= self.node_count {+ return None;+ } if e.type_ & REVERSE_GEOMETRY_FLAG != 0 {- let u_global = self.find_node_idx_for_edge(edge_idx);- let v_global = e.target;- if v_global < self.node_count && self.has_intermediate {- let s = self.node(v_global).edge_ptr;- let e_ptr = self.node(v_global + 1).edge_ptr; // sentinel valid- for k in s..e_ptr {- if self.edge(k).target == u_global {- let start_byte = self.intermediate_offset(k);- let end_byte = self.intermediate_offset(k + 1);- let cnt =- self.decode_edge_coords(start_byte, (end_byte - start_byte) as u32, out);- return Some((cnt, true));- }+ // 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+ for k in s..e_ptr {+ if self.edge(k).target == source {+ let cnt = self.decode_edge_coords(k, e.target, source, out);+ return Some((cnt, true)); } } None- } else if self.has_intermediate {- let start_byte = self.intermediate_offset(edge_idx);- let end_byte = self.intermediate_offset(edge_idx + 1);- let cnt = self.decode_edge_coords(start_byte, (end_byte - start_byte) as u32, out);- Some((cnt, false)) } else {- None+ let cnt = self.decode_edge_coords(edge_idx, source, e.target, out);+ Some((cnt, false)) } } - /// Delta-decode `byte_len` bytes at byte offset `data_off` in the- /// intermediate blob into `out`. Returns the number of decoded points.- fn decode_edge_coords(&self, data_off: u64, byte_len: u32, out: &mut [LatLon]) -> u32 {- if byte_len < 8 {+ /// Delta-decode edge `idx`'s polyline into `out`, seeded with node `source`'s+ /// coordinates and terminated with node `target`'s. Returns the number of+ /// decoded points, or 0 when the edge stores no polyline.+ ///+ /// The blob holds *only* the interior points, because the first and last are+ /// always the edge's own endpoints and `nodes.bin` already has both. Nothing+ /// here distinguishes an absent blob from an empty one; the presence bitmap+ /// does, in [`Graph::intermediate_range`].+ fn decode_edge_coords(&self, idx: u64, source: u32, target: u32, out: &mut [LatLon]) -> u32 {+ let Some((data_off, byte_len)) = self.intermediate_range(idx) else { return 0;- }- let data = unsafe { self.intermediate_data.add(data_off as usize) };- // First point is absolute (int32 lat_e7, int32 lon_e7).- let mut lat = unsafe { (data as *const i32).read_unaligned() };- let mut lon = unsafe { (data.add(4) as *const i32).read_unaligned() };+ };+ let a = self.node(source);+ let mut lat = a.lat_e7;+ let mut lon = a.lon_e7; out[0] = LatLon { lat_e7: lat, lon_e7: lon, }; + let data = unsafe { self.intermediate_data.add(data_off as usize) }; let mut count: u32 = 1;- let mut off: u32 = 8;- while off + 4 <= byte_len && count < 256 {+ let mut off: u32 = 0;+ // One slot is reserved for the target, so the interior stops one short of+ // the 256 points every caller's buffer holds.+ while off + 4 <= byte_len && count + 1 < 256 { let d_lat = unsafe { (data.add(off as usize) as *const i16).read_unaligned() }; let d_lon = unsafe { (data.add(off as usize + 2) as *const i16).read_unaligned() }; lat = lat.wrapping_add(d_lat as i32);@@ -521,7 +752,13 @@ impl Graph { count += 1; off += 4; }- count++ let b = self.node(target);+ out[count as usize] = LatLon {+ lat_e7: b.lat_e7,+ lon_e7: b.lon_e7,+ };+ count + 1 } }
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 c5a31c8121..2c4111cd5a 100644--- a/maps/src/main/rust/src/lib.rs+++ b/maps/src/main/rust/src/lib.rs@@ -7,11 +7,15 @@ //! traffic speeds and the per-square segment cache live in their own locks, //! mirroring the C++ globals but made explicit. -mod geometry;-mod graph;+// `graph`, `geometry`, `routing` and `state` are `pub` so the host-side+// route differential (`examples/route_diff.rs`) can drive the real engine+// instead of reimplementing it. Nothing outside this crate links the cdylib,+// so the wider surface costs nothing on device.+pub mod geometry;+pub mod graph; mod mvt;-mod routing;-mod state;+pub mod routing;+pub mod state; mod transit; use std::collections::{BTreeMap, HashMap};@@ -190,7 +194,9 @@ pub extern "system" fn Java_com_vayunmathur_maps_util_OfflineRouter_findRouteNat ctx }; - if ctx.target_node == 0xFFFF_FFFF {+ // A route that never leaves the edge it snapped to reaches no node, so+ // `target_node` stays unset; `ctx.direct` is the route in that case.+ if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() { return null; } @@ -363,7 +369,7 @@ fn snap_walk_legs(legs: &mut [transit::TransitLeg]) { None => continue, }; perform_search_loop(&g, &speeds, &mut no_traffic, WALK, &mut ctx, scratch, heap);- if ctx.target_node == 0xFFFF_FFFF {+ if ctx.target_node == 0xFFFF_FFFF && ctx.direct.is_none() { continue; }
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 e6f58640b8..bf3b45c03b 100644--- a/maps/src/main/rust/src/routing.rs+++ b/maps/src/main/rust/src/routing.rs@@ -47,6 +47,37 @@ pub struct RoutingContext { pub end: SnappedEdge, pub target_node: u32, pub iterations: i32,+ /// A route that stays on the edge it started on, when both ends snapped to+ /// the same road. See [`direct_path`].+ pub direct: Option<Direct>,+}++/// A route from the start projection to the end projection that never leaves the+/// edge they both snapped to.+///+/// Without this, a trip along one road is forced out to a junction and back,+/// because the A* search can only start and finish at nodes: it is seeded at the+/// start edge's two endpoints and stops at one of the end edge's two endpoints,+/// and on a single edge those are the *same* two nodes. The search therefore+/// "succeeds" immediately at a shared endpoint and the reconstruction walks from+/// the start projection back to that endpoint and forward again.+///+/// Uncompacted, an edge was one pair of adjacent OSM vertices — a few metres —+/// so the detour was invisible. Once degree-2 chains collapse, an edge is a whole+/// road between junctions, and a 20 m walk became a 2 km round trip. Measured on+/// the SLO fixture, 63 of 80 short probes were affected, the worst going from 0 m+/// to 2 km.+pub struct Direct {+ /// Start projection to end projection along the road, inclusive.+ pub coords: Vec<LatLon>,+ pub dist_mm: u32,+ pub time_10ms: u32,+ pub name_offset: u32,+ /// Road class with any flag bits already masked off.+ pub type_: u8,+ pub speed_limit: u8,+ /// The directed edge actually travelled, for traffic lookup.+ pub edge_idx: u64, } /// One coalesced navigation step (pre-localization). Marshaled to Kotlin@@ -203,7 +234,7 @@ fn junction_lanes( } // Outgoing heading: junction -> first vertex leaving the junction.- let (nlat, nlon) = match g.get_edge_coordinates(k, &mut coords) {+ let (nlat, nlon) = match g.get_edge_coordinates_from(junction, k, &mut coords) { Some((count, is_rev)) if count >= 2 => { let p1 = get_pt_at(&coords, count, is_rev, 1); (p1.lat_e7, p1.lon_e7)@@ -292,7 +323,8 @@ pub fn find_nearest_edge(g: &Graph, lat: f64, lon: f64, mode: i32) -> SnappedEdg continue; } - if let Some((count, is_reversed)) = g.get_edge_coordinates(j, &mut coords) {+ if let Some((count, is_reversed)) = g.get_edge_coordinates_from(u_global, j, &mut coords)+ { if count >= 2 { let num_pts = count; let mut current_dist_from_start_mm: u32 = 0;@@ -394,11 +426,160 @@ pub fn prepare_routing( push(start.node_a, start.dist_a_mm, scratch, heap); push(start.node_b, start.dist_b_mm, scratch, heap); + let direct = direct_path(g, traffic, &start, &end, mode);+ Some(RoutingContext { start, end, target_node: 0xFFFF_FFFF, iterations: 0,+ direct,+ })+}++/// Polyline of `edge_idx` in source-to-target order, falling back to the straight+/// chord when the edge stores no geometry.+fn edge_polyline(g: &Graph, edge_idx: u64, source: u32, target: u32) -> Vec<LatLon> {+ let mut buf = [LatLon { lat_e7: 0, lon_e7: 0 }; 256];+ if let Some((count, is_reversed)) = g.get_edge_coordinates_from(source, edge_idx, &mut buf) {+ if count >= 2 {+ return (0..count).map(|p| get_pt_at(&buf, count, is_reversed, p)).collect();+ }+ }+ let a = g.get_node(source);+ let b = g.get_node(target);+ vec![+ LatLon { lat_e7: a.lat_e7, lon_e7: a.lon_e7 },+ LatLon { lat_e7: b.lat_e7, lon_e7: b.lon_e7 },+ ]+}++/// The other direction of the same road: the *only* edge from `target` back to+/// `source`, or `None` when there is none or more than one.+///+/// Uniqueness is required, not incidental. `graph.rs` resolves+/// [`REVERSE_GEOMETRY_FLAG`] by taking the first such edge, and the generator's+/// `twin_is_unique` refuses to set the flag unless exactly one exists — so+/// accepting the first match here would let a *parallel but different* road+/// between the same two junctions pass as the twin, and its name, type and speed+/// limit would then be attached to a polyline belonging to the other road. The+/// synthetic transit-stop connectors make that shape real: the graph fixture has+/// two edges from one node to another, a collapsed street and a one-way service+/// road.+///+/// A self-loop (an anchorless ring collapsed to one node) would otherwise match+/// itself and so claim that its own reverse direction exists.+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 mut found = None;+ for k in s..e {+ if g.edge(k).target == source {+ if found.is_some() {+ return None;+ }+ found = Some(k);+ }+ }+ found+}++/// Where a point sits along `poly`: `(segment index, distance from the start)`.+/// The point is expected to already lie on the polyline, so the nearest segment+/// is unambiguous.+fn locate_on(g: &Graph, poly: &[LatLon], lat_e7: i32, lon_e7: i32) -> (usize, u32) {+ let mut best = (0usize, 0u32);+ let mut best_off = u32::MAX;+ let mut acc: u32 = 0;+ for i in 0..poly.len() - 1 {+ let (a, b) = (poly[i], poly[i + 1]);+ let p = get_projection(g, lat_e7, lon_e7, a.lat_e7, a.lon_e7, b.lat_e7, b.lon_e7);+ if p.dist_mm < best_off {+ best_off = p.dist_mm;+ best = (i, acc.saturating_add(fast_dist_mm(g, a.lat_e7, a.lon_e7, p.lat_e7, p.lon_e7)));+ }+ acc = acc.saturating_add(fast_dist_mm(g, a.lat_e7, a.lon_e7, b.lat_e7, b.lon_e7));+ }+ best+}++/// The stretch of `poly` between two located points, endpoints included. Always+/// at least two points: when both project onto the same segment the result is+/// just the two projections, which for coincident ends is a valid zero-length+/// route.+fn sub_polyline(poly: &[LatLon], from: (usize, LatLon), to: (usize, LatLon)) -> Vec<LatLon> {+ let mut out = vec![from.1];+ for p in poly.iter().take(to.0 + 1).skip(from.0 + 1) {+ out.push(*p);+ }+ out.push(to.1);+ out+}++/// Build the on-edge route when both ends snapped to the same road, or `None`+/// when they did not or when travelling it in the required direction is not+/// allowed.+fn direct_path(+ g: &Graph,+ traffic: &TrafficSpeeds,+ start: &SnappedEdge,+ end: &SnappedEdge,+ mode: i32,+) -> Option<Direct> {+ if start.edge_idx == INVALID_EDGE || end.edge_idx == INVALID_EDGE {+ return None;+ }+ let twin = twin_edge(g, start.node_a, start.node_b);+ // Same directed edge, or the one unambiguous other direction of one road.+ // Anything else — including a second, parallel road between the same pair of+ // nodes — is left to the search, because its polyline is a different road.+ if end.edge_idx != start.edge_idx && Some(end.edge_idx) != twin {+ return None;+ }++ let poly = edge_polyline(g, start.edge_idx, start.node_a, start.node_b);+ if poly.len() < 2 {+ return None;+ }+ let s_pt = LatLon { lat_e7: start.proj_lat, lon_e7: start.proj_lon };+ let e_pt = LatLon { lat_e7: end.proj_lat, lon_e7: end.proj_lon };+ let s_at = locate_on(g, &poly, s_pt.lat_e7, s_pt.lon_e7);+ 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.+ let forward = s_at <= e_at;+ let edge_idx = if forward { start.edge_idx } else { twin? };+ let e = g.edge(edge_idx);+ if !is_mode_allowed(e.type_, mode) {+ return None;+ }++ let coords = if forward {+ sub_polyline(&poly, (s_at.0, s_pt), (e_at.0, e_pt))+ } else {+ let mut c = sub_polyline(&poly, (e_at.0, e_pt), (s_at.0, s_pt));+ c.reverse();+ c+ };++ let mut dist_mm: u32 = 0;+ for w in coords.windows(2) {+ dist_mm = dist_mm+ .saturating_add(fast_dist_mm(g, w[0].lat_e7, w[0].lon_e7, w[1].lat_e7, w[1].lon_e7));+ }+ let type_ = e.type_ & ROAD_TYPE_MASK;+ Some(Direct {+ 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,+ type_,+ speed_limit: e.speed_limit,+ edge_idx, }) } @@ -414,21 +595,50 @@ pub fn perform_search_loop( ) { // Cap is a safety net only. The 36M-node CA graph needs ~6.4M expansions for // the longest routes (SF->LA), so the old 1M cap aborted them ("no route").+ // Reaching one end of the destination's edge is not the same as arriving.+ // The search can only stop at nodes, so it stops at `end.node_a` or+ // `end.node_b` and `reconstruct_path` then walks the leftover stub to the+ // projection. Stopping at whichever anchor is reached *first* ignores how+ // long that stub is, and after compaction the two anchors are a whole road+ // apart rather than a few metres, so the wrong choice costs the length of+ // the street. Score both completions and keep the better one.+ let mut best_total = u32::MAX; while !heap.empty() && ctx.iterations < 25_000_000 { ctx.iterations += 1; let u = heap.pop(); - if u == ctx.end.node_a || u == ctx.end.node_b {- ctx.target_node = u;- break;- }- let u_cost = scratch.get_entry(u).g_fwd; if u >= g.node_count { continue; } let n_u = g.node(u); + // `f` is a lower bound on any route through `u`, and the heap pops in+ // non-decreasing `f` order, so once it cannot beat a completed route+ // nothing left can.+ let f_u = u_cost.saturating_add(heuristic_time_10ms(+ g, n_u.lat_e7, n_u.lon_e7, ctx.end.proj_lat, ctx.end.proj_lon, mode,+ ));+ if f_u >= best_total {+ break;+ }++ if u == ctx.end.node_a || u == ctx.end.node_b {+ let stub = if u == ctx.end.node_a {+ ctx.end.dist_a_mm+ } else {+ ctx.end.dist_b_mm+ };+ let total = u_cost.saturating_add(get_edge_time_10ms(+ g, traffic, INVALID_EDGE, stub, ctx.end.type_, ctx.end.speed_limit, mode,+ ));+ if total < best_total {+ best_total = total;+ ctx.target_node = u;+ }+ // Keep expanding: this anchor may also be on the way to the other.+ }+ if mode == DRIVING { ensure_traffic(n_u.lat_e7, n_u.lon_e7); }@@ -581,6 +791,62 @@ impl<'a> StepBuilder<'a> { } } +/// Total time of the searched route, including the stub from the last node to the+/// destination projection. [`u32::MAX`] when the search found nothing.+fn network_time_10ms(+ g: &Graph,+ traffic: &TrafficSpeeds,+ mode: i32,+ ctx: &RoutingContext,+ scratch: &mut RoutingScratchpad,+) -> u32 {+ if ctx.target_node == INVALID_NODE {+ return u32::MAX;+ }+ let reached = scratch.get_entry(ctx.target_node).g_fwd;+ // `g_fwd` stops at the node; the walk from there to the projection is the+ // part `reconstruct_path`'s end stub adds.+ let stub = if ctx.target_node == ctx.end.node_a {+ ctx.end.dist_a_mm+ } else {+ ctx.end.dist_b_mm+ };+ let stub_time = get_edge_time_10ms(+ g, traffic, INVALID_EDGE, stub, ctx.end.type_, ctx.end.speed_limit, mode,+ );+ reached.saturating_add(stub_time)+}++/// Turn a [`Direct`] route into steps, reusing the same coalescing the searched+/// path gets so the two are indistinguishable downstream.+fn direct_steps(g: &Graph, traffic: &TrafficSpeeds, mode: i32, d: &Direct) -> Vec<StepData> {+ let mut b = StepBuilder {+ g,+ traffic,+ mode,+ steps: Vec::new(),+ last_bearing: 0.0,+ pending_junction: INVALID_NODE,+ pending_prev: INVALID_NODE,+ pending_approach: INVALID_EDGE,+ };+ for w in d.coords.windows(2) {+ let dist = fast_dist_mm(g, w[0].lat_e7, w[0].lon_e7, w[1].lat_e7, w[1].lon_e7);+ b.add_segment(+ f64::from(w[0].lat_e7) * 1e-7,+ f64::from(w[0].lon_e7) * 1e-7,+ f64::from(w[1].lat_e7) * 1e-7,+ f64::from(w[1].lon_e7) * 1e-7,+ d.name_offset,+ d.type_,+ d.speed_limit,+ dist,+ d.edge_idx,+ );+ }+ b.steps+}+ /// Rebuild the step list from `ctx.target_node`. Returns an empty vec if no /// path exists. pub fn reconstruct_path(@@ -590,6 +856,16 @@ pub fn reconstruct_path( ctx: &RoutingContext, scratch: &mut RoutingScratchpad, ) -> Vec<StepData> {+ // Staying on the edge both ends snapped to usually wins, but not always: a+ // C-shaped road whose two ends meet a straight one is faster left and+ // rejoined. Take whichever is quicker, and take the on-edge route outright+ // when the search found nothing at all.+ if let Some(d) = &ctx.direct {+ if d.time_10ms <= network_time_10ms(g, traffic, mode, ctx, scratch) {+ return direct_steps(g, traffic, mode, d);+ }+ }+ let mut path_nodes: Vec<u32> = Vec::new(); let mut curr = ctx.target_node; let mut safety = 0u32;@@ -622,7 +898,7 @@ pub fn reconstruct_path( let node0 = g.get_node(n0); let j = ctx.start.edge_idx; let geom = if j != INVALID_EDGE {- g.get_edge_coordinates(j, &mut coords)+ g.get_edge_coordinates_from(ctx.start.node_a, j, &mut coords) } else { None };@@ -737,8 +1013,9 @@ pub fn reconstruct_path( b.pending_approach = prev_edge_idx; prev_edge_idx = best_e_idx; - if let Some((count, is_reversed)) =- g.get_edge_coordinates(best_e_idx, &mut coords).filter(|&(c, _)| c >= 2)+ if let Some((count, is_reversed)) = g+ .get_edge_coordinates_from(u, best_e_idx, &mut coords)+ .filter(|&(c, _)| c >= 2) { for p in 0..count - 1 { let p1 = get_pt_at(&coords, count, is_reversed, p);@@ -765,7 +1042,7 @@ pub fn reconstruct_path( let nodek = g.get_node(nk); let j = ctx.end.edge_idx; let geom = if j != INVALID_EDGE {- g.get_edge_coordinates(j, &mut coords)+ g.get_edge_coordinates_from(ctx.end.node_a, j, &mut coords) } else { None };
scripts/maps/README.md
diff --git a/scripts/maps/README.md b/scripts/maps/README.mdindex 85f42ca801..52422a62b7 100644--- a/scripts/maps/README.md+++ b/scripts/maps/README.md@@ -745,23 +745,45 @@ struct PoiRecord { // 14 bytes, little-endian ## Single global routing graph (P16) The offline **routing graph** is a **single global graph** — there is no-per-zone splitting and no separate merge/compaction stage. `osm_ingest`'s-`road_graph` emits, in one pass, exactly the on-disk layout the Rust router+per-zone splitting and no separate merge stage. `osm_ingest`'s `road_graph`+emits, in one pass, exactly the on-disk layout the Rust router (`maps/src/main/rust/src/graph.rs`) mmaps: | File | Contents | Consumed by (graph.rs) | |---|---|---|-| `metadata.bin` | `u32 magic` (`"MARG"` = `0x4752414D`), `u32 version` (1), `u64 node count` — 16 B | `load` |-| `nodes.bin` | `NodeMaster[node_count + 1]` (16 B: `i32 lat_e7`, `i32 lon_e7`, `u64 edge_ptr`), trailing sentinel | `node` / `get_node` |+| `metadata.bin` | `u32 magic` (`"MARG"` = `0x4752414D`), `u32 version` (3), `u64 node count` — 16 B | `load` |+| `nodes.bin` | `NodeRec[node_count + 1]` (**12 B**: `i32 lat_e7`, `i32 lon_e7`, `u32 edge_ptr`), trailing sentinel | `node` / `get_node`, widening into `NodeMaster` | | `edges.bin` | `Edge[edge_count]` (14 B: `u32 target`, `u32 dist_mm`, `u32 name_offset`, `u8 type`, `u8 speed_limit`) | `edge` |-| `lanes.bin` | `u64 offsets[edge_count + 1]` then a `u16` turn-mask blob | `edge_lane_masks` |+| `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 off) × (n + 1)`, then a `u16` turn-mask blob — **sparse**, only lane-bearing edges are listed | `edge_lane_masks` |+| `intermediate.bin` | a delta-encoded polyline blob at offset 0, then a trailer: `u64 rank[..]`, `u8 present[..]` (one bit per directed edge), `u64 coarse[..]`, `u16 within[..]` over the `G` edges that store one, and `u64 G`. `off(g) = coarse[g / 32] + within[g]` where `g = rank(k)` | `get_edge_coordinates` | | `road_names.bin` | NUL-terminated string pool | `road_name` | -`intermediate.bin` (delta-encoded edge geometry) is **optional** and is not-produced by this generator; `graph.rs` treats its absence gracefully and the-router falls back to straight node-to-node segments. It can be added later-without changing any of the files above. When present it **is** length-validated-against `edge_count`, since its offset array is sized from it.+`intermediate.bin` (delta-encoded edge geometry) is **mandatory** and is produced+by the generator. It became mandatory when `road_graph` started collapsing+degree-2 chains: an edge is now a whole road between junctions, so its polyline+is the only record of that road's shape and `Graph::load` refuses a pack without+it. Its tables are sized from `edge_count` and from the `u64 G` in its last 8+bytes, and both are cross-checked against the blob — the offset sentinel must equal+the blob's length and the rank total must equal `G`. `lanes.bin` is validated+against its own index header instead, since it carries no per-edge table either.+See `osm_ingest/README.md` for the encoding rules and the `REVERSE_GEOMETRY_FLAG`+contract.++**Version 2** narrowed `nodes.bin`'s `edge_ptr` to a `u32`, made `lanes.bin` a+sparse index and gave `intermediate.bin` two-level offsets, which took a projected+planet pack from 50.8 GB to ~34 GB. **Version 3** gave `intermediate.bin` a+presence bitmap — 70.4% of directed edges store no polyline — and dropped both+endpoints of every stored polyline, since the first is always the edge's source node+and the last its target, taking the projected pack to ~29 GB. There is no dual-path+reader: an older pack is rejected outright. See+[osm_ingest/README.md](osm_ingest/README.md#getting-a-planet-under-40-gb) and+[Getting it under 30](osm_ingest/README.md#getting-it-under-30).++Because the blob now holds only a polyline's *interior*, decoding needs the edge's+source node: `get_edge_coordinates_from(source, edge_idx, out)` is the real entry+point and `get_edge_coordinates(edge_idx, out)` is a wrapper that recovers the+source with a binary search. Every caller iterating a node's edge range should pass+the source it already holds. **Why single global (drop graph zoning):** the previous pipeline wrote per-zone `*_zone_N.bin` artifacts in a layout `graph.rs` could not load and relied on a@@ -812,9 +834,17 @@ they are delivered differently: fetches the files above from `https://data.vayunmathur.com/<file>` into the app's external files dir (the same dir `Graph::load` reads). It is a single logical download surfaced once in `DownloadedMapsPage` (not per Morton zone).- A planet routing graph is on the order of a few GB (nodes/edges/lanes; far- smaller than the tile basemap), so shipping it whole is practical and removes- the per-zone bookkeeping.+ A planet routing graph is about **29 GB** compacted, so shipping it whole is+ practical and removes the per-zone bookkeeping. That figure is projected from the+ measured planet counts (431 M nodes, 1.07 G directed edges) under the v3 layout;+ v2 put it at ~34 GB and v1 at **50.8 GB**, two thirds of which was dense+ `u64` offset tables in `lanes.bin` and `intermediate.bin` describing edges that+ had nothing to describe — see+ [osm_ingest/README.md](osm_ingest/README.md#getting-a-planet-under-40-gb). An+ earlier revision of this document said "a few GB"; it counted only+ `nodes.bin`/`edges.bin`/`lanes.bin`, budgeted no edge geometry at all, and+ assumed a graph with one node per OSM geometry vertex, which uncompacted would+ have put a planet nearer **140 GB**. * **Map tiles — stay zoned.** The vector basemap (`v5.pmtiles`) is ≈137 GB (see the size table above), so it can never be one download. Offline tile packs remain the 64 Morton-grid `zone_$id.pmtiles` files, downloaded per zone.@@ -900,11 +930,11 @@ poi_extract: 284,216 POIs (172,448 node, 107,612 closed-way, 4,156 relation), 188,990 unique names ~5 s ``` -Verified: `metadata.bin` is the 16-byte `MARG`/v1/`node_count` header;+Verified: `metadata.bin` is the 16-byte `MARG`/version/`node_count` header; `nodes.bin` is `node_count + 1` records with a sentinel whose `edge_ptr` equals-`edge_count`; `edges.bin` is an exact multiple of 14; `lanes.bin` is-`(edge_count + 1) × 8` offset bytes plus the `u16` blob; nodes and POI records-are Morton-ordered. **Both tools are deterministic** — two runs on California+`edge_count`; `edges.bin` is an exact multiple of 14; `lanes.bin`'s index resolves+by the same binary search the device uses; nodes and POI records are+Morton-ordered. **Both tools are deterministic** — two runs on California produce byte-identical output for all eight files, which the C++ never did (it filled its node array from concurrent workers and interned names in thread-scheduling order).
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex 1a5cf2e78b..79d55cfb20 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -5,7 +5,7 @@ Maps app's offline artifacts. Three binaries share one library: | Binary | Replaces | Emits | |---|---|---|-| `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `road_names.bin` |+| `road_graph` | `scripts/maps/generator.cpp` | `metadata.bin`, `nodes.bin`, `edges.bin`, `lanes.bin`, `intermediate.bin`, `road_names.bin` | | `poi_extract` | `scripts/maps/poi_extract.cpp` | `<name>.geojsonseq`, `poi_names.bin`, `poi_index.bin` | | `osm_extract` | `osmium tags-filter \| osmium export \| normalize_*.py` | one `<layer>.geojsonseq` per baked vector layer | @@ -43,6 +43,26 @@ cargo run --release --bin osm_extract -- california-latest.osm.pbf \ --layer safety --out safety.geojsonseq --bbox -122.6,37.2,-121.7,37.9 ``` +`road_graph` takes two flags beyond `--out`, both about build-time memory rather+than output:++```sh+# Chains confined to one OSM way: no segment array, no incidence index.+cargo run --release --bin road_graph -- planet.osm.pbf --within-way-chains++# Write the pack in 3 source-partitioned rounds instead of one.+cargo run --release --bin road_graph -- planet.osm.pbf --rounds 3++# Keep the chain spill off the output disk. `chains.pts` is the only file the+# build reads randomly, so it wants cheap seeks; the output only needs sequential+# writes and can go wherever there is room.+cargo run --release --bin road_graph -- planet.osm.pbf --spill-dir /fast/scratch+```++Neither changes the on-disk contract, and `--rounds` does not change the output+at all — a test asserts every byte is identical across `--rounds 1`, `4` and+`17`. See [Build-time memory](#build-time-memory).+ From Windows, `scripts/maps/build_graph.ps1` wraps the road-graph build in one command and `scripts/maps/build_all.ps1` chains every cargo-only stage. `scripts/maps/build_all.sh` and the per-layer `build_*_layer.sh` scripts call@@ -109,14 +129,23 @@ changing its reader produces a graph that loads as garbage, which is why | File | Layout | Reader | |---|---|---|-| `metadata.bin` | `u32 magic "MARG"`, `u32 version 1`, `u64 node_count` (16 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` |-| `nodes.bin` | `NodeMaster[node_count + 1]`: `i32 lat_e7, i32 lon_e7, u64 edge_ptr`; Morton-sorted, trailing sentinel whose `edge_ptr == edge_count` | `graph.rs` |+| `metadata.bin` | `u32 magic "MARG"`, `u32 version 3`, `u64 node_count` (16 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 |-| `lanes.bin` | `u64 byte_offsets[edge_count + 1]` then the packed `u16` per-lane turn masks | `graph.rs` `LANE_*` |+| `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+`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+[Getting it under 30](#getting-it-under-30) for what each cost and what replaced+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.+ 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@@ -125,6 +154,657 @@ inversions the old tool produced. The POI type numbers live in `src/tags.rs` and are also tabulated in `scripts/maps/README.md`. **Never renumber an existing type — only append.** +## Compaction and `intermediate.bin`++`road_graph` collapses degree-2 chains: a run of nodes that each have exactly two+neighbours becomes a single edge whose polyline lives in `intermediate.bin`. This+is in `src/compact.rs`, and the encoder is `src/geom.rs`.++Before compaction there was one edge per consecutive pair of way nodes, so every+geometry vertex was a routing node. Measured on California:++| | uncompacted | compacted |+|---|---|---|+| nodes | 35,857,253 | 6,416,947 (5.59x fewer) |+| directed edges | 74,340,356 | 16,781,727 (4.43x fewer) |+| `nodes.bin` | 573.7 MB | 102.7 MB |+| `edges.bin` | 1040.8 MB | 234.9 MB |+| `lanes.bin` | 597.1 MB | 135.5 MB |+| `intermediate.bin` | — | 314.1 MB |+| **total** | **2.22 GB** | **0.79 GB (2.8x smaller)** |++Both columns are **v1** layouts. See+[Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and+[Getting it under 30](#getting-it-under-30) for what v2 and v3 do to the+`nodes.bin`, `lanes.bin` and `intermediate.bin` rows.++Those nodes bought nothing: no route ever chose anything at them. What they did+buy was the road's shape, which is why removing them requires storing geometry.++### The file is mandatory++`Graph::load` refuses a pack directory without it. Once an edge is a whole road+between junctions, its polyline is the only record of that road's shape;+`find_nearest_edge` would otherwise project a query onto a straight chord+spanning an entire street, so snapping *and* drawn geometry would be wrong rather+than merely coarse. It is also in `MainActivity.kt`'s download list, and adding+it there makes `InitialDownloader`'s `allFilesPresent` false for any install that+predates it, which re-triggers the download.++### Three encoding rules, all enforced by assertion++All three come from `decode_edge_coords`:++1. **At most 256 points per edge**, endpoints included. The decode loop stops+ there and its callers allocate exactly `[LatLon; 256]`, so a longer polyline+ would be silently truncated. `compact.rs` splits a chain that would exceed the+ budget, promoting the cut node back to a real node (4,983 splits on+ California). The largest legal blob is therefore `4 × 254` = 1016 bytes.+2. **Deltas are `i16`.** Consecutive points must be within 32,767 units+ (~364 m of latitude) on each axis, and the reader uses `wrapping_add`, so an+ overflow would corrupt silently rather than fail. Where a real gap is larger,+ `geom.rs` inserts **collinear** points on the straight line between the pair:+ the geometry is unchanged and each costs 4 bytes.+3. **A chain must begin and end on its own nodes' coordinates.** Only the+ interior is stored, so the reader rebuilds both ends out of `nodes.bin`. This+ was always true by construction — both come from the same coordinate array —+ but the reader now depends on it, so `assert_endpoints` checks it per stored+ edge rather than letting a wrong polyline reach a phone.++An edge whose polyline is just the chord between its own endpoints stores nothing+and is simply absent from the presence bitmap, which is also the escape hatch for+a single hop too long to delta-encode at all.++### `REVERSE_GEOMETRY_FLAG`++Only one edge of a bidirectional pair stores the polyline. The other sets bit+`0x40` in its `type_` byte, and the reader finds the twin by scanning the+*target's* edge range for the first edge pointing back at the source. That halves+the blob, and imposes two obligations on the generator:++* **Set it only when the twin is unambiguous.** With two parallel roads between+ the same pair of nodes, the reader's "first edge back" could resolve to the+ wrong one, so `twin_is_unique` checks there is exactly one, and both polylines+ are stored when there is not.+* **`type_` is a bitfield, not an enum.** Bits 0-5 are the road class, bit 6 is+ this flag. `geometry.rs::ROAD_TYPE_MASK` is the reader's half of that contract;+ it used to be `0x7F`, which let the flag through into `is_mode_allowed`'s range+ checks and so rejected every flagged edge for every travel mode — silently+ deleting half the road network.++### What compaction may not collapse++`compact.rs::classify` requires all of: exactly two incident segments to two+distinct neighbours; agreement on road type, speed limit, name and+one-way-ness; lane masks equal **per traversed direction**, compared by content+rather than by pool offset since two ways intern identical masks at different+offsets; one-way segments actually flowing through the node rather than into it;+and no transit stop code, because isolated-stop reconnection addresses stop nodes+directly.++A ring road whose every node qualifies has no anchor to start from. Its+lowest-numbered node is kept, so the ring becomes one edge from that node to+itself.++A one-way chain is emitted along its traffic flow, not along whichever end the+walk happened to start from.++## Getting a planet under 40 GB++The output format the planet build inherited projected to **50.8 GB**, against a+40 GB target, and two thirds of that was offset tables describing edges that had+nothing to describe. Version 2 is the clean break that fixes it — no dual-path+reader, no downloader change, since nothing had shipped from a v1 pack.++| file | v1 | v2 | basis |+|---|---|---|---|+| `metadata.bin` | 16 B | 16 B | unchanged |+| `nodes.bin` | 6.90 GB | **5.18 GB** | 12 B × (N+1) |+| `edges.bin` | 15.04 GB | 15.04 GB | unchanged |+| `lanes.bin` | 8.60 GB | **0.04 GB** | sparse index |+| `intermediate.bin` | 20.02 GB | **13.86 GB** | two-level offsets |+| `road_names.bin` | 0.25 GB | 0.25 GB | unchanged |+| **total** | **50.8 GB** | **~34.4 GB** | 5.6 GB under target |++Projected from the measured planet counts: 431,474,933 surviving nodes,+1,074,282,569 directed edges, 552,689,139 chains. **Measured on California the same+change is −32.1%** (see [below](#measured-on-california-v1-vs-v2)), against the+−32.3% this table projects, which is the closest thing to a check on it short of+running the planet again.++**`lanes.bin`: a sparse index.** `turn:lanes` is rare — about 2.9 M of a planet's+1.07 G directed edges carry any — so a dense `u64` per edge meant 99.8% of an+8.60 GB file described edges with no lanes at all. Only the lane-bearing edges are+listed now, as `(u32 edge_idx, u32 blob_byte_off)` pairs ascending by edge index,+and `edge_lane_masks` binary-searches instead of indexing. It is called once per+maneuver rather than once per edge, so ~22 probes is free. "This edge has no+lanes" is now spelled by absence from the index rather than by an empty range, and+it resolves to the same `None` the topology-inference fallback in `routing.rs`+already handles.++**`intermediate.bin`: two-level offsets.** A per-edge blob was at most 1028 bytes —+8 for the absolute first point plus 4 per delta, capped at 256 points by the+reader — so six of every eight offset bytes were always zero. v2 replaced the dense+`u64` with a `u64` per 32 edges plus a `u16` within the block, `off(k) =+coarse[k / 32] + within_block[k]`. The block size of 32 is what makes the narrow+half safe: a block spanned at most 32 × 1028 = 32,896 bytes, comfortably inside a+`u16`. That bound is `geom::MAX_POINTS` / `geom::fits` and the chain splitting in+the collapse pass; it is the invariant the whole scheme rests on, so the writer+asserts it and a test pins it at a chain of exactly 256 points. v3 keeps the two+levels but keys them on geometry edges and drops both endpoints, which tightens the+per-blob bound to 1016 bytes — see [Getting it under 30](#getting-it-under-30).++**`nodes.bin`: `edge_ptr` as a `u32`.** 1.07 G edges leave 4× of headroom, so the+record is 12 bytes instead of 16. It is an on-disk `NodeRec` that `node()` widens+into the existing `NodeMaster`, whose `edge_ptr` stays a `u64`, so nothing outside+`graph.rs` sees the change. The generator gained a `cap_u32` guard on the edge+count for it — the same idiom already used for node, survivor and chain counts —+because this is the change that would let a wrapped edge count silently address+another node's edge range.++`edges.bin` is left alone deliberately. Its 14 bytes are `u32 target`,+`u32 dist_mm`, `u32 name_offset`, `u8 type_`, `u8 speed_limit`: `dist_mm` holds a+whole collapsed road so it needs the range, `name_offset` addresses a 250 MB pool,+and `type_` is a bitfield with exactly one spare bit and a history of a masking+error deleting half the road network.++### Stop reconnection is about component *size*, not the largest component++The other thing only a planet could show. `reconnect_isolated_stops` used to find+the largest connected component and hook every stop outside it to its nearest node+inside it. On a region that is right — the largest component is 98.2% of+California, 93.8% of Europe. On a planet it is Eurasia-plus-Africa at **57.7%**,+because continents are not road-connected, so every stop in the Americas,+Australia, Japan, the UK and Indonesia was classified as isolated and the code+tried to bridge an ocean to reach a road in France. It failed **1,173,347** times,+a quarter of all stops, paying for a widening search out to a million-node index+window before each failure.++The question worth asking is *"is this stop attached to a real road network?"*,+not *"is it attached to the biggest one?"*. So the BFS keeps a size per component+instead of discarding all but the largest, a stop needs reconnecting only when its+own component is below `MIN_ROUTABLE_COMPONENT` (1000 nodes), and the target is the+nearest node in **any** component at or above that threshold. A stop alone on an+untagged node is a component of size 1 and is still connected; a stop on a small+island's road network is left alone, because it is already as reachable as that+island gets; a stop in North America connects to North America.++That removes the pathology rather than its symptom: a qualifying node is now+metres away instead of an ocean away, so the widening search almost always+succeeds on its first 1000-node window.++The threshold is capped at the largest component that actually exists, because a+graph with no component of 1000 nodes still has a road network — it is just a+small one — and requiring a size nothing reaches would reconnect nothing. That is+also what keeps the fixtures in `graph_build.rs`, whose whole graph is four nodes,+reconnecting against their own three-node road.++`MIN_ROUTABLE_COMPONENT` wants a measured value rather than a guess, so every+build reports the three counts that make the choice auditable: stops left alone as+already-connected, stops reconnected, and stops that still found nothing. The last+one is the number that decides whether the threshold is right — on a planet it+should collapse from 1,173,347 toward zero.++### Measured on California, v1 vs v2++`california-latest.osm.pbf`, 1.26 GB, both collapse paths, same machine and same+input as the v1 numbers above.++| | reference v1 | reference v2 | within-way v1 | within-way v2 |+|---|---|---|---|---|+| `metadata.bin` | 16 | 16 | 16 | 16 |+| `nodes.bin` | 102,693,792 | **77,020,344** | 113,583,040 | **85,187,280** |+| `edges.bin` | 234,999,884 | 234,999,828 | 252,469,686 | 252,469,630 |+| `lanes.bin` | 135,575,036 | **3,013,792** | 145,815,866 | **3,563,182** |+| `intermediate.bin` | 314,211,280 | **217,693,470** | 318,945,504 | **215,252,596** |+| `road_names.bin` | 5,481,848 | 5,481,848 | 5,481,848 | 5,481,848 |+| **total** | **792,961,856** | **538,209,298** | **836,295,960** | **561,954,552** |+| | | **−32.1%** | | **−32.8%** |++Every byte of that is accounted for, which is what makes it a check rather than a+result:++* `nodes.bin` is exactly `(6,418,361 + 1) × 12` against `× 16`.+* `lanes.bin`'s mask blob is **byte-identical** at 1,289,380 bytes; what went was+ the 134,285,656-byte dense table, replaced by a 1,724,408-byte index over the+ 215,550 edges (**1.28%**) that actually carry `turn:lanes`.+* `intermediate.bin` fell by 96,517,810 bytes, which is precisely the dense+ `(E+1) × 8` table minus the new `coarse` + `within_block` pair. The polyline blob+ is untouched.+* `edges.bin` lost 56 bytes = 4 edges × 14, and those four edges are the stop+ change below, not a format change.++**Stop reconnection, both paths identically:** 81,553 stops → **20,836 already on+a routable component, 60,717 reconnected, 0 found nothing**. The v1 rule+reconnected 60,719, so the reconnected count moved by two pairs — which is the+whole of the `edges.bin` delta. California's largest component is 98.24% of+6,418,361 nodes across 76,081 components, so almost nothing sits in a mid-sized+non-largest component and the two rules were always going to agree here. That is+exactly why the rule had to be fixed against a planet instead.++`route_diff` reference-vs-within reports **34,900** baseline vertices missing from+the candidate and a worst-case route delta of **−1.49 km** — both unchanged from+the v1-era measurements below, which is the evidence that the format change is+semantically inert. A true v1-vs-v2 `route_diff` is not possible by construction:+the reader accepts one version, which is the price of the clean break.++**`--rounds 1` vs `3` vs `17` is byte-identical on all six files, on both collapse+paths.** That is the strongest check either new offset scheme gets: round+boundaries move which edges each pass collects, which coarse block it is filling,+which within-block offsets it appends, where `lanes.bin`'s sparse index resumes and+where `nodes.bin`'s running edge counter picks up — and none of it reaches the file.++## Getting it under 30++v2 left the pack at ~34.4 GB against a 40 GB target, and the next question was+whether 25 GB is reachable. Five candidate changes were priced against measured+Europe and planet counts; the three cheapest and least risky are all in+`intermediate.bin`, and version 3 is those three:++| projected saving | change |+|---|---|+| −2.54 GB | drop the absolute first point — it is always the source node |+| −1.55 GB | a presence bitmap instead of a per-edge offset |+| −1.27 GB | drop the last point — it is always the target node |++That takes `intermediate.bin` from 13.86 GB to **~8.50 GB** and the pack to+**~29.0 GB**:++| file | v1 | v2 | v3 | basis |+|---|---|---|---|---|+| `metadata.bin` | 16 B | 16 B | 16 B | unchanged |+| `nodes.bin` | 6.90 GB | 5.18 GB | 5.18 GB | unchanged since v2 |+| `edges.bin` | 15.04 GB | 15.04 GB | 15.04 GB | unchanged |+| `lanes.bin` | 8.60 GB | 0.04 GB | 0.04 GB | unchanged since v2 |+| `intermediate.bin` | 20.02 GB | 13.86 GB | **8.50 GB** | bitmap + dropped endpoints |+| `road_names.bin` | 0.25 GB | 0.25 GB | 0.25 GB | unchanged |+| **total** | **50.8 GB** | **~34.4 GB** | **~29.0 GB** | **−15.7%** on v2, −42.9% on v1 |++Projected from the same measured planet counts as the v2 table — 431,474,933+surviving nodes, 1,074,282,569 directed edges — with `G`, the number of edges that+store a polyline, projected from Europe's measured 110,807,665 of 374,856,290+(29.56%) at **~317.6 M**. Every row of the v3 column is arithmetic on those two+numbers: the blob loses `12 × G` = 3.81 GB, and the tables go from+`coarse` 0.27 GB + `within` 2.15 GB = **2.42 GB** to `rank` 17 MB + `present`+134 MB + `coarse` 79 MB + `within` 635 MB = **0.87 GB**.++The two dropped endpoints are pure redundancy removal: the test+`intermediate_bin_reproduces_the_collapsed_geometry` already asserted that a stored+polyline starts at its edge's source and ends at its target, so both were already+known to be recoverable from `nodes.bin`. The bitmap follows from the 70.4% of+edges that store no polyline at all, each of which still owned a `u16` and a+repeated coarse `u64` under v2.++Two further changes were priced and **rejected for now**, and they are what the+remaining 3.5 GB to a 25.5 GB pack would have to come from: `dist_mm → u24`+centimetres (−1.07 GB) needs an escape hatch for chains over 167 km and moves every+route cost, and delta-coded `nodes.bin` coordinates (−2.4 GB) put a decode step on+the router's hottest read and must handle Morton quadrant boundaries. Neither is+worth it for a pack already 11 GB under the original target.++**The California measurement checks the arithmetic, not the ratio.** Feeding+California's own counts — E = 16,785,702, G = 4,494,428 — through the same formula+predicts a 79,227,999-byte fall, and the file fell by exactly that (see+[below](#measured-on-california-v2-vs-v3)). The *percentage* differs from the+planet's projected −38.7%, at −36.4%, because California stores a polyline on only+26.8% of its edges against Europe's 29.6% and its mean polyline is shorter: a lower+`G / E` means less endpoint saving per byte of blob. That is a property of the+region, not a disagreement with the model.++**The layout, and why the tables come last.**++```text+[ blob ]+[ u64 rank[E.div_ceil(512) + 1] ] set bits before each 64-byte block, total appended+[ u8 present[E.div_ceil(8)] ] one bit per directed edge+[ u64 coarse[G.div_ceil(32) + 1] ] G = geometry edges = rank[last]+[ u16 within[G + 1] ]+[ u64 G ] fixed-size trailer+```++`G` is not known until the final round has run, so a reserved prefix cannot be+sized — the same problem `lanes.bin` has. `LaneFile` solves it by streaming its+blob to scratch and copying it back, which is free for 13 MB but would be ~23 GB+of extra I/O for this blob. A trailer instead makes the whole file **append-only+with no scratch file at all**, which is strictly less I/O than v2, where+`BlobFile` copied a 2.4 GB prefix back. The four tables are held in memory while+the blob streams: 0.87 GB at planet scale, against v2's 2.42 GB *on disk*.++The reader recovers everything from the last 8 bytes plus `edges.bin`'s file size,+and validates more than v2 did: the file must hold all four tables plus the+trailer, the `coarse`/`within` sentinel must equal the remaining blob region+exactly, and `rank`'s total must equal `G`.++**The offsets are keyed on geometry edges, not edges.** `off(g) = coarse[g / 32] ++within[g]` where `g = rank(k)`, so an edge's polyline is found by testing its+presence bit and then ranking below it — one `u64` load plus at most 64 bytes of+`popcount`. This *tightens* the `u16` bound rather than loosening it: a per-edge+blob is now at most `4 × (256 − 2)` = 1016 bytes, a block of 32 spans at most+32,512, and every entry in a block is a real blob where before most were+zero-length.++**The encoding.** A stored polyline is `Q0 .. Q(m-1)` with `Q0` the source node's+coordinates and `Q(m-1)` the target's. Only the interior deltas are stored: `m − 2`+pairs of `i16`, omitting both the 8-byte absolute `Q0` and the final delta that+lands on `Q(m-1)`. So bytes = `4 × (m − 2)`, the saving is exactly 12 per stored+edge, and `m = byte_len / 4 + 2`. An empty blob decodes to `[source, target]` — the+chord — which is why "no interior" and "the chord" are now the same statement, and+why presence needs a bit rather than a length. Interpolation is unaffected:+`geom::interp_steps` still decides how many steps a hop takes and only the *final*+step is the one omitted.++**The reader API.** `decode_edge_coords` now needs the edge's endpoints, so+`Graph::get_edge_coordinates_from(source, edge_idx, out)` is the real entry point+and `get_edge_coordinates(edge_idx, out)` is a wrapper that recovers the source via+`find_node_idx_for_edge`. All six `routing.rs` call sites pass the source they+already hold; that is not polish, because otherwise the wrapper's ~29-probe binary+search lands inside `find_nearest_edge`'s candidate loop, which runs over a+1601-node window twice per route and up to 16 times per transit plan. As a bonus it+*removes* the `find_node_idx_for_edge` call the reverse-geometry path used to make+per reversed edge, purely to recover a value the caller already had.++### Measured on California, v2 vs v3++`california-latest.osm.pbf`, 1.26 GB, both collapse paths, same machine and input+as the tables above. Only `intermediate.bin` moves.++| | reference v2 | reference v3 | within-way v2 | within-way v3 |+|---|---|---|---|---|+| `metadata.bin` | 16 | 16 | 16 | 16 |+| `nodes.bin` | 77,020,344 | 77,020,344 | 85,187,280 | 85,187,280 |+| `edges.bin` | 234,999,828 | 234,999,828 | 252,469,630 | 252,469,630 |+| `lanes.bin` | 3,013,792 | 3,013,792 | 3,563,182 | 3,563,182 |+| `intermediate.bin` | 217,693,470 | **138,465,471** | 215,252,596 | **134,529,908** |+| `road_names.bin` | 5,481,848 | 5,481,848 | 5,481,848 | 5,481,848 |+| **total** | **538,209,298** | **458,981,299** | **561,954,552** | **481,231,864** |+| | | **−14.7%** | | **−14.4%** |++Against v1 that is **−42.1%** and **−42.5%**.++Every byte of the `intermediate.bin` delta is accounted for, which is what makes it+a check rather than a result. The reference path has E = 16,785,702 directed edges+and G = 4,494,428 stored polylines:++* the v2 file was a 179,925,624-byte blob behind 37,767,846 bytes of tables+ (`coarse` 4,196,440 + `within` 33,571,406);+* dropping both endpoints takes 12 bytes off each of the 4,494,428 stored+ polylines, i.e. **−53,933,136**, leaving a 125,992,488-byte blob;+* the trailer is 12,472,983 bytes — `rank` 262,288 + `present` 2,098,213 ++ `coarse` 1,123,616 + `within` 8,988,858 + 8 — so the tables cost **−25,294,863**;+* 125,992,488 + 12,472,983 = **138,465,471**, exactly the file on disk.++So the presence bitmap plus the narrower offset tables are 3.0× smaller than v2's+two-level pair, and the blob is 30% smaller for holding nothing but interiors.++**`route_diff` is unchanged from the v2 baseline, to the digit.** `compare` reports+the same **999** same-snap-same-length, **966** alternative optimum, **8** snapped+elsewhere, and the same worst deltas of **−1,493,486 mm** and **−20,893** 10 ms+units. `geometry` reports the same **34,900** baseline vertices missing forward and+**29,703** reversed, and the same ±98,897,640 mm length delta, so the vertex+difference is still symmetric. That is the point of keeping `count == 0` for an+absent polyline in this change: every one of those numbers describes the *reference+vs within-way* difference, and none of them may move for a format change. They did+not.++`geometry / reversed` also matches: 4,494,428 / 3,669,235 on the reference path and+4,377,764 / 3,595,577 on within-way, and 8,163,663 of 16,785,702 edges resolve a+polyline either way.++**`--rounds 1` vs `3` vs `17` is byte-identical on all six files, on both collapse+paths.** That is the strongest check the presence bitmap gets, because round+boundaries move which edges each pass collects, which presence bits each pass sets,+which coarse block it is filling and which within-block offsets it appends — and+none of it reaches the file.++Europe and planet runs are out of scope for this change; the ~29 GB figure above+stays a projection.++**A note the earlier revision of this file got wrong.** The p99 snap offset of+2.2 km recorded below was once attributed to `find_nearest_edge` skipping edges+with no resolvable geometry. It does not skip them: it falls through to+"No geometry: snap to the straight node-to-node segment" and projects onto the+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.++## Build-time memory++The output has fitted a planet for a while; the build did not. California peaked+at **4.97 GB of RSS** for a 1.26 GB PBF, which scales to roughly 310 GB on an+80 GB planet file — and the structural breakdown agreed, putting the pass-3+working set at about 217 GB. The gap was 2.3x on a 94 GB machine, so this was a+restructure rather than a diet, following the same route `gtfs_ingest` took: not+spill machinery, but a streaming, incrementally-finalised build.++Four changes do the work.++**Rank/select over the bitset that already existed.** `Bitset` marks exactly the+graph's nodes, keyed by raw OSM id. A cumulative popcount per 512-bit block —+sized to the largest id actually seen, not to `BITSET_SIZE` — makes+`dense(osm_id)` an O(1) rank. The node array is then *implicitly ordered by OSM+id*, which deletes the sorted `(osm_id, local_id)` table the edge pass used to+binary-search, deletes the per-node `osm_id` because it is the index, and deletes+the per-node spatial key because only the survivors ever need a Morton sort.+What is left is `coords`, at 8 bytes a node.++This is also where dangling references become dangerous rather than merely+untidy. Pass 1 marks every ref of every routable way, including refs to nodes no+blob in the file defines — an extract clipped at a boundary is full of them — and+under rank addressing each of those owns a slot. A slot that never receives+coordinates reads as `(0, 0)`, which corrupts distances, spatial keys and+polylines while leaving every count plausible. Hence the `present` bitset, set+during the coordinate scatter, and hence the pass order: **coordinates before+anything that reads the node array**.++**Never cache ways; re-read the PBF.** `blob_kinds` already lets a later pass+skip whole blobs. Way blobs are a small minority of a planet file, so re-reading+them is far cheaper than the ~32 GB way-and-ref cache it replaces. The build logs+what fraction of blobs the ways pass actually read, because that number is what+justifies the strategy.++**Never materialise segments** (`--within-way-chains`). Restricting chains to a+single OSM way means every segment in a chain shares its way's type, speed, name,+one-way-ness and lanes *by construction*, so the attribute-agreement half of+`compact.rs::classify` becomes free. All that remains is a global per-node+degree, which is one byte a node. That deletes the segment array **and** the+incidence CSR over it — 114 GB of the 217.++**Spill the chains and write in source-partitioned rounds.** Chains go to+`chains.hdr` (fixed-size records, so the count is the file size over the stride+and any stage can seek to chain *k*) and `chains.pts` (coordinates, not node ids,+so `coords` is freed the moment the spill is written). The edge index, the+component scan and every write round are then sequential scans over those files.++### What within-way chains cost++An accepted quality regression, and a real one: a node where two different ways+meet end-to-end with matching tags is collapsed by `compact.rs` and kept here.+OSM splits long roads constantly, at every tag change and at the 2000-node way+ceiling, so this is not a rare case. `graph_build.rs`'s+`within_way_chains_keep_the_node_where_two_ways_meet` states it as a test rather+than an estimate.++Two things soften it. The 256-point split budget already forces cuts on long+dense roads anyway, and more surviving nodes strictly *improves* snapping — the+p99 snap offset fell from 3.7 km to 2.2 km when compaction landed, for the same+reason in reverse. Nothing about the drawn shape of a road changes: the extra node+was already a vertex in `intermediate.bin`.++Two correctness simplifications come free with it, both of which were bugs that+had to be fixed once already. The walk advances through a finite ref list, so it+cannot loop: there is no per-segment "used" flag and no anchorless-cycle phase, and+a ring way closes on its own first node. And within one way every segment runs+along ref order, so a one-way chain is already oriented along its traffic and+there is no reorientation step to hand the forward and backward lane masks to the+wrong end.++If the regression turns out to be unacceptable at scale, the recovery path needs+no new memory: run `compact.rs`'s logic over the **chain** stream instead of the+segment stream. Chains are a few hundred million records rather than billions of+segments, they already carry every attribute `classify` compares, and a chain is+structurally a `Seg` with a point range.++### Why the writer uses rounds and not computed offsets++Computing each edge's index and writing it into place is sound for `edges.bin` —+fixed 14-byte records, pre-sized file — and wrong for the two blob files. The+reader derives a polyline's length from `off(k + 1) - off(k)` and a lane run's+length from the next index entry, so `intermediate.bin` and `lanes.bin` are forced+into edge-index order with monotonic offsets, and writing a blob at a computed+offset would mean knowing every earlier blob's length first: a per-edge length+array, a prefix sum and a second encode pass.++Partitioning by source instead makes every write an append. Each round takes a+contiguous range of final node ids, scans the spill for the edges whose *source*+falls in that range, sorts that buffer by `(source, target, chain)`, and writes+both blobs, both of `intermediate.bin`'s offset halves, `edges.bin` and `nodes.bin`+forwards. Offsets come out monotonic by construction, the offset halves become+append-only scratch files copied into their reserved prefixes at the end,+`nodes.bin`'s running edge counter works because the rounds ascend, and the+`(source, target)` grouping the reader and `twin_is_unique` depend on is restored+within each round.++`lanes.bin` is the one file that cannot reserve a prefix, because its index is+sparse and `n` is not known until the last round has run. Its blob streams to a+scratch file while the index accumulates in memory — 23 MB at planet scale — and+the header plus index are written in front of the blob at the end.++Each round's edge count is checked against `edge_ptr` *before* anything is+written, which catches both an edge landing in the wrong round and an edge whose+source is not a surviving node.++`--rounds` defaults to 1, so small inputs and the test suite are untouched.++`--spill-dir` puts the spill somewhere other than the output directory. Worth+separating, because `chains.pts` is the only file the build reads *randomly* —+once per edge that stores a polyline — while the output only ever needs+sequential writes. On the first California run the spill sat on a slow mount and+that single random read per edge cost more wall clock than every other stage put+together: 47 minutes at 21% CPU, with 17.8 M voluntary context switches against+16.8 M edges. Two reorderings removed most of those reads outright — a chain of+two points cannot have stored geometry, and an edge that defers to its twin never+needs the polyline — and the flag moves the rest onto a disk whose seeks are+cheap.++### Measured on California++`california-latest.osm.pbf`, 1.26 GB, 23010 data blobs, 35,864,766 marked nodes.+Both paths built from the same input on the same machine, spill on a local disk:++| | reference (`compact.rs`) | `--within-way-chains` |+|---|---|---|+| nodes kept | 6,418,361 | 7,098,939 (+10.6%) |+| directed edges | 16,785,706 | 18,033,549 (+7.4%) |+| chains | 8,687,974 | 9,368,552 (+7.8%) |+| split for the 256-point limit | 4,985 | 4,480 |+| largest component | 98.24% | 98.32% |+| `intermediate.bin` | 314,211,280 B | 318,945,504 B (+1.5%) |+| total road length | 1,950,166 km | −0.005% |+| **peak RSS** | **4.49 GB** | **2.79 GB (−38%)** |+| wall clock | 1:33 | 1:26 |++So the cross-way regression the plan could only guess at is **about a tenth of the+node count**, bought for 38% less peak memory and the deletion of the segment+array and its incidence index. The ways pass read **2145 of 23010 blobs (9.3%)**,+which is the measurement that justifies re-reading them rather than caching.++Both `intermediate.bin` figures are **v1** sizes, measured before the two-level+offset table. The node and edge counts, the split count and the peak RSS are+unaffected by the format change.++Note that ~2.5 GB of either figure is the `BITSET_SIZE` node mask, which is a+fixed cost independent of region size, so neither number scales linearly.++`route_diff geometry` reports a vertex-set difference of ~0.1% in **both**+directions — each build appears to be "missing" vertices the other has, 34,900 one+way and 29,703 the other, with the total length delta exactly ±98,897,640 mm. That+symmetry is the tell: within-way chains keep strictly more nodes, so they cannot+lose a real vertex. What moves is the *interpolated* filler `geom::encode` inserts+when a gap exceeds ~364 m — chopping a polyline at a different node slides that+filler along the same straight line. `route_diff` counts those points as vertices,+so its vertex check has a false-failure mode whenever the chopping changes; the+length tolerance, which is the check that would catch real loss, passes both ways.++Both vertex counts were **re-measured unchanged under v2**, which is the evidence+that the offset-format change is semantically inert: a different way of addressing+the same polyline blob cannot move a vertex, and it did not.++`route_diff compare`, re-run under v2 over the same 2000 pairs: 999 identical,+**966 taking an alternative optimum of a different length**, 8 snapping more than a+metre elsewhere, none gained or lost routability, worst case **−1.49 km** on a long+route. **This is still not explained.** The plausible cause is that more surviving+nodes mean more turn penalties, which moves the optimum. The figure reproduces the+v1-era measurement to the metre, but `routing.rs` is *still* being modified+concurrently, so this is a second measurement against a tree that is still not+quiet rather than the clean re-run that would settle it.++### Measured on Europe++`europe-latest.osm.pbf`, 33.2 GB, 534,883 blobs, 793,460,857 marked nodes. The+continent gate matters because it is the first run where `coords`, `degree`,+`edge_ptr` and `targets` all pass a gigabyte, and where the `u32` ceilings come+within about 2x.++| | reference | `--within-way-chains` | + streamed spill, `--rounds 8` |+|---|---|---|---|+| nodes kept | 138,635,441 | 151,447,545 (+9.2%) | same |+| directed edges | 350,312,326 | 374,856,290 (+7.0%) | same |+| chains | 178,171,772 | 190,983,876 | same |+| `intermediate.bin` | 6.85 GB | 6.99 GB | same |+| **peak RSS** | **61.85 GiB** | **31.81 GiB** | **14.30 GiB** |+| wall clock | 39:11 | 35:17 | 41:15 |++Three things to take from that.++**The reference path is out at planet scale, measured rather than argued.** 61.85 GiB+for a continent, on a 94 GB machine, with a planet 2.65x larger.++**The cross-way regression is stable across two scales**: +10.6% nodes on+California, +9.2% on Europe. It does not grow with the input.++**The last two thirds of the memory win came from two changes the fixtures could+never have shown.** At `--rounds 1` the write buffer held every edge —+374,856,290 x 48 B, 18 GB — and the chain pass accumulated the whole chain set+before writing the spill, another 11.7 GB. Neither is visible on a 9-node fixture.+The rounds writer already existed for the first; the second needed the spill write+moved into the pass sink, which is where it should have been.++All six output files are **byte-identical** between the `--rounds 1` accumulated+build and the `--rounds 8` streamed one, on a 375 M-edge graph. That is the+strongest check the rounds writer gets: round boundaries move which edges each pass+collects, which offsets it appends and where `nodes.bin`'s running counter resumes,+and none of it reaches the file.++The cost of eight rounds is eight sequential passes over a 16 GB spill, which is+the 17% of extra wall clock.++A planet is run at **`--rounds 3`**, not 8. The write buffer is+`edges / rounds × 48 B`, so three rounds move it from 6.4 GB to 17.2 GB and peak+RSS from ~24 GB to roughly 30-35 GB — still comfortable in 94 GB — in exchange for+three passes over the 24 GB header spill instead of eight. The header spill is on+the slower mount, so that should be the larger effect.++### Measuring it++`road_graph` prints its own peak RSS from `/proc/self/status` at the end of every+run, so every build is a measurement rather than something to be caught with+`top`. `VmHWM` is a high-water mark, so it survives the frees that a sample+between two phases would miss; it does not include page cache or dirty pages,+which is a further reason the rounds writer is preferable to computed-offset+writes. Other platforms report nothing rather than a guess.++Also worth watching, in roughly this order: the cross-way regression on a real+extract; the dangling-ref ratio, which the build logs as marked ids with no+coordinates; the fraction of blobs the ways pass skips; and `unique_names` /+`name_bytes`, which decides whether `names.rs` needs `gtfs_ingest`'s `StringPool`+treatment.++Two rules hold everywhere. Every large array must be allocated at its final size:+one `push`-driven doubling on a 12 GB array transiently costs 36 GB. And
Diff truncated.