Modern Apps git

← Modern-Apps.git

maps: pack format v5/v6 - 7-byte edge record, sparse name table

Commit
41df2a7be835dd06ee7373dfc27a90a6d5f3726b
Author
vayun-mathur <[email protected]>
When
2026-08-23 03:22 UTC (3 months ago)
Parents
423bfaa

Diff

maps/src/main/rust/examples/route_diff.rs
diff --git a/maps/src/main/rust/examples/route_diff.rs b/maps/src/main/rust/examples/route_diff.rsindex 135d32dc93..f6e10824f8 100644--- a/maps/src/main/rust/examples/route_diff.rs+++ b/maps/src/main/rust/examples/route_diff.rs@@ -399,10 +399,18 @@ fn dump(args: &[String]) -> Result<bool, String> {         w(&n.edge_ptr.to_le_bytes())?;     }     f.flush().map_err(|e| format!("{out}: {e}"))?;+    // The escape and named counts are reported but deliberately *not* written into+    // the dump. The dump has to stay byte-identical across every phase, and which+    // fields a record could not hold is a property of the encoding rather than of the+    // graph.     println!(-        "{out}: {} edge(s) and {} node record(s)",+        "{out}: {} edge(s) and {} node record(s), {} escaped ({:.4}%), {} named ({:.2}%)",         g.edge_count,-        u64::from(g.node_count) + 1+        u64::from(g.node_count) + 1,+        g.escape_count,+        g.escape_count as f64 / g.edge_count.max(1) as f64 * 100.0,+        g.named_edges,+        g.named_edges as f64 / g.edge_count.max(1) as f64 * 100.0     );     Ok(true) }@@ -1059,7 +1067,12 @@ fn geometry(args: &[String]) -> Result<bool, String> {     }     println!(); -    let missing: Vec<&(i32, i32)> = b.vertices.difference(&c.vertices).collect();+    // Sorted, because the sample below is the only thing a human has to go on and a+    // `HashSet`'s iteration order is randomised per process — so an unsorted sample+    // changes on every run of the same pack, which makes it useless for both+    // diagnosis and for diffing two runs against each other.+    let mut missing: Vec<&(i32, i32)> = b.vertices.difference(&c.vertices).collect();+    missing.sort_unstable();     let mut ok = true;     if missing.is_empty() {         println!("PASS  every baseline vertex survives in the candidate");
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 266bd42caf..bcc135a819 100644--- a/maps/src/main/rust/src/graph.rs+++ b/maps/src/main/rust/src/graph.rs@@ -73,11 +73,15 @@ pub const GRAPH_MAGIC: u32 = 0x4752_414D; /// 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. Version 4 changes no+/// polyline. Version 4 changes no /// layout at all: it adds `edge_count` to `metadata.bin` so that nothing is /// derived from a file's *length*, which is what the next round of record-/// narrowing would silently invalidate. There is no dual-path reader: an older-/// pack is rejected.-pub const GRAPH_VERSION: u32 = 4;+/// narrowing would silently invalidate. Version 5 is that narrowing: an+/// `edges.bin` record is 11 bytes rather than 14, taking planet to ~25.8 GB.+/// Version 6 moves `name_offset` out of the record into a sparse side table, since+/// two thirds of edges are unnamed, taking the record to 7 bytes and planet to+/// ~23.3 GB. There is no dual-path reader: an older pack is rejected.+pub const GRAPH_VERSION: u32 = 6;  /// Sentinel `name_offset` meaning "this edge has no name". ///@@ -86,6 +90,57 @@ pub const GRAPH_VERSION: u32 = 4; /// for the places that have to put a `u32` in a struct crossing the JNI boundary. pub const NO_NAME: u32 = 0xFFFF_FFFF; +/// Sentinel in an [`EdgeRec`]'s `target_delta` meaning "this edge's `target` and+/// `dist_mm` are both in the escape table".+///+/// Reserved rather than used, so the representable delta range is symmetric at+/// ±32767.+const TARGET_DELTA_ESCAPE: i16 = i16::MIN;++/// Sentinel in an [`EdgeRec`]'s `u24 dist_mm` meaning the same thing.+///+/// # Why one escape table and not two+///+/// Either sentinel means *both* fields come from the escape row, so one branch in+/// the A* relaxation covers both. Two sentinels with two tables would cost two+/// branches, two metadata fields and two sets of off-by-one risk to keep a 39 MB+/// table apart from an 85 KB one.+///+/// Merging also makes the `dist_mm` escape rate irrelevant to the design, which+/// matters because it is the *least* transferable number available: California has+/// 166 edges past 16.78 km, and collapsed chains in Siberia or the Australian+/// Outback will be far longer. A hundredfold miss just rides along in the same+/// table.+const DIST_MM_ESCAPE: u32 = 0xFF_FFFF;++/// Directed edges per entry of `edges.bin`'s escape block index.+///+/// # Why a block index and not a binary search+///+/// The inline sentinel already *is* the presence bit — it is in a register that was+/// just loaded — so a v3-style presence bitmap would spend 134 MB duplicating it.+/// All that is missing is edge index → row, and `u32 escape_first[E/1024 + 1]` is+/// 4.2 MB at planet scale: one load from a largely cache-resident array, then a scan+/// of the ~3 rows a block holds at a 0.3% escape rate, usually one cache line. A+/// binary search over 3.24 M rows would be 12–15 misses instead.+///+/// `lanes.bin` does binary-search its sparse index, and its doc comment justifies+/// that by being "called once per maneuver rather than per edge". `target` is read+/// on every relaxation, so that precedent does not transfer.+pub const ESCAPE_BLOCK: u64 = 1024;++/// Alignment every section of a multi-section file starts on.+///+/// Eight rather than four so that a section's first entry is naturally aligned+/// whatever its width, and so that section offsets do not depend on `E mod 8`.+const SECTION_ALIGN: u64 = 8;++/// Round `n` up to the next multiple of `align`, which must be a power of two.+#[inline]+const fn align_up(n: u64, align: u64) -> u64 {+    (n + align - 1) & !(align - 1)+}+ /// 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@@ -96,11 +151,77 @@ pub const NO_NAME: u32 = 0xFFFF_FFFF; /// 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;+/// Bytes of presence bitmap one entry of a 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, while the index is a 64th of the bitmap it indexes.+/// `RANK_BLOCK_BYTES` in the generator, and the two must agree.+pub const RANK_BLOCK_BYTES: u64 = 64;++/// A presence bitmap over the directed edges, plus a rank index over it.+///+/// Answers two questions: does edge `idx` have one of these, and if so which one is+/// it. That is what makes a per-edge field sparse — the edges without one own no+/// bytes at all — and it is used twice: for `intermediate.bin`'s stored polylines+/// (70.4% of a planet's edges store none) and for `edges.bin`'s names (62.3% to 68.9%+/// are unnamed, and the fraction *falls* with scale). One type rather than two+/// transcriptions of the same eight lines.+///+/// ```text+/// [ 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+/// ```+#[derive(Clone, Copy)]+struct EdgeBitmap {+    rank: *const u8,+    present: *const u8,+}++impl EdgeBitmap {+    /// Byte size of both tables for `edge_count` directed edges. The generator sizes+    /// them the same way.+    const fn bytes(edge_count: u64) -> u64 {+        (edge_count.div_ceil(RANK_BLOCK_BYTES * 8) + 1) * std::mem::size_of::<u64>() as u64+            + edge_count.div_ceil(8)+    }++    /// Offset of `present` within the pair, i.e. the size of `rank` alone.+    const fn present_offset(edge_count: u64) -> u64 {+        (edge_count.div_ceil(RANK_BLOCK_BYTES * 8) + 1) * std::mem::size_of::<u64>() as u64+    }++    /// True when edge `idx` has one.+    #[inline]+    fn contains(&self, idx: u64) -> bool {+        let byte = unsafe { read_at::<u8>(self.present, (idx / 8) as usize) };+        byte & (1u8 << (idx % 8)) != 0+    }++    /// How many edges below `idx` have one, i.e. the side-table index of edge `idx`+    /// itself when its own bit is set.+    ///+    /// Only meaningful for an edge whose bit *is* set, so callers must test+    /// [`EdgeBitmap::contains`] first or they will read another edge's entry.+    #[inline]+    fn rank_of(&self, idx: u64) -> u64 {+        let byte = idx / 8;+        let block = byte / RANK_BLOCK_BYTES;+        let mut n = unsafe { read_at::<u64>(self.rank, block as usize) };+        for b in block * RANK_BLOCK_BYTES..byte {+            n += u64::from(unsafe { read_at::<u8>(self.present, b as usize) }.count_ones());+        }+        let partial = unsafe { read_at::<u8>(self.present, byte as usize) };+        n + u64::from((partial & ((1u8 << (idx % 8)) - 1)).count_ones())+    }++    /// The rank index's appended total, which must equal the side table's length.+    /// Cheap, and it ties the index to the table it indexes rather than trusting both+    /// to have come from the same run.+    #[inline]+    fn total(&self, edge_count: u64) -> u64 {+        unsafe { read_at::<u64>(self.rank, edge_count.div_ceil(RANK_BLOCK_BYTES * 8) as usize) }+    }+}  // --- On-disk packed structs --- // `#[repr(C, packed)]` reproduces the exact byte strides the generator writes@@ -130,20 +251,62 @@ struct LaneEntry {     blob_off: u32, } -/// An `edges.bin` record as the generator writes it: 14 bytes.+/// An `edges.bin` record as the generator writes it: 11 bytes. /// /// Private, so a layout change stays inside this file. [`Graph::edge`] widens it /// into [`Edge`].+///+/// `target` is stored as a signed delta from the edge's own source rather than+/// absolutely, which is only affordable because the nodes are sorted by a+/// space-filling curve and an edge is short: measured on California, 99.699% of+/// deltas fit an `i16`. `dist_mm` is a `u24`, which is exact for anything under+/// 16.78 km — 99.999% of edges. The rest escape; see [`TARGET_DELTA_ESCAPE`].+///+/// `name_offset` is *not* a field. Two thirds of edges are unnamed — 62.3% of+/// California's, 68.9% of Europe's — so it lives in a sparse side table reached+/// through [`Graph::edge_name_offset`], and the four bytes it used to cost every+/// edge are now four bytes for the third that have one. It is read on the+/// instruction-emission path and never in the A* relaxation, which is what makes+/// three loads instead of one affordable there and not here. #[repr(C, packed)] #[derive(Clone, Copy)] struct EdgeRec {-    target: u32,-    dist_mm: u32,-    name_offset: u32,+    target_delta: i16,+    /// `dist_mm` as three little-endian bytes. Assembled by [`EdgeRec::dist_mm`]+    /// rather than by loading a `u32` and masking, so the read can never run past+    /// the end of the array.+    dist: [u8; 3],     type_: u8,     speed_limit: u8, } +impl EdgeRec {+    #[inline]+    fn dist_mm(&self) -> u32 {+        let d = self.dist;+        u32::from_le_bytes([d[0], d[1], d[2], 0])+    }++    /// True when `target` and `dist_mm` both live in the escape table.+    #[inline]+    fn escaped(&self) -> bool {+        // Read into a local first: `self.target_delta` is a field of a packed+        // struct, so taking a reference to it is not allowed.+        let delta = self.target_delta;+        delta == TARGET_DELTA_ESCAPE || self.dist_mm() == DIST_MM_ESCAPE+    }+}++/// One row of `edges.bin`'s escape table: the fields an 11-byte record could not+/// hold, for the 0.3% of edges that need them. Ascending by `edge_idx`.+#[repr(C, packed)]+#[derive(Clone, Copy)]+struct EscapeRow {+    edge_idx: u32,+    target: u32,+    dist_mm: u32,+}+ /// The in-memory view of an `edges.bin` record, the same widening /// [`NodeRec`]/[`NodeMaster`] uses. ///@@ -189,7 +352,8 @@ const _: () = {     // validation in `Graph::load` derives from these, so they are also what makes     // that validation mean anything.     assert!(std::mem::size_of::<NodeRec>() == 12);-    assert!(std::mem::size_of::<EdgeRec>() == 14);+    assert!(std::mem::size_of::<EdgeRec>() == 7);+    assert!(std::mem::size_of::<EscapeRow>() == 12);     assert!(std::mem::size_of::<LaneEntry>() == 8); }; @@ -278,17 +442,31 @@ pub struct Graph {      nodes: *const u8,     pub node_count: u32, // real nodes; nodes.bin has node_count + 1 (sentinel)-    edges: *const u8,     pub edge_count: u64, +    // `edges.bin`, in five sections:+    //   [ EdgeRec[E] ][ pad ][ u32 escape_first[E/1024 + 1] ][ EscapeRow[escapes] ]+    //   [ pad ][ u64 name rank[..] ][ u8 name present[..] ][ u32 name_off[named] ]+    // The records hold `target` as an i16 delta and `dist_mm` as a u24; either+    // field's sentinel sends both to the escape table. See `EdgeRec`.+    edges: *const u8,+    escape_first: *const u8, // u32[E.div_ceil(ESCAPE_BLOCK) + 1]+    escapes: *const u8,      // EscapeRow[escape_count], ascending by edge_idx+    /// Edges whose `target` or `dist_mm` came out of the escape table rather than+    /// the record. Validated against the block index's total at load.+    pub escape_count: u64,+    names: EdgeBitmap,+    name_off: *const u8, // u32[named_edges], indexed by rank in `names`+    /// Edges with a name at all. Validated against the rank index's total at load.+    pub named_edges: u64,+     // `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]+    // where g is the edge's rank in `geometry`.+    intermediate_data: *const u8,   // delta-encoded coordinate bytes, at offset 0+    geometry: EdgeBitmap,           // which edges store a polyline, and their rank+    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.@@ -344,11 +522,16 @@ impl Graph {             base.push('/');         } -        // metadata.bin: u32 magic, u32 version, u64 node_count, u64 edge_count.-        // Scoped so the mapping is released before the big regions are mapped.-        let (node_count, edge_count) = {+        // metadata.bin: u32 magic, u32 version, then a u64 count per section that+        // needs one — node_count, edge_count, escape_count, named_edges. Scoped so+        // the mapping is released before the big regions are mapped.+        //+        // Explicit count fields rather than a generic section directory: each+        // version adds one, and a named field is more debuggable than speculative+        // generality.+        let (node_count, edge_count, escape_count, named_edges) = {             let meta = MmapRegion::map(&format!("{base}metadata.bin"))?;-            if meta.len < 24 {+            if meta.len < 40 {                 return None;             }             let magic = unsafe { read_at::<u32>(meta.base(), 0) };@@ -358,19 +541,22 @@ impl Graph {             }             let nodes = unsafe { read_at::<u64>(meta.base().add(8), 0) };             let edges = unsafe { read_at::<u64>(meta.base().add(16), 0) };+            let escapes = unsafe { read_at::<u64>(meta.base().add(24), 0) };+            let named = unsafe { read_at::<u64>(meta.base().add(32), 0) };             // `edge_ptr` is a `u32`, so an edge count past that ceiling would have             // wrapped in the writer and pointed a node at another node's range. The-            // generator refuses to produce one; this refuses to read one.-            if u32::try_from(edges).is_err() {+            // generator refuses to produce one; this refuses to read one. Neither+            // sparse table can describe more edges than exist.+            if u32::try_from(edges).is_err() || escapes > edges || named > edges {                 return None;             }-            (u32::try_from(nodes).ok()?, edges)+            (u32::try_from(nodes).ok()?, edges, escapes, named)         };          // `edge_count` now comes from the header rather than from `edges.bin`'s-        // length. That is the point of version 4: every later version narrows the-        // record, and a derived count would change silently with the stride and-        // mis-size `intermediate.bin`'s trailer — which is computed from it.+        // length. That is the point of version 4, and 5 and 6 are why: the record is+        // 7 bytes and the file has four more sections behind it, so its length is no+        // longer any simple multiple of anything.         let nodes_region = MmapRegion::map(&format!("{base}nodes.bin"))?;         let edges_region = MmapRegion::map(&format!("{base}edges.bin"))?;         // nodes.bin is `NodeRec[node_count + 1]`: one sentinel record past the real@@ -380,9 +566,52 @@ impl Graph {         if nodes_region.len as u64 != want_nodes {             return None;         }-        if edges_region.len as u64 != edge_count * std::mem::size_of::<EdgeRec>() as u64 {++        // edges.bin's five sections, computed forwards from the metadata counts.+        // The total-length assertion below is what replaces v3's self-locating+        // trailer: if the computed sections do not exactly consume the region, the+        // file is not the one these counts describe.+        let escape_blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;+        let escape_first_off =+            align_up(edge_count * std::mem::size_of::<EdgeRec>() as u64, SECTION_ALIGN);+        let escapes_off =+            escape_first_off + escape_blocks * std::mem::size_of::<u32>() as u64;+        let names_off = align_up(+            escapes_off + escape_count * std::mem::size_of::<EscapeRow>() as u64,+            SECTION_ALIGN,+        );+        let name_off_off = names_off + EdgeBitmap::bytes(edge_count);+        let want_edges = name_off_off + named_edges * std::mem::size_of::<u32>() as u64;+        if edges_region.len as u64 != want_edges {+            return None;+        }+        let edges = edges_region.base();+        let escape_first = unsafe { edges.add(escape_first_off as usize) };+        let escapes = unsafe { edges.add(escapes_off as usize) };+        let names = EdgeBitmap {+            rank: unsafe { edges.add(names_off as usize) },+            present: unsafe {+                edges.add((names_off + EdgeBitmap::present_offset(edge_count)) as usize)+            },+        };+        let name_off = unsafe { edges.add(name_off_off as usize) };+        // The block index's last entry is the row total, and the rank index's is the+        // named-edge total. Both are the direct analogue of `intermediate.bin`'s+        // `rank_total == geometry_edges` check: they tie an index to the section it+        // indexes rather than trusting both to have been written by the same run.+        if unsafe { read_at::<u32>(escape_first, (escape_blocks - 1) as usize) } as u64+            != escape_count+            || names.total(edge_count) != named_edges+        {             return None;         }+        // Rows ascend, so bounding the last one bounds them all.+        if escape_count > 0 {+            let last = unsafe { read_at::<EscapeRow>(escapes, (escape_count - 1) as usize) };+            if u64::from(last.edge_idx) >= edge_count {+                return None;+            }+        }          // intermediate.bin:         //   [ blob ][ u64 rank[..] ][ u8 present[..] ][ u64 coarse[..] ]@@ -404,21 +633,24 @@ impl Graph {         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 bitmap_bytes = EdgeBitmap::bytes(edge_count);         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;+        let trailer = bitmap_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 geometry = EdgeBitmap {+            rank: unsafe { intermediate_data.add(blob_bytes as usize) },+            present: unsafe {+                intermediate_data+                    .add((blob_bytes + EdgeBitmap::present_offset(edge_count)) as usize)+            },+        };+        let intermediate_coarse = unsafe { intermediate_data.add((blob_bytes + bitmap_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@@ -430,16 +662,7 @@ impl Graph {                 (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 {+        if sentinel != blob_bytes || geometry.total(edge_count) != geometry_edges {             return None;         } @@ -488,8 +711,6 @@ impl Graph {         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();-         // --- Derived tables (identical formulas to the C++ init) ---         let mut lon_to_mm_scale = [0u32; 4096];         for (i, scale) in lon_to_mm_scale.iter_mut().enumerate() {@@ -542,11 +763,16 @@ impl Graph {             _lanes_region: lanes_region,             nodes,             node_count,-            edges,             edge_count,+            edges,+            escape_first,+            escapes,+            escape_count,+            names,+            name_off,+            named_edges,             intermediate_data,-            intermediate_rank,-            intermediate_present,+            geometry,             intermediate_coarse,             intermediate_within,             lane_index,@@ -624,12 +850,10 @@ impl Graph {      /// Edge `idx`, which must be one of node `source`'s outgoing edges.     ///-    /// `source` is not needed to find the record today. It is in the signature-    /// because the record will stop storing `target` absolutely — a delta from the-    /// source is three bytes smaller — and because passing it makes the-    /// debug assertion below possible, which is the cheapest available guard-    /// against the one bug class that change introduces: decoding an edge against-    /// the wrong source produces a plausible node id, not a crash.+    /// `source` is what makes the record readable at all: it stores `target` as a+    /// signed delta from it. Passing the wrong one produces a plausible node id+    /// rather than a crash, which is why the debug assertion below exists — it is the+    /// cheapest available guard against the one bug class delta coding introduces.     #[inline]     pub fn edge(&self, source: u32, idx: u64) -> Edge {         debug_assert!(@@ -641,21 +865,55 @@ impl Graph {             self.edge_range(source)         );         let r = unsafe { read_at::<EdgeRec>(self.edges, idx as usize) };+        let (target, dist_mm) = if r.escaped() {+            self.escaped_fields(idx)+        } else {+            (+                source.wrapping_add_signed(i32::from(r.target_delta)),+                r.dist_mm(),+            )+        };         Edge {-            target: r.target,-            dist_mm: r.dist_mm,+            target,+            dist_mm,             type_: r.type_,             speed_limit: r.speed_limit,         }     } +    /// `(target, dist_mm)` from the escape table, for an edge whose record carries a+    /// sentinel.+    ///+    /// One load from the block index, then a scan of that block's rows — ~3 of them+    /// at a 0.3% escape rate, usually within one cache line. See [`ESCAPE_BLOCK`].+    ///+    /// A record with a sentinel and no matching row is a corrupt pack that the load-+    /// time checks cannot catch without an O(E) scan. It returns `u32::MAX` as the+    /// target, which every caller already rejects as out of range, so the edge is+    /// skipped rather than followed somewhere arbitrary.+    #[cold]+    fn escaped_fields(&self, idx: u64) -> (u32, u32) {+        let block = (idx / ESCAPE_BLOCK) as usize;+        let lo = unsafe { read_at::<u32>(self.escape_first, block) };+        let hi = unsafe { read_at::<u32>(self.escape_first, block + 1) };+        for r in lo..hi {+            let row = unsafe { read_at::<EscapeRow>(self.escapes, r as usize) };+            if u64::from(row.edge_idx) == idx {+                return (row.target, row.dist_mm);+            }+        }+        debug_assert!(false, "edge {idx} is escaped but has no escape row");+        (u32::MAX, DIST_MM_ESCAPE)+    }+     /// Whether edge `idx` of node `source` points at `want`.     ///-    /// Four call sites scan a node's edge range looking for the one edge that-    /// reaches a given node and never use the target as a value. Once `target` is-    /// stored as a delta they can answer that without widening the field at all, so-    /// the comparison lives here rather than being hand-inlined four times against-    /// whatever the record happens to hold.+    /// Four call sites scan a node's edge range looking for the one edge that reaches+    /// a given node and never use the target as a value. Delegating to [`Graph::edge`]+    /// rather than comparing in delta space keeps the escape handling in one place:+    /// the delta form would have to handle both an escaped record that could still+    /// match and a `want − source` outside `i16` range, and the saving over one+    /// sign-extend and one add is nothing.     #[inline]     pub fn edge_targets(&self, idx: u64, source: u32, want: u32) -> bool {         self.edge(source, idx).target == want@@ -664,14 +922,22 @@ impl Graph {     /// Byte offset of edge `idx`'s name in the string pool, or `None` when it has     /// none.     ///-    /// Separate from [`Edge`] because 62% of a planet's edges are unnamed and this-    /// is read on the instruction-emission path, never in the A* relaxation — so the-    /// field can become a sparse side table without any hot-path cost. Being the-    /// sole reader is what makes that possible.+    /// Separate from [`Edge`] because two thirds of edges are unnamed — 62.3% of+    /// California's, 68.9% of Europe's — and this is read on the+    /// instruction-emission path, never in the A* relaxation. So the field is a+    /// sparse side table: three loads instead of one, for the third of edges that+    /// have a name and nothing at all for the rest.+    ///+    /// Being the *sole* reader is what made that possible. The A* relaxation used to+    /// copy this into the scratchpad on every improving edge — into a field nothing+    /// ever read — and until that store went away no sparse representation was+    /// affordable.     #[inline]     pub fn edge_name_offset(&self, idx: u64) -> Option<u32> {-        let r = unsafe { read_at::<EdgeRec>(self.edges, idx as usize) };-        (r.name_offset != NO_NAME).then_some(r.name_offset)+        if !self.names.contains(idx) {+            return None;+        }+        Some(unsafe { read_at::<u32>(self.name_off, self.names.rank_of(idx) as usize) })     }      /// Real OSM per-lane turn-indication masks for directed edge `idx`, ordered@@ -719,35 +985,6 @@ 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@@ -765,10 +1002,10 @@ impl Graph {     /// stores none.     #[inline]     fn intermediate_range(&self, idx: u64) -> Option<(u64, u32)> {-        if !self.stores_geometry(idx) {+        if !self.geometry.contains(idx) {             return None;         }-        let g = self.geometry_rank(idx);+        let g = self.geometry.rank_of(idx);         let start = self.geometry_offset(g);         let end = self.geometry_offset(g + 1);         Some((start, (end - start) as u32))
scripts/maps/osm_ingest/README.md
diff --git a/scripts/maps/osm_ingest/README.md b/scripts/maps/osm_ingest/README.mdindex fcb07f1bf6..f07a7fb1f6 100644--- a/scripts/maps/osm_ingest/README.md+++ b/scripts/maps/osm_ingest/README.md@@ -129,16 +129,16 @@ changing its reader produces a graph that loads as garbage, which is why  | File | Layout | Reader | |---|---|---|-| `metadata.bin` | `u32 magic "MARG"`, `u32 version 4`, `u64 node_count`, `u64 edge_count` (24 B) | `graph.rs` `GRAPH_MAGIC`/`GRAPH_VERSION` |+| `metadata.bin` | `u32 magic "MARG"`, `u32 version 5`, `u64 node_count`, `u64 edge_count`, `u64 escape_count` (32 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` | `EdgeRec[edge_count]`, **14 bytes**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` | `graph.rs` — widened into `Edge` by `edge()`; `name_offset` reached only through `edge_name_offset()` |+| `edges.bin` | `EdgeRec[edge_count]`, **11 bytes**: `i16 target_delta, u24 dist_mm, u8 type, u8 speed_limit, u32 name_offset`; then padding to an 8-byte boundary, `u32 escape_first[E.div_ceil(1024) + 1]`, and `(u32 edge_idx, u32 target, u32 dist_mm) × escape_count` ascending by `edge_idx` | `graph.rs` — widened into `Edge` by `edge(source, idx)`; `name_offset` reached only through `edge_name_offset()` | | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) × (n + 1)` ascending by `edge_idx`, then the packed `u16` per-lane turn masks. **Sparse**: only lane-bearing edges appear | `graph.rs` `edge_lane_masks` | | `intermediate.bin` | the delta-encoded polyline blob at **offset 0** — per storing edge, `i16 dlat, i16 dlon` per *interior* point — then a trailer: `u64 rank[E.div_ceil(512) + 1]`, `u8 present[E.div_ceil(8)]`, `u64 coarse[G.div_ceil(32) + 1]`, `u16 within[G + 1]`, `u64 G`. `off(g) = coarse[g / 32] + within[g]` where `g = rank(k)` | `graph.rs` `intermediate_range` / `decode_edge_coords` — **mandatory**, see below | | `road_names.bin` | deduped NUL-terminated UTF-8 pool; a name offset is a byte offset | `graph.rs` | | `poi_index.bin` | 14-byte records: `i32 lat_e7, i32 lon_e7, u32 name_off, u16 type`, Morton-sorted | `PoiIndex.kt` | | `poi_names.bin` | same pool convention as `road_names.bin` | `PoiIndex.kt` | -`GRAPH_VERSION` is **4**. Version 1 stored a 16-byte node record and a dense+`GRAPH_VERSION` is **5**. Version 1 stored a 16-byte node record and a dense `u64` offset per edge in both blob files; version 2 fixed that, and version 3 gave `intermediate.bin` a presence bitmap and dropped both endpoints of every stored polyline. See [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and@@ -146,13 +146,17 @@ polyline. See [Getting a planet under 40 GB](#getting-a-planet-under-40-gb) and it. There is no dual-path reader — an older pack is rejected — so the app and the pack have to be updated together, as they already did across the v0→v1 boundary. -Version 4 changes **no layout at all**. It adds `edge_count` to `metadata.bin`, so-that the reader stops deriving it from `edges.bin`'s file size, and with it+Versions 4 and 5 are the next step down, to ~25.8 GB; see+[Getting it under 25](#getting-it-under-25-what-the-census-says). Version 4 changes+**no layout at all**. It adds `edge_count` to `metadata.bin`, so that the reader+stops deriving it from `edges.bin`'s file size, and with it [exact length validation](#every-files-length-is-checked) of every other file. That has to land before any record narrows: the moment the stride changes, a derived `edge_count` changes silently — and it is what sizes `intermediate.bin`'s trailer, so the mis-parse would be of a *different file*. +Version 5 is the narrowing itself.+ ### Every file's length is checked  Every mandatory file's length is now an exact function of the two counts in@@ -160,9 +164,9 @@ Every mandatory file's length is now an exact function of the two counts in  | File | Expected length | |---|---|-| `metadata.bin` | ≥ 24 B, with the right magic and version |+| `metadata.bin` | ≥ 32 B, with the right magic and version | | `nodes.bin` | exactly `(node_count + 1) × 12` |-| `edges.bin` | exactly `edge_count × 14` |+| `edges.bin` | exactly `align_up(edge_count × 11, 8) + (E.div_ceil(1024) + 1) × 4 + escape_count × 12`, with the block index's last entry equal to `escape_count` and every row's `edge_idx < edge_count` | | `lanes.bin` | exactly `4 + (n + 1) × 8 + blob`, from its own header, plus every `edge_idx < edge_count` | | `intermediate.bin` | trailer sized from `edge_count` and `G`, with `coarse[G/32] + within[G] == ` the blob length | @@ -641,9 +645,47 @@ P(|target − source| > n) ≈ c · n^(−1/2) because a level-*k* quadrant boundary produces a delta of order `N / 4^k` and is crossed with probability proportional to `2^k`; substituting `n = N / 4^k` gives `P = (L·√N / W) / √n`, and `L·√N / W` is the ratio of edge length to node spacing —-a local, physical quantity that does not depend on `N`. California gives-**c ≈ 0.546** at the `i16` boundary. `--stats` prints `c` at every power of two so-the shape of the curve is visible, not just one point on it.+a local, physical quantity that does not depend on `N`. `--stats` prints `c` at every+power of two so the shape of the curve is visible, not just one point on it.++**Measured on both California and Europe, and it holds.** Europe is 20.9× the edge+count and 21.6× the node count:++| | California | Europe | ratio |+|---|---|---|---|+| directed edges | 16,785,702 | 350,290,432 | 20.9× |+| nodes | 6,418,361 | 138,635,441 | 21.6× |+| `i16` escape rate | 0.3014% | 0.3132% | **1.04×** |+| `c` at n = 32,767 | 0.5456 | 0.5670 | **1.04×** |+| `u24 dist_mm` escape rate | 0.000989% | 0.000892% | 0.90× |+| named edges | 37.72% | 31.15% | 0.83× |+| max out-degree | 24 | **77** | 3.2× |+| degree-0 nodes | 0.0231% | 0.0270% | 1.17× |+| max `dist_mm` | 61.5 km | **2,979 km** | 48× |++`c` moves by 4% across a 21× change in scale, well inside the 1.5× the design needed,+so the planet escape rate is predictable and the escape table is ~40 MB rather than+anything that matters. Two other columns are worth more than they look:++* **The named fraction *falls* with scale** (37.7% → 31.1%), so making `name_offset`+  sparse saves more on a planet than California suggests, not less.+* **Max out-degree triples** (24 → 77). Any future per-node `u8 degree` field would+  still fit, but not by the margin California implied — which is why one is not+  worth adding without a writer pre-pass that widens the field if it overflows.++### The single most useful thing the census found++Europe has an edge **2,979 km long**. California's longest is 61.5 km.++That number kills the option v3 considered and this work rejected: `dist_mm` as a+`u24` counting **centimetres**, which needs no escape table because 2^24 cm is+167.77 km. It would have been silently, catastrophically wrong on Europe — the value+wraps — and it quantises all 1.07 G edges to buy that. Millimetres plus a shared+escape table keeps every distance *exact* and costs 3,126 rows on Europe: 37 KB.++It also vindicates merging the two escape tables. The `dist_mm` escape rate is the+least transferable number in the whole census, and merging makes it irrelevant to+the design: a hundredfold miss rides along in the table `target` already needed.  ### Hilbert was tried, and loses @@ -685,6 +727,151 @@ verified against instead of the ~35 K vertices 999 sampled routes happen to touc `route_diff` also gained a `bench` mode, so the phases that are gated on latency rather than correctness have a baseline to be gated against. +Version 4's own gate: every data file byte-identical to the v3 pack on both collapse+paths, `metadata.bin` 16 B → 24 B, and `route_diff report` byte-identical to what+the *v3 binary* produced from the *v3 pack* — a direct reader-equivalence check+across the change rather than a comparison against itself.++### Version 5: the 11-byte record++```text+[ EdgeRec[E] ]                     11 B: i16 target_delta, u24 dist_mm,+                                         u8 type_, u8 speed_limit, u32 name_offset+[ pad to an 8-byte boundary ]+[ u32 escape_first[E.div_ceil(1024) + 1] ]+[ { u32 edge_idx, u32 target, u32 dist_mm } × escape_count ]   ascending by edge_idx+```++`target` becomes a signed delta from the edge's own source and `dist_mm` a `u24`,+so 14 bytes become 11 — **3.22 GB** of a planet, less the escape table. Every value+stays exact.++**One escape table, not two.** `target_delta == i16::MIN` *or* `dist_mm == 0xFFFFFF`+means both fields come from the escape row. Two sentinels with two tables would cost+two branches in the A* relaxation, two metadata fields and two sets of off-by-one+risk, to keep a 39 MB table apart from an 85 KB one. Merging costs ~13 MB and+removes half the code — and it makes the `dist_mm` escape rate, the least+transferable number in the census, irrelevant to the design: collapsed chains in+Siberia will be far longer than California's, and a hundredfold miss just rides+along in the same table.++**A block index, not a binary search.** The inline sentinel already *is* the+presence bit — it is in a register that was just loaded — so a v3-style presence+bitmap would spend 134 MB duplicating it. All that is missing is edge index → row,+and `u32 escape_first[E/1024 + 1]` is 4.2 MB: one load from a largely+cache-resident array, then a scan of the ~3 rows a block holds, usually one cache+line. A binary search over 3.24 M rows would be 12–15 misses. `lanes.bin` does+binary-search its sparse index and its doc comment justifies that by being "called+once per maneuver rather than per edge"; `target` is read on every relaxation, so+that precedent does not transfer.++**Field order is load-bearing.** The four fields the A* relaxation reads sit in+bytes 0..7, so one 8-byte load covers all of them, and `name_offset` is last. The+`u24` is assembled from three bytes rather than loaded as a masked `u32`, so no read+can run past the array — and the array is padded to 8 bytes anyway, which keeps the+block index naturally aligned whatever `E` is.++Shrinking the record is a locality *win*, not a cost: adjacency records per 64-byte+line goes 4.6 → 5.8, so the relaxation should get slightly faster rather than+slower.++**Measured on California:** `edges.bin` 234,999,828 → 185,316,836 bytes on the+reference path (−21.1%), with 50,711 escape rows (0.302% of 16,785,702 edges); the+whole pack 458,981,307 → 409,298,323 (−10.8%). The per-element dump is identical —+**0 of 16,785,702 edges and 0 of 6,418,362 node records differ**, and the same on the+within-way path's 18,033,545 edges — `report` is still byte-identical to the v3+binary's, and `compare` and `geometry` do not move a digit.++| file | v3/v4 | v5 | basis |+|---|---|---|---|+| `metadata.bin` | 24 B | 32 B | `escape_count` |+| `edges.bin` | 15.04 GB | **11.86 GB** | 11 B × E + 4.2 MB index + 40 MB rows |+| everything else | | unchanged | |+| **planet total** | **~29.0 GB** | **~25.8 GB** | |++**Seven synthetic tests cover what California cannot contain**: deltas at 0, ±1,+±32766, ±32767, ±32768, −32769 and +40000; `dist_mm` at 0, 1, `0xFFFFFE`,+`0xFFFFFF`, `0x1000000` and `u32::MAX`; an edge that fails both tests at once+(one row, not two); escapes at edge 0 and edge E−1; a pack with no escapes at all,+where the padding is the only thing keeping a wide load in bounds; and escape rows+on both sides of every block boundary at 1023/1024/1025/2047/2048/2049. The+encoder and the decoder are exercised as a pair, directly, because putting two nodes+exactly 32,768 apart in Morton order would mean choosing coordinates for the 32,767+nodes in between.++**`--rounds 1` vs `3` vs `17` stays byte-identical on all six files, on both collapse+paths.** That is the strongest check the escape table gets: round boundaries move+which edges each pass collects, which of them escape, and where the block index's+prefix counts land — and none of it reaches the file.++### Version 6: `name_offset` becomes sparse++```text+[ EdgeRec[E] ]                     7 B: i16 target_delta, u24 dist_mm,+                                        u8 type_, u8 speed_limit+[ pad ][ u32 escape_first[..] ][ EscapeRow[escape_count] ][ pad ]+[ u64 name rank[E.div_ceil(512) + 1] ][ u8 name present[E.div_ceil(8)] ]+[ u32 name_off[named_edges] ]+```++Two thirds of edges have no name — **62.28%** of California's, **68.85%** of+Europe's — so a dense `u32` per edge spent four bytes on a sentinel more often than+on an offset. A presence bitmap plus a rank index makes absence free and costs the+named third four bytes each: **−2.53 GB** of a planet.++**It is a presence bitmap over the existing byte offset, not a dense name id.**+Adding an id space would get a further 0.41 GB, but it means changing+`NamePool::intern`'s return type, and `poi_build.rs` is a second consumer that has to+keep byte offsets for `PoiIndex.kt`. Recoverable later without touching+`poi_build.rs` if that 0.41 GB is ever wanted.++**The rank/select pair is now one type, used twice.** `intermediate.bin` has had a+presence bitmap and rank index since v3, and this is the same question asked of a+different field, so `EdgeBitmap` in the reader and `PresenceBitmap` in the writer+replace what would have been two transcriptions of the same eight lines. The block+size stays 64 bytes — 512 edges, one cache line — so a rank is one `u64` load plus at+most eight `popcount`s.++**Why this and not sparse `speed_limit`.** `speed_limit` is zero on 91.76% of edges+and making it sparse would save 0.84 GB, but it is read in the A* relaxation, up to+25 M expansions × degree per route, from a record already in L1. A rank probe there+is not worth 0.84 GB. Names are read when an *instruction* is emitted — once per+maneuver, not once per edge — which is what makes three loads instead of one+affordable.++**The prerequisite was deleting a dead store.** The A* relaxation used to copy+`name_offset` into the scratchpad on every improving edge, into an `Entry` field+nothing ever read; the same was true of `last_type`. Until those went, `name_offset`+was on the hot path and no sparse form was affordable. Removing them also took+`Entry` from 24 bytes to 20, in the structure the router touches most.++**Measured on California:** `edges.bin` 185,316,836 → 145,857,713 bytes on the+reference path, so the whole pack is 458,981,307 → 369,839,208 — **−19.4% against+v3**. 6,330,795 of 16,785,702 edges are named (37.72%). The per-element dump is+identical again — **0 of 16,785,702 edges and 0 of 6,418,362 node records differ,+including `name_offset` for every edge**, which is the phase where that dump earns+its keep.++The 145,857,713 breaks down exactly as the reader computes it: 117,499,920 of padded+records, 65,576 of escape block index, 608,532 of escape rows, 4 of padding,+2,360,501 of name bitmap and rank, and 25,323,180 of name offsets.++| file | v3 | v5 | v6 | basis |+|---|---|---|---|---|+| `metadata.bin` | 16 B | 32 B | 40 B | `named_edges` |+| `edges.bin` | 15.04 GB | 11.86 GB | **9.33 GB** | 7 B × E + 0.15 GB bitmap + 1.62 GB offsets |+| everything else | | | unchanged | |+| **planet total** | **~29.0 GB** | **~25.8 GB** | **~23.3 GB** | |++That planet column uses California's 37.72% named fraction. At Europe's 31.15% the+offsets are 1.34 GB rather than 1.62 GB, so the real figure should come in nearer+**23.0 GB**.++**Four synthetic tests cover the sparse table's boundaries**: a name at edge 0 and at+edge E−1; names either side of the 512-edge rank-block boundary and either side of+1024, with a distinct offset per named edge so a rank off by one reads a visibly+wrong value; a pack where no edge is named; and one where every edge is.+ ## Build-time memory  The output has fitted a planet for a while; the build did not. California peaked
scripts/maps/osm_ingest/src/bin/road_graph.rs
diff --git a/scripts/maps/osm_ingest/src/bin/road_graph.rs b/scripts/maps/osm_ingest/src/bin/road_graph.rsindex 1af2b9d9e1..08618a6346 100644--- a/scripts/maps/osm_ingest/src/bin/road_graph.rs+++ b/scripts/maps/osm_ingest/src/bin/road_graph.rs@@ -129,6 +129,15 @@ fn main() -> ExitCode {                  {} defer to a twin",                 stats.intermediate_bytes, stats.geometry_edges, stats.reversed_edges             );+            println!(+                "edges.bin: {} byte(s), {} edge(s) needed the escape table ({:.4}%), \+                 {} named ({:.2}%)",+                stats.edges_bytes,+                stats.escape_count,+                stats.escape_count as f64 / stats.edge_count.max(1) as f64 * 100.0,+                stats.named_edges,+                stats.named_edges as f64 / stats.edge_count.max(1) as f64 * 100.0+            );             println!("Peak RSS: {}", osm_ingest::mem::peak_rss_report());             println!("Wrote {}", out_dir.display());             if want_stats {
scripts/maps/osm_ingest/src/graph_build.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build.rs b/scripts/maps/osm_ingest/src/graph_build.rsindex b72c8e4998..01efea5645 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -7,14 +7,14 @@ //! //! | File | Layout | //! |---|---|-//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count`, `u64 edge_count` (24 B) |+//! | `metadata.bin` | `u32 magic "MARG"`, `u32 version`, `u64 node_count`, `u64 edge_count`, `u64 escape_count`, `u64 named_edges` (40 B) | //! | `nodes.bin` | `NodeRec[node_count + 1]`, **12 bytes each**: `i32 lat_e7, i32 lon_e7, u32 edge_ptr`; the trailing sentinel's `edge_ptr` is `edge_count` |-//! | `edges.bin` | `Edge[edge_count]`, **14 bytes each**: `u32 target, u32 dist_mm, u32 name_offset, u8 type, u8 speed_limit` |+//! | `edges.bin` | `EdgeRec[edge_count]`, **7 bytes each**: `i16 target_delta, u24 dist_mm, u8 type, u8 speed_limit`; then padding, `u32 escape_first[E.div_ceil(1024) + 1]`, `(u32 edge_idx, u32 target, u32 dist_mm) x escape_count`, padding, and the sparse name table — a presence bitmap with a rank index plus `u32 name_off[named_edges]`. See [`EdgeFile`] | //! | `lanes.bin` | `u32 n`, then `(u32 edge_idx, u32 blob_byte_off) x (n + 1)` ascending by `edge_idx`, then the packed `u16` mask blob — **sparse**, only lane-bearing edges appear | //! | `intermediate.bin` | the delta-encoded polyline blob ([`crate::geom`]) at offset 0, then a trailer: `u64 rank[..]`, `u8 present[..]` (one bit per directed edge), `u64 coarse[..]`, `u16 within[..]` over the *geometry* edges, and `u64 G`. See [`GeomFile`] | //! | `road_names.bin` | deduped NUL-terminated string pool | //!-//! Every file's length is now an exact function of `metadata.bin`'s two counts, and+//! Every file's length is now an exact function of `metadata.bin`'s counts, and //! the reader checks each one. `road_names.bin` is the exception: it is a byte pool //! with no count of its own, and reads into it are bounds-checked instead. //!@@ -75,11 +75,13 @@ pub const BITSET_SIZE: u64 = 20_000_000_000;  /// `"MARG"` little-endian — `GRAPH_MAGIC` in `graph.rs`. const GRAPH_MAGIC: u32 = 0x4752_414D;-/// Version 4 adds `edge_count` to `metadata.bin`. No layout changed; the point is-/// that the reader stops deriving the edge count from `edges.bin`'s *length*, which-/// the next round of record narrowing would silently invalidate — and which sizes-/// `intermediate.bin`'s trailer.-const GRAPH_VERSION: u32 = 4;+/// Version 5 narrows an `edges.bin` record from 14 bytes to 11: `target` becomes an+/// `i16` delta from the edge's source and `dist_mm` a `u24`, with one escape table+/// behind the record array for the 0.3% that do not fit. Planet goes ~29.0 -> ~25.8+/// GB, and every value stays *exact*.+/// Version 6 moves `name_offset` out of the record into a sparse side table — two+/// thirds of edges have no name — taking the record to 7 bytes and planet to ~23.3 GB.+const GRAPH_VERSION: u32 = 6;  /// Geometry edges per coarse block in `intermediate.bin`'s two-level offset table /// — `INTERMEDIATE_BLOCK` in `graph.rs`, and the two must agree.@@ -127,8 +129,8 @@ const UNNAMED_STOP: &[u8] = b"OSM_STOP"; /// Sentinel in a narrowed `target` delta meaning "this record's `target` and /// `dist_mm` both live in the escape table". ///-/// A future `edges.bin` record stores `target` as an `i16` delta from the edge's-/// own source rather than absolutely, which is only possible because the nodes are+/// An `edges.bin` record stores `target` as an `i16` delta from the edge's own+/// source rather than absolutely, which is only possible because the nodes are /// sorted by a space-filling curve and an edge is short: [`Census`] measures how /// often that fails. `i16::MIN` is reserved rather than used, so the representable /// range is symmetric at ±32767.@@ -142,11 +144,29 @@ const TARGET_DELTA_ESCAPE: i16 = i16::MIN; /// extra table. const DIST_MM_ESCAPE: u32 = 0xFF_FFFF; -/// `target - source` when it fits the `i16` a narrowed record stores, `None` when-/// the edge has to escape.+/// Bytes per `edges.bin` record — `EdgeRec` in `graph.rs`, and an on-disk contract+/// with it: `i16 target_delta, u24 dist_mm, u8 type_, u8 speed_limit`. `name_offset`+/// is not a field; it is a sparse side table behind the record array.+const EDGE_REC_BYTES: u64 = 7;++/// Directed edges per entry of `edges.bin`'s escape block index — `ESCAPE_BLOCK` in+/// `graph.rs`, and the two must agree.+const ESCAPE_BLOCK: u64 = 1024;++/// Alignment each section of a multi-section file starts on — `SECTION_ALIGN` in+/// `graph.rs`.+const SECTION_ALIGN: u64 = 8;++/// Round `n` up to the next multiple of `align`, which must be a power of two.+const fn align_up(n: u64, align: u64) -> u64 {+    (n + align - 1) & !(align - 1)+}++/// `target - source` when it fits the `i16` a record stores, `None` when the edge+/// has to escape. ///-/// This is *the* escape predicate: [`Census`] counts with it and the encoder will-/// narrow with it, so the two cannot disagree by one and produce a pack that loads+/// This is *the* escape predicate: [`Census`] counts with it and [`EdgeFile::push`]+/// narrows with it, so the two cannot disagree by one and produce a pack that loads /// while reading the wrong node. #[inline] fn target_delta(source: u32, target: u32) -> Option<i16> {@@ -276,6 +296,11 @@ pub struct Stats {     /// Edges deferring to their twin's polyline.     pub reversed_edges: u64,     pub intermediate_bytes: u64,+    pub edges_bytes: u64,+    /// Edges whose `target` or `dist_mm` needed the escape table.+    pub escape_count: u64,+    /// Edges with a name at all, i.e. the length of the sparse name table.+    pub named_edges: u64,     /// What a narrower record would cost. Always collected — it is a handful of     /// adds per edge — and reported by `--stats`.     pub census: Census,@@ -713,6 +738,9 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats>         geometry_edges: written.geometry_edges,         reversed_edges: written.reversed_edges,         intermediate_bytes: written.intermediate_bytes,+        edges_bytes: written.edges_bytes,+        escape_count: written.escape_count,+        named_edges: written.named_edges,         census: written.census,     }) }@@ -1420,6 +1448,9 @@ struct Written {     geometry_edges: u64,     reversed_edges: u64,     intermediate_bytes: u64,+    edges_bytes: u64,+    escape_count: u64,+    named_edges: u64,     census: Census, } @@ -1464,7 +1495,7 @@ fn write_graph(     println!("Writing {edge_count} edge(s) in {rounds} round(s)...");      let mut nodes_out = BufWriter::new(create(&out_dir.join("nodes.bin"))?);-    let mut edges_out = BufWriter::new(create(&out_dir.join("edges.bin"))?);+    let mut edges_out = EdgeFile::create(out_dir, "edges.bin", edge_count)?;      // `intermediate.bin` puts its blob at offset 0 and everything that indexes it     // in a trailer, so it is written strictly forwards with no scratch file at all@@ -1598,7 +1629,7 @@ fn write_graph(                     inter.skip();                 } -                write_edge(&mut edges_out, e, type_).map_err(io_err)?;+                edges_out.push(e, type_)?;                 if e.lane_count > 0 && e.lane_off != NO_LANES {                     let start = e.lane_off as usize;                     lane_bytes.clear();@@ -1624,7 +1655,9 @@ fn write_graph(     // node v's edge range.     write_node(&mut nodes_out, 0, 0, edge_ptr as u32).map_err(io_err)?;     nodes_out.flush().map_err(io_err)?;-    edges_out.flush().map_err(io_err)?;+    let escape_count = edges_out.escapes.len() as u64;+    let named_edges = edges_out.name_offsets.len() as u64;+    let edges_bytes = edges_out.finish(edge_count)?;      let intermediate_bytes = inter.finish(edge_count)?;     lanes.finish()?;@@ -1637,6 +1670,8 @@ fn write_graph(     meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;     meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;     meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;+    meta.write_all(&escape_count.to_le_bytes()).map_err(io_err)?;+    meta.write_all(&named_edges.to_le_bytes()).map_err(io_err)?;     meta.flush().map_err(io_err)?;      Ok(Written {@@ -1644,6 +1679,9 @@ fn write_graph(         geometry_edges,         reversed_edges,         intermediate_bytes,+        edges_bytes,+        escape_count,+        named_edges,         census,     }) }@@ -1732,7 +1770,7 @@ struct GeomFile {     out: BufWriter<File>,     blob_len: u64,     /// One bit per directed edge, sized up front from the edge count.-    present: Vec<u8>,+    present: PresenceBitmap,     coarse: Vec<u64>,     within: Vec<u16>,     /// Blob offset of the first geometry edge in the block being filled, i.e. the@@ -1749,8 +1787,7 @@ impl GeomFile {     /// `geometry_edges` store a polyline. The reader sizes it the same way, from     /// `edges.bin`'s length and the final `u64`.     fn trailer_bytes(edge_count: u64, geometry_edges: u64) -> u64 {-        (edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8-            + edge_count.div_ceil(8)+        PresenceBitmap::bytes(edge_count)             + (geometry_edges.div_ceil(INTERMEDIATE_BLOCK) + 1) * 8             + (geometry_edges + 1) * 2             + 8@@ -1762,7 +1799,7 @@ impl GeomFile {             out: BufWriter::new(create(&path)?),             path,             blob_len: 0,-            present: vec![0u8; edge_count.div_ceil(8) as usize],+            present: PresenceBitmap::new(edge_count),             coarse: Vec::new(),             within: Vec::new(),             block_base: 0,@@ -1785,7 +1822,7 @@ impl GeomFile {             !bytes.is_empty(),             "an interior-only blob of no bytes is the chord, which needs no presence bit"         );-        self.present[(self.pushed / 8) as usize] |= 1u8 << (self.pushed % 8);+        self.present.set(self.pushed);         self.push_entry();         self.out.write_all(bytes).map_err(io_err)?;         self.blob_len += bytes.len() as u64;@@ -1830,39 +1867,253 @@ impl GeomFile {             self.coarse.push(self.blob_len);         } -        // Rank over the presence bitmap, laid out exactly like `Bitset`'s: set-        // bits before each block, with the total appended. That total is `G`,-        // which is what lets the reader cross-check the two halves of the trailer-        // against each other.-        let blocks = self.present.len().div_ceil(RANK_BLOCK_BYTES);-        let mut rank = Vec::with_capacity(blocks + 1);+        // The presence bitmap and its rank index, the same pair `edges.bin`'s names+        // use. The rank total is `G`, which is what lets the reader cross-check the+        // two halves of the trailer against each other.+        let total = self.present.write(&mut self.out)?;+        debug_assert_eq!(total, self.stored, "the presence bitmap disagrees with G");+        for c in &self.coarse {+            self.out.write_all(&c.to_le_bytes()).map_err(io_err)?;+        }+        for w in &self.within {+            self.out.write_all(&w.to_le_bytes()).map_err(io_err)?;+        }+        self.out.write_all(&self.stored.to_le_bytes()).map_err(io_err)?;+        self.out.flush().map_err(io_err)?;++        let want = self.blob_len + GeomFile::trailer_bytes(edge_count, self.stored);+        let got = std::fs::metadata(&self.path)+            .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?+            .len();+        if got != want {+            return Err(Error(format!(+                "{} came out {got} byte(s) long, not the {want} the reader will compute",+                self.path.display()+            )));+        }+        Ok(want)+    }+}++/// A presence bitmap over the directed edges, built in memory and written with a+/// rank index in front of it.+///+/// The writer half of `graph.rs`'s `EdgeBitmap`, and an on-disk contract with it:+///+/// ```text+/// [ 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+/// ```+///+/// Used twice, for the same reason the reader's is: `intermediate.bin`'s stored+/// polylines and `edges.bin`'s names are both per-edge fields most edges do not have.+struct PresenceBitmap {+    bits: Vec<u8>,+    /// Bits set so far, i.e. the length of the side table this indexes.+    set: u64,+}++impl PresenceBitmap {+    /// Byte size of the rank index plus the bitmap for `edge_count` edges. The reader+    /// sizes them the same way.+    fn bytes(edge_count: u64) -> u64 {+        (edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8 + edge_count.div_ceil(8)+    }++    fn new(edge_count: u64) -> PresenceBitmap {+        PresenceBitmap {+            bits: vec![0u8; edge_count.div_ceil(8) as usize],+            set: 0,+        }+    }++    /// Mark edge `idx` as having one. Must be called in ascending `idx`, which every+    /// caller satisfies because the rounds ascend and each round writes its edges in+    /// index order.+    fn set(&mut self, idx: u64) {+        debug_assert!(+            self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) == 0,+            "edge {idx} was already marked"+        );+        self.bits[(idx / 8) as usize] |= 1u8 << (idx % 8);+        self.set += 1;+    }++    /// Write the rank index then the bitmap. Returns the number of set bits, which is+    /// the rank index's appended total and the length the side table must have.+    fn write<W: Write>(&self, out: &mut W) -> Result<u64> {+        // Set bits before each block, with the total appended. That total is what+        // lets the reader tie the index to the table it indexes.+        let blocks = self.bits.len().div_ceil(RANK_BLOCK_BYTES);         let mut total = 0u64;         for b in 0..blocks {-            rank.push(total);+            out.write_all(&total.to_le_bytes()).map_err(io_err)?;             let start = b * RANK_BLOCK_BYTES;-            let end = (start + RANK_BLOCK_BYTES).min(self.present.len());-            total += self.present[start..end]+            let end = (start + RANK_BLOCK_BYTES).min(self.bits.len());+            total += self.bits[start..end]                 .iter()                 .map(|byte| u64::from(byte.count_ones()))                 .sum::<u64>();         }-        rank.push(total);-        debug_assert_eq!(total, self.stored, "the presence bitmap disagrees with G");+        out.write_all(&total.to_le_bytes()).map_err(io_err)?;+        out.write_all(&self.bits).map_err(io_err)?;+        debug_assert_eq!(total, self.set, "the bitmap disagrees with its own counter");+        Ok(total)+    }+}++/// `edges.bin`, in five sections:+///+/// ```text+/// [ EdgeRec[E] ]                     7 B: i16 target_delta, u24 dist_mm,+///                                         u8 type_, u8 speed_limit+/// [ pad to SECTION_ALIGN ]+/// [ u32 escape_first[E.div_ceil(1024) + 1] ]   first escape row of each block+/// [ { u32 edge_idx, u32 target, u32 dist_mm } x escapes ]   ascending by edge_idx+/// [ pad to SECTION_ALIGN ]+/// [ u64 name rank[E.div_ceil(512) + 1] ][ u8 name present[E.div_ceil(8)] ]+/// [ u32 name_off[named_edges] ]                indexed by rank in the bitmap+/// ```+///+/// `target` is a signed delta from the edge's own source, which is affordable only+/// because the nodes are sorted by a space-filling curve: 99.699% of California's+/// deltas fit an `i16`. `dist_mm` is a `u24`, exact below 16.78 km, which is+/// 99.999% of edges. Either field's sentinel means *both* come from one escape row,+/// so the reader takes one branch and the table stays single.+///+/// `name_offset` is sparse rather than a field, because two thirds of edges have no+/// name — 62.3% of California's, 68.9% of Europe's — and it is read when an+/// instruction is emitted, never in the A* relaxation.+///+/// # Why the tables come last, and why they fit in memory+///+/// Neither the escape count nor the named-edge count is known until the final round+/// has run, so a reserved prefix cannot be sized. But unlike `intermediate.bin` the+/// record array is a fixed stride, so this needs no trailer to be self-locating: the+/// reader computes all five offsets from `metadata.bin`'s counts. The escape rows+/// accumulate in memory — 39 MB at planet scale against `edges.bin`'s 8.6 GB — as do+/// the name offsets (1.6 GB, the largest of them) and the bitmap (134 MB).+struct EdgeFile {+    path: PathBuf,+    out: BufWriter<File>,+    /// `(edge_idx, target, dist_mm)` for the edges a record cannot hold, in+    /// ascending `edge_idx` — which is the order they are pushed in, because the+    /// rounds ascend and each round writes its edges in index order.+    escapes: Vec<(u32, u32, u32)>,+    /// Which edges have a name, and the pool offsets of the ones that do, in the+    /// same order.+    named: PresenceBitmap,+    name_offsets: Vec<u32>,+    /// Directed edges written so far, which is the index the next call describes.+    pushed: u64,+} -        for r in &rank {-            self.out.write_all(&r.to_le_bytes()).map_err(io_err)?;+impl EdgeFile {+    /// Byte size of the whole file. The reader computes it the same way, from+    /// `metadata.bin`.+    fn total_bytes(edge_count: u64, escapes: u64, named: u64) -> u64 {+        let rows = align_up(edge_count * EDGE_REC_BYTES, SECTION_ALIGN)+            + (edge_count.div_ceil(ESCAPE_BLOCK) + 1) * 4+            + escapes * 12;+        align_up(rows, SECTION_ALIGN) + PresenceBitmap::bytes(edge_count) + named * 4+    }++    fn create(dir: &Path, name: &str, edge_count: u64) -> Result<EdgeFile> {+        let path = dir.join(name);+        Ok(EdgeFile {+            out: BufWriter::new(create(&path)?),+            path,+            escapes: Vec::new(),+            named: PresenceBitmap::new(edge_count),+            name_offsets: Vec::new(),+            pushed: 0,+        })+    }++    /// Write one directed edge's record, escaping it if either field will not fit and+    /// recording its name if it has one.+    fn push(&mut self, e: &TmpEdge, type_: u8) -> Result<()> {+        let (delta, dist) = match target_delta(e.source, e.target) {+            Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm),+            // Both sentinels, not just the one that failed: the reader tests either,+            // so writing both keeps the two tests in agreement whichever field a+            // future caller happens to have in hand.+            _ => {+                let idx = cap_u32("escaped edge index", self.pushed)?;+                self.escapes.push((idx, e.target, e.dist_mm));+                (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)+            }+        };+        self.out.write_all(&delta.to_le_bytes()).map_err(io_err)?;+        self.out.write_all(&dist.to_le_bytes()[..3]).map_err(io_err)?;+        self.out.write_all(&[type_, e.speed_limit]).map_err(io_err)?;+        if e.name_offset != NO_NAME {+            self.named.set(self.pushed);+            self.name_offsets.push(e.name_offset);         }-        self.out.write_all(&self.present).map_err(io_err)?;-        for c in &self.coarse {-            self.out.write_all(&c.to_le_bytes()).map_err(io_err)?;+        self.pushed += 1;+        Ok(())+    }++    /// Pad to the section boundary, then append the block index, the escape rows, the+    /// name bitmap and the name offsets. Returns the finished file's size.+    fn finish(mut self, edge_count: u64) -> Result<u64> {+        if self.pushed != edge_count {+            return Err(Error(format!(+                "{} holds {} edge(s), not the {edge_count} the pack is sized for",+                self.path.display(),+                self.pushed+            )));         }-        for w in &self.within {-            self.out.write_all(&w.to_le_bytes()).map_err(io_err)?;+        let mut at = edge_count * EDGE_REC_BYTES;+        at = self.pad_to(at)?;++        // `escape_first[b]` is the index of the first row in block `b`, i.e. the+        // count of rows below `b * ESCAPE_BLOCK`. The rows ascend, so one walk over+        // them fills the whole array, and the final entry is the row total — which is+        // what lets the reader tie the index to the section it indexes.+        let blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;+        let mut row = 0usize;+        for b in 0..blocks {+            let limit = b * ESCAPE_BLOCK;+            while row < self.escapes.len() && u64::from(self.escapes[row].0) < limit {+                row += 1;+            }+            self.out.write_all(&(row as u32).to_le_bytes()).map_err(io_err)?;+        }+        if row != self.escapes.len() {+            return Err(Error(format!(+                "{}: the block index reached row {row} of {}, so a row is past the \+                 last block",+                self.path.display(),+                self.escapes.len()+            )));+        }+        at += blocks * 4;++        for (idx, target, dist_mm) in &self.escapes {+            self.out.write_all(&idx.to_le_bytes()).map_err(io_err)?;+            self.out.write_all(&target.to_le_bytes()).map_err(io_err)?;+            self.out.write_all(&dist_mm.to_le_bytes()).map_err(io_err)?;+        }+        at += self.escapes.len() as u64 * 12;+        self.pad_to(at)?;++        let named = self.named.write(&mut self.out)?;+        if named != self.name_offsets.len() as u64 {+            return Err(Error(format!(+                "{}: the name bitmap has {named} bit(s) set but {} offset(s) were \+                 collected",+                self.path.display(),+                self.name_offsets.len()+            )));+        }+        for off in &self.name_offsets {+            self.out.write_all(&off.to_le_bytes()).map_err(io_err)?;         }-        self.out.write_all(&self.stored.to_le_bytes()).map_err(io_err)?;         self.out.flush().map_err(io_err)?; -        let want = self.blob_len + GeomFile::trailer_bytes(edge_count, self.stored);+        let want = EdgeFile::total_bytes(edge_count, self.escapes.len() as u64, named);         let got = std::fs::metadata(&self.path)             .map_err(|e| Error(format!("cannot stat {}: {e}", self.path.display())))?             .len();@@ -1874,6 +2125,14 @@ impl GeomFile {         }         Ok(want)     }++    /// Write zeroes up to the next section boundary, returning the new offset.+    fn pad_to(&mut self, at: u64) -> Result<u64> {+        let aligned = align_up(at, SECTION_ALIGN);+        let zeroes = [0u8; SECTION_ALIGN as usize];+        self.out.write_all(&zeroes[..(aligned - at) as usize]).map_err(io_err)?;+        Ok(aligned)+    } }  /// `lanes.bin`, as a sparse index: `[ u32 n ][ (u32 edge_idx, u32 off) x (n + 1) ]`@@ -1989,13 +2248,6 @@ fn write_node<W: Write>(     out.write_all(&edge_ptr.to_le_bytes()) } -fn write_edge<W: Write>(out: &mut W, e: &TmpEdge, type_: u8) -> std::io::Result<()> {-    out.write_all(&e.target.to_le_bytes())?;-    out.write_all(&e.dist_mm.to_le_bytes())?;-    out.write_all(&e.name_offset.to_le_bytes())?;-    out.write_all(&[type_, e.speed_limit])-}- fn create(path: &Path) -> Result<File> {     File::create(path).map_err(|e| Error(format!("cannot write {}: {e}", path.display()))) }@@ -2103,15 +2355,145 @@ mod tests {         )     } +    /// A `u64` field of `metadata.bin` at byte `at`.+    fn meta_u64(o: &Outputs, at: usize) -> u64 {+        u64::from_le_bytes(o.meta[at..at + 8].try_into().unwrap())+    }++    /// `edges.bin`, located and decoded exactly as `graph.rs::load` does: the record+    /// array sized from `edge_count`, padding to the section boundary, the escape+    /// block index and the rows.+    ///+    /// Every accessor below is a literal mirror of the device's, which is what makes+    /// these contract tests rather than a re-read of our own tables.+    struct Edges<'a> {+        bytes: &'a [u8],+        edge_count: u64,+        first_at: usize,+        rows_at: usize,+        /// The name presence bitmap's rank index, then the bitmap, then the offsets.+        name_rank_at: usize,+        name_present_at: usize,+        name_off_at: usize,+        named_edges: u64,+    }++    impl<'a> Edges<'a> {+        fn new(+            bytes: &'a [u8],+            edge_count: u64,+            escape_count: u64,+            named_edges: u64,+        ) -> Edges<'a> {+            let first_at = align_up(edge_count * EDGE_REC_BYTES, SECTION_ALIGN) as usize;+            let blocks = edge_count.div_ceil(ESCAPE_BLOCK) + 1;+            let rows_at = first_at + (blocks * 4) as usize;+            let name_rank_at =+                align_up(rows_at as u64 + escape_count * 12, SECTION_ALIGN) as usize;+            let rank_bytes = ((edge_count.div_ceil(RANK_BLOCK_BITS) + 1) * 8) as usize;+            Edges {+                bytes,+                edge_count,+                first_at,+                rows_at,+                name_rank_at,+                name_present_at: name_rank_at + rank_bytes,+                name_off_at: name_rank_at + PresenceBitmap::bytes(edge_count) as usize,+                named_edges,+            }+        }++        fn of(o: &'a Outputs) -> Edges<'a> {+            Edges::new(&o.edges, meta_u64(o, 16), meta_u64(o, 24), meta_u64(o, 32))+        }++        /// What the reader will compute the file's length to be.+        fn total_bytes(&self) -> usize {+            self.name_off_at + (self.named_edges * 4) as usize+        }++        /// True when edge `idx` has a name, from the presence bitmap.+        fn named(&self, idx: u64) -> bool {+            self.bytes[self.name_present_at + (idx / 8) as usize] & (1u8 << (idx % 8)) != 0+        }++        /// Edge `idx`'s rank in the name bitmap, computed as `graph.rs` does: the+        /// block's stored count plus a popcount of the bytes below it.+        fn name_rank(&self, idx: u64) -> u64 {+            let byte = (idx / 8) as usize;+            let block = byte / RANK_BLOCK_BYTES;+            let at = self.name_rank_at + block * 8;+            let mut n = u64::from_le_bytes(self.bytes[at..at + 8].try_into().unwrap());+            for b in block * RANK_BLOCK_BYTES..byte {+                n += u64::from(self.bytes[self.name_present_at + b].count_ones());+            }+            let partial = self.bytes[self.name_present_at + byte] & ((1u8 << (idx % 8)) - 1);+            n + u64::from(partial.count_ones())+        }++        /// Edge `idx`'s name offset, or [`NO_NAME`] when it has none.+        fn name_offset(&self, idx: u64) -> u32 {+            if !self.named(idx) {+                return NO_NAME;+            }+            let at = self.name_off_at + (self.name_rank(idx) * 4) as usize;+            u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap())+        }++        fn escape_first(&self, block: u64) -> u32 {+            let at = self.first_at + (block * 4) as usize;+            u32::from_le_bytes(self.bytes[at..at + 4].try_into().unwrap())+        }++        /// `(edge_idx, target, dist_mm)` of escape row `r`.+        fn row(&self, r: u64) -> (u32, u32, u32) {+            let b = &self.bytes[self.rows_at + (r * 12) as usize..];+            (+                u32::from_le_bytes(b[0..4].try_into().unwrap()),+                u32::from_le_bytes(b[4..8].try_into().unwrap()),+                u32::from_le_bytes(b[8..12].try_into().unwrap()),+            )+        }++        /// `(target, dist_mm, name_offset, type_, speed_limit)` of edge `idx`, whose+        /// source is `source` — decoded as `Graph::edge` and+        /// `Graph::edge_name_offset` do, escape table and name bitmap included.+        fn get(&self, source: u32, idx: u64) -> (u32, u32, u32, u8, u8) {+            assert!(idx < self.edge_count, "edge {idx} is past the pack");+            let b = &self.bytes[(idx * EDGE_REC_BYTES) as usize..];+            let delta = i16::from_le_bytes([b[0], b[1]]);+            let dist = u32::from_le_bytes([b[2], b[3], b[4], 0]);+            let (type_, speed) = (b[5], b[6]);+            let name = self.name_offset(idx);+            if delta == TARGET_DELTA_ESCAPE || dist == DIST_MM_ESCAPE {+                let block = idx / ESCAPE_BLOCK;+                for r in self.escape_first(block)..self.escape_first(block + 1) {+                    let (row_idx, target, dist_mm) = self.row(u64::from(r));+                    if u64::from(row_idx) == idx {+                        return (target, dist_mm, name, type_, speed);+                    }+                }+                panic!("edge {idx} carries a sentinel but has no escape row");+            }+            (source.wrapping_add_signed(i32::from(delta)), dist, name, type_, speed)+        }+    }++    /// The edge's source: the **largest** node index whose `edge_ptr <= idx`, which+    /// is how `find_node_idx_for_edge` defines it. Taking the first such node instead+    /// would land on an empty range wherever degree-0 nodes share an `edge_ptr`.+    fn source_of(o: &Outputs, idx: u64) -> u32 {+        (0..node_count(o))+            .rev()+            .find(|v| node_at(o, *v).2 <= idx)+            .unwrap_or(0) as u32+    }++    /// `(target, dist_mm, name_offset, type_, speed_limit)` of edge `i`, with the+    /// source recovered from `nodes.bin`. Keeps every existing caller unchanged+    /// across the delta encoding, and exercises the source recovery as a side effect.     fn edge_at(o: &Outputs, i: usize) -> (u32, u32, u32, u8, u8) {-        let b = &o.edges[i * 14..i * 14 + 14];-        (-            u32::from_le_bytes(b[0..4].try_into().unwrap()),-            u32::from_le_bytes(b[4..8].try_into().unwrap()),-            u32::from_le_bytes(b[8..12].try_into().unwrap()),-            b[12],-            b[13],-        )+        Edges::of(o).get(source_of(o, i as u64), i as u64)     }      fn name_at(o: &Outputs, off: u32) -> String {@@ -2121,7 +2503,7 @@ mod tests {     }      fn edge_count(o: &Outputs) -> u64 {-        (o.edges.len() / 14) as u64+        meta_u64(o, 16)     }      fn node_count(o: &Outputs) -> usize {@@ -2371,13 +2753,21 @@ mod tests {             want.extend(GRAPH_VERSION.to_le_bytes());             want.extend(4u64.to_le_bytes());             want.extend(stats.edge_count.to_le_bytes());+            want.extend(stats.escape_count.to_le_bytes());+            want.extend(stats.named_edges.to_le_bytes());             want         }); -        // nodes.bin holds node_count + 1 12-byte records; edges.bin is a multiple-        // of 14.+        // nodes.bin holds node_count + 1 12-byte records; edges.bin is the record+        // array padded to a section boundary, then the escape index and rows, then+        // the sparse name table — exactly the length the reader computes, not merely+        // a multiple of anything.         assert_eq!(o.nodes.len(), 12 * 5);-        assert_eq!(o.edges.len() % 14, 0);+        assert_eq!(o.edges.len(), Edges::of(&o).total_bytes());+        assert_eq!(stats.escape_count, 0, "no fixture edge is long enough to escape");+        // Main St runs 1-2 and 2-4 in both directions; the service road and the two+        // synthetic stop connectors carry no name.+        assert_eq!(stats.named_edges, 4);         let edge_count = edge_count(&o);         assert_eq!(edge_count, stats.edge_count);         // Uncompacted this was 3 bidirectional segments + 1 oneway = 7 directed@@ -3022,7 +3412,15 @@ mod tests {             // entry and the `u64 G` trailer; plus `nodes.bin`'s trailing sentinel and             // a lane index holding only its own header and sentinel.             assert_eq!(o.nodes.len(), 12);-            assert!(o.edges.is_empty());+            // `edges.bin` is not empty even with no edges: the escape block index and+            // the name rank index each carry their final entry, which are the totals+            // the reader cross-checks `escape_count` and `named_edges` against. Four+            // bytes of "no escapes", padding, then eight of "no names".+            assert_eq!(o.edges.len() as u64, EdgeFile::total_bytes(0, 0, 0));+            assert_eq!(o.edges.len(), 4 + 4 + 8);+            assert!(o.edges.iter().all(|b| *b == 0), "every count is zero");+            assert_eq!(stats.escape_count, 0);+            assert_eq!(stats.named_edges, 0);             assert_eq!(o.inter.len(), 8 + 8 + 2 + 8, "rank, coarse, within, G");             assert_eq!(o.inter.len() as u64, GeomFile::trailer_bytes(0, 0));             assert_eq!(o.lanes.len(), 4 + 8);@@ -3031,6 +3429,256 @@ mod tests {         }     } +    // ---------------------------------------------------------------------+    // edges.bin narrowing: the boundaries no real extract contains+    // ---------------------------------------------------------------------++    fn tmp_edge(source: u32, target: u32, dist_mm: u32) -> TmpEdge {+        TmpEdge {+            source,+            target,+            dist_mm,+            name_offset: NO_NAME,+            type_: 1,+            speed_limit: 50,+            lane_off: NO_LANES,+            lane_count: 0,+            chain: NO_CHAIN,+            chain_rev: false,+            pts_start: 0,+            pts_len: 0,+        }+    }++    /// Push `spec` — `(source, target, dist_mm)` — through the real [`EdgeFile`] and+    /// read every record back through the mirror of `graph.rs`'s decode.+    ///+    /// The delta encoding's boundaries are unreachable from a PBF fixture: putting+    /// two nodes exactly 32,768 apart in Morton order would mean choosing+    /// coordinates for 32,767 nodes in between. So the encoder and the decoder are+    /// exercised as a pair directly, which is also where the off-by-one would be.+    fn roundtrip_edges(+        tag: &str,+        spec: &[(u32, u32, u32)],+    ) -> (Vec<(u32, u32, u32, u8, u8)>, Vec<u8>, u64) {+        let dir = std::env::temp_dir().join(format!("osm_ingest_edges_{tag}"));+        let _ = std::fs::remove_dir_all(&dir);+        std::fs::create_dir_all(&dir).unwrap();+        let count = spec.len() as u64;+        let mut f = EdgeFile::create(&dir, "edges.bin", count).unwrap();+        for (source, target, dist) in spec {+            f.push(&tmp_edge(*source, *target, *dist), 1).unwrap();+        }+        let escapes = f.escapes.len() as u64;+        let named = f.name_offsets.len() as u64;+        let total = f.finish(count).unwrap();+        let bytes = std::fs::read(dir.join("edges.bin")).unwrap();+        assert_eq!(bytes.len() as u64, total, "finish() lied about the length");+        assert_eq!(total, EdgeFile::total_bytes(count, escapes, named));+        let e = Edges::new(&bytes, count, escapes, named);+        // The block index's last entry is the row total, which is what the reader+        // cross-checks `escape_count` against.+        let blocks = count.div_ceil(ESCAPE_BLOCK) + 1;+        assert_eq!(+            u64::from(e.escape_first(blocks - 1)),+            escapes,+            "the block index total disagrees with the row count"+        );+        let decoded = spec+            .iter()+            .enumerate()+            .map(|(i, (source, _, _))| e.get(*source, i as u64))+            .collect();+        (decoded, bytes, escapes)+    }++    #[test]+    fn every_target_delta_boundary_round_trips() {+        // Far enough from zero that every delta below is a representable u32 target.+        let source = 1_000_000u32;+        let deltas: [i64; 11] = [0, 1, -1, 32766, -32766, 32767, -32767, 32768, -32768, -32769, 40000];+        let spec: Vec<(u32, u32, u32)> = deltas+            .iter()+            .map(|d| (source, (i64::from(source) + d) as u32, 1234))+            .collect();+        let (decoded, _, escapes) = roundtrip_edges("deltas", &spec);+        for (i, d) in deltas.iter().enumerate() {+            assert_eq!(decoded[i].0, spec[i].1, "delta {d} did not round-trip");+            assert_eq!(decoded[i].1, 1234, "delta {d} disturbed dist_mm");+        }+        // ±32767 fit. ±32768, −32769 and +40000 do not — and −32768 is `i16::MIN`,+        // which is the sentinel, so it escapes even though its magnitude would fit.+        // That reservation is what keeps the representable range symmetric.+        assert_eq!(escapes, 4, "expected 32768, -32768, -32769 and 40000 to escape");+    }++    #[test]+    fn every_dist_mm_boundary_round_trips() {+        let source = 5u32;+        let dists = [0u32, 1, 0xFF_FFFE, 0xFF_FFFF, 0x100_0000, u32::MAX];+        let spec: Vec<(u32, u32, u32)> =+            dists.iter().map(|d| (source, source + 1, *d)).collect();+        let (decoded, _, escapes) = roundtrip_edges("dists", &spec);+        for (i, d) in dists.iter().enumerate() {+            assert_eq!(decoded[i].1, *d, "dist {d} did not round-trip");+            assert_eq!(decoded[i].0, source + 1, "dist {d} disturbed the target");+        }+        // 0xFFFFFE is the largest a u24 can hold and be a value; 0xFFFFFF is the+        // sentinel, so it escapes despite fitting. The escape keeps every distance+        // *exact* — the alternative considered was centimetres, which needs no table+        // but quantises all 1.07 G edges.+        assert_eq!(escapes, 3);+    }++    #[test]+    fn an_edge_that_fails_both_tests_is_one_row_not_two() {+        let spec = vec![(0u32, 500_000u32, 0x200_0000u32)];+        let (decoded, _, escapes) = roundtrip_edges("both", &spec);+        assert_eq!(escapes, 1, "one row serves both fields");+        assert_eq!(decoded[0].0, 500_000);+        assert_eq!(decoded[0].1, 0x200_0000);+    }++    #[test]+    fn an_escape_at_either_end_of_the_pack_is_found() {+        // The block index is a prefix-count array, so the first and last edge are+        // where an off-by-one in it shows up.+        let far = 200_000u32;+        let spec = vec![+            (far, 0, 10),+            (far, far + 1, 20),+            (far, far + 2, 30),+            (far, 0, 40),+        ];+        let (decoded, _, escapes) = roundtrip_edges("ends", &spec);+        assert_eq!(escapes, 2);+        let got: Vec<(u32, u32)> = decoded.iter().map(|d| (d.0, d.1)).collect();+        assert_eq!(got, vec![(0, 10), (far + 1, 20), (far + 2, 30), (0, 40)]);+    }++    #[test]+    fn a_pack_with_no_escapes_is_records_padding_and_an_index_sentinel() {+        let spec: Vec<(u32, u32, u32)> = (0..100u32).map(|i| (1000, 1000 + i, i)).collect();+        let (decoded, bytes, escapes) = roundtrip_edges("no_escapes", &spec);+        assert_eq!(escapes, 0);+        // Only padding separates the record array from the block index, so it is the+        // only thing keeping a wide load of the last record in bounds.+        let records = 100 * EDGE_REC_BYTES;+        let pad = align_up(records, SECTION_ALIGN) - records;+        assert_eq!(pad, 4, "100 x 7 = 700, which is 4 short of a multiple of 8");+        assert!(+            bytes[records as usize..(records + pad) as usize].iter().all(|b| *b == 0),+            "the padding must be zeroed, not whatever the buffer held"+        );+        assert_eq!(bytes.len() as u64, EdgeFile::total_bytes(100, 0, 0));+        for (i, d) in decoded.iter().enumerate() {+            assert_eq!((d.0, d.1), (1000 + i as u32, i as u32));+            assert_eq!(d.2, NO_NAME, "no fixture edge is named");+        }+    }++    #[test]+    fn escape_rows_spanning_block_boundaries_are_all_found() {+        // Every side of every block boundary a 1024-edge block has, plus both ends.+        let far = 500_000u32;+        let n = 3000u32;+        let escaping = [0u32, 1023, 1024, 1025, 2047, 2048, 2049, n - 1];+        let spec: Vec<(u32, u32, u32)> = (0..n)+            .map(|i| {+                // An escaping edge points a long way back; the rest are a short+                // forward delta.+                let target = if escaping.contains(&i) { i } else { far + i };+                (far, target, 1000 + i)+            })+            .collect();+        let (decoded, _, escapes) = roundtrip_edges("blocks", &spec);+        assert_eq!(escapes, escaping.len() as u64);+        for i in 0..n as usize {+            assert_eq!(+                (decoded[i].0, decoded[i].1),+                (spec[i].1, spec[i].2),+                "edge {i} decoded wrongly"+            );+        }+    }++    /// Named at edge 0 and E−1, unnamed either side of a rank-block boundary, and a+    /// name offset at both ends of the `u32` range.+    ///+    /// The rank index covers 512 edges an entry, so the boundary at 511/512 is where+    /// a rank computed from the wrong block would show up — and it is a boundary a+    /// small fixture never reaches.+    #[test]+    fn the_sparse_name_table_survives_every_boundary() {+        let dir = std::env::temp_dir().join("osm_ingest_edges_names");+        let _ = std::fs::remove_dir_all(&dir);+        std::fs::create_dir_all(&dir).unwrap();+        let n = 1200u64;+        // Which edges get a name, and what offset. Deliberately includes both ends,+        // both sides of the 512-edge rank boundary and both sides of 1024.+        let named: Vec<u64> = vec![0, 1, 510, 511, 512, 513, 1022, 1023, 1024, 1025, n - 1];+        let mut f = EdgeFile::create(&dir, "edges.bin", n).unwrap();+        for i in 0..n {+            let mut e = tmp_edge(0, i as u32, 7);+            e.speed_limit = 90;+            if let Some(k) = named.iter().position(|x| *x == i) {+                // A distinct offset per named edge, so a rank off by one reads a+                // visibly wrong value rather than a plausible one.+                e.name_offset = (k as u32) * 17;+            }+            f.push(&e, REVERSE_GEOMETRY_FLAG | 3).unwrap();+        }+        let escapes = f.escapes.len() as u64;+        let named_count = f.name_offsets.len() as u64;+        assert_eq!(named_count, named.len() as u64);+        let total = f.finish(n).unwrap();+        let bytes = std::fs::read(dir.join("edges.bin")).unwrap();+        assert_eq!(bytes.len() as u64, total);+        let e = Edges::new(&bytes, n, escapes, named_count);+        for i in 0..n {+            let (target, dist, name, type_, speed) = e.get(0, i);+            assert_eq!(target, i as u32);+            assert_eq!(dist, 7);+            assert_eq!(type_, REVERSE_GEOMETRY_FLAG | 3, "edge {i}");+            assert_eq!(speed, 90, "edge {i}");+            let want = match named.iter().position(|x| *x == i) {+                Some(k) => (k as u32) * 17,+                None => NO_NAME,+            };+            assert_eq!(name, want, "edge {i}'s name offset");+        }+    }++    #[test]+    fn a_pack_where_no_edge_is_named_and_one_where_every_edge_is() {+        for all_named in [false, true] {+            let dir = std::env::temp_dir()+                .join(format!("osm_ingest_edges_named_{all_named}"));+            let _ = std::fs::remove_dir_all(&dir);+            std::fs::create_dir_all(&dir).unwrap();+            let n = 600u64;+            let mut f = EdgeFile::create(&dir, "edges.bin", n).unwrap();+            for i in 0..n {+                let mut e = tmp_edge(0, i as u32, 1);+                if all_named {+                    e.name_offset = i as u32 * 3;+                }+                f.push(&e, 1).unwrap();+            }+            let named_count = f.name_offsets.len() as u64;+            assert_eq!(named_count, if all_named { n } else { 0 });+            let total = f.finish(n).unwrap();+            let bytes = std::fs::read(dir.join("edges.bin")).unwrap();+            assert_eq!(bytes.len() as u64, total);+            assert_eq!(total, EdgeFile::total_bytes(n, 0, named_count));+            let e = Edges::new(&bytes, n, 0, named_count);+            for i in 0..n {+                let want = if all_named { i as u32 * 3 } else { NO_NAME };+                assert_eq!(e.get(0, i).2, want, "edge {i} with all_named={all_named}");+            }+        }+    }+     #[test]     fn the_round_count_does_not_change_a_single_output_byte() {         // The strongest check on the rounds writer. Round boundaries move the split