osm_ingest: split oversized Rust files under the 500-line limit
- Commit
6a32355ed96674f80dc5326340889e16c4efaf4f- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 20:29 UTC (4 days ago)
- Parents
03049f7
Fourteen files exceeded the 500-line rustFileLength limit, the worst poi_build.rs at 834 lines, overlay.rs at 683 and pbf.rs at 605. Split each along module lines using the established include! part pattern: whole top-level items move verbatim into *_sN.rs files spliced into the same module, so every item, visibility and call path is identical and no public surface changes. Verified: cargo fmt -p osm_ingest -- --check clean and cargo test -p osm_ingest --locked green (315 passed).
Diff
scripts/maps/osm_ingest/src/chains.rs
diff --git a/scripts/maps/osm_ingest/src/chains.rs b/scripts/maps/osm_ingest/src/chains.rsindex 4a10e4544c..0baf36f607 100644--- a/scripts/maps/osm_ingest/src/chains.rs+++ b/scripts/maps/osm_ingest/src/chains.rs@@ -426,113 +426,6 @@ fn flush( } } -/// Cut `path` into runs that each fit one edge's geometry.-///-/// Returns inclusive index ranges. A run of two nodes is always allowed even if-/// its single segment is too long to delta-encode: the caller stores no geometry-/// for it, and the reader's straight-chord fallback is then exactly right,-/// because a two-node run *is* a straight chord.-fn split_runs(path: &[u32], coords: &[geom::Pt]) -> Vec<(usize, usize)> {- let point = |n: u32| coords[n as usize];- let mut runs = Vec::new();- let mut start = 0usize;- let mut cost = 1u64;- let mut i = 1usize;- while i < path.len() {- let step = geom::segment_points(point(path[i - 1]), point(path[i]));- if cost + step <= u64::from(geom::MAX_POINTS) {- cost += step;- i += 1;- continue;- }- if i - 1 > start {- // Close the run before this segment and retry it with a fresh budget- // starting at the shared node.- runs.push((start, i - 1));- start = i - 1;- cost = 1;- } else {- // One segment that cannot be encoded at all, even alone.- runs.push((start, i));- start = i;- cost = 1;- i += 1;- }- }- if start < path.len() - 1 {- runs.push((start, path.len() - 1));- }- runs-}--/// Does dense node `n` survive as a graph node?-///-/// A chain endpoint always does. Anything of degree 1 or 3+ is a junction, a-/// dead end or an anchor the walks must address. Degree 2 is the only-/// collapsible case and is handled by the walk, not here.-///-/// Degree 0 is dropped unless it carries a transit stop: a node with no-/// incident segment is a way the region filter removed (every road node outside-/// the region reads degree 0 once its ways are skipped), dead weight in-/// `nodes.bin` with no edge ever addressing it. An isolated stop is the one-/// exception — the reconnect pass addresses stop nodes directly.-#[inline]-pub(crate) fn survives(endpoints: &Bitset, degree: &[u8], stop: &Bitset, n: u32) -> bool {- if endpoints.get(u64::from(n)) {- return true;- }- let d = degree[n as usize];- d != 2 && (d != 0 || stop.get(u64::from(n)))-}--// ---- the spill ------------------------------------------------------------//-// Chains are the last structure in the build that scales with the road network-// rather than with the node set, and every stage after them is a sequential scan.-// So they go to two flat files and the stages read them back: the CSR build, the-// reconnect BFS and each write round all stream, and none of them needs the chain-// set resident.-//-// Two properties are worth the redundancy in the record:-//-// * **The header is fixed size**, so the chain count is the file's length divided-// by the record size, and any stage can seek straight to chain *k* and process a-// contiguous slice of chains without reading the ones before it.-// * **`chains.pts` holds coordinates, not node ids**, so `coords` — the largest-// array in the build, and the only one indexed by *marked* rather than surviving-// node — can be freed the moment the spill is written. The cost is that the two-// endpoint node ids have to be repeated in the header, which is eight bytes a-// chain against gigabytes of coordinates.--/// Bytes per record in `chains.hdr`. The trailing padding is reserved and written-/// as zero, so the record can grow a field without changing the stride.-pub(crate) const CHAIN_REC_BYTES: u64 = 48;--/// Bytes per point in `chains.pts`: `i32 lat_e7`, `i32 lon_e7`.-const CHAIN_PT_BYTES: u64 = 8;--/// One chain, as `chains.hdr` stores it.-#[derive(Clone, Copy)]-pub(crate) struct ChainRec {- /// First point's index in `chains.pts`.- pub pts_start: u64,- pub pts_len: u32,- /// Dense id of the first point. Kept even though the point itself is stored,- /// because the writer needs the *node* to map to a final id and the- /// coordinates cannot be mapped back to one.- pub first: u32,- /// Dense id of the last point.- pub last: u32,- pub dist_mm: u32,- pub name_offset: u32,- pub fwd_lane_off: u32,- pub bwd_lane_off: u32,- pub fwd_lane_count: u16,- pub bwd_lane_count: u16,- pub type_: u8,- pub speed_limit: u8,- pub oneway: bool,-}-+include!("chains_s1.rs"); include!("chains_part1.rs"); include!("chains_part2.rs");
scripts/maps/osm_ingest/src/chains_s1.rs
diff --git a/scripts/maps/osm_ingest/src/chains_s1.rs b/scripts/maps/osm_ingest/src/chains_s1.rsnew file mode 100644index 0000000000..19232c22cf--- /dev/null+++ b/scripts/maps/osm_ingest/src/chains_s1.rs@@ -0,0 +1,108 @@+/// Cut `path` into runs that each fit one edge's geometry.+///+/// Returns inclusive index ranges. A run of two nodes is always allowed even if+/// its single segment is too long to delta-encode: the caller stores no geometry+/// for it, and the reader's straight-chord fallback is then exactly right,+/// because a two-node run *is* a straight chord.+fn split_runs(path: &[u32], coords: &[geom::Pt]) -> Vec<(usize, usize)> {+ let point = |n: u32| coords[n as usize];+ let mut runs = Vec::new();+ let mut start = 0usize;+ let mut cost = 1u64;+ let mut i = 1usize;+ while i < path.len() {+ let step = geom::segment_points(point(path[i - 1]), point(path[i]));+ if cost + step <= u64::from(geom::MAX_POINTS) {+ cost += step;+ i += 1;+ continue;+ }+ if i - 1 > start {+ // Close the run before this segment and retry it with a fresh budget+ // starting at the shared node.+ runs.push((start, i - 1));+ start = i - 1;+ cost = 1;+ } else {+ // One segment that cannot be encoded at all, even alone.+ runs.push((start, i));+ start = i;+ cost = 1;+ i += 1;+ }+ }+ if start < path.len() - 1 {+ runs.push((start, path.len() - 1));+ }+ runs+}++/// Does dense node `n` survive as a graph node?+///+/// A chain endpoint always does. Anything of degree 1 or 3+ is a junction, a+/// dead end or an anchor the walks must address. Degree 2 is the only+/// collapsible case and is handled by the walk, not here.+///+/// Degree 0 is dropped unless it carries a transit stop: a node with no+/// incident segment is a way the region filter removed (every road node outside+/// the region reads degree 0 once its ways are skipped), dead weight in+/// `nodes.bin` with no edge ever addressing it. An isolated stop is the one+/// exception — the reconnect pass addresses stop nodes directly.+#[inline]+pub(crate) fn survives(endpoints: &Bitset, degree: &[u8], stop: &Bitset, n: u32) -> bool {+ if endpoints.get(u64::from(n)) {+ return true;+ }+ let d = degree[n as usize];+ d != 2 && (d != 0 || stop.get(u64::from(n)))+}++// ---- the spill -----------------------------------------------------------+//+// Chains are the last structure in the build that scales with the road network+// rather than with the node set, and every stage after them is a sequential scan.+// So they go to two flat files and the stages read them back: the CSR build, the+// reconnect BFS and each write round all stream, and none of them needs the chain+// set resident.+//+// Two properties are worth the redundancy in the record:+//+// * **The header is fixed size**, so the chain count is the file's length divided+// by the record size, and any stage can seek straight to chain *k* and process a+// contiguous slice of chains without reading the ones before it.+// * **`chains.pts` holds coordinates, not node ids**, so `coords` — the largest+// array in the build, and the only one indexed by *marked* rather than surviving+// node — can be freed the moment the spill is written. The cost is that the two+// endpoint node ids have to be repeated in the header, which is eight bytes a+// chain against gigabytes of coordinates.++/// Bytes per record in `chains.hdr`. The trailing padding is reserved and written+/// as zero, so the record can grow a field without changing the stride.+pub(crate) const CHAIN_REC_BYTES: u64 = 48;++/// Bytes per point in `chains.pts`: `i32 lat_e7`, `i32 lon_e7`.+const CHAIN_PT_BYTES: u64 = 8;++/// One chain, as `chains.hdr` stores it.+#[derive(Clone, Copy)]+pub(crate) struct ChainRec {+ /// First point's index in `chains.pts`.+ pub pts_start: u64,+ pub pts_len: u32,+ /// Dense id of the first point. Kept even though the point itself is stored,+ /// because the writer needs the *node* to map to a final id and the+ /// coordinates cannot be mapped back to one.+ pub first: u32,+ /// Dense id of the last point.+ pub last: u32,+ pub dist_mm: u32,+ pub name_offset: u32,+ pub fwd_lane_off: u32,+ pub bwd_lane_off: u32,+ pub fwd_lane_count: u16,+ pub bwd_lane_count: u16,+ pub type_: u8,+ pub speed_limit: u8,+ pub oneway: bool,+}+
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 e62ed2bdcd..8d189aaebe 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -426,80 +426,4 @@ impl Bitset { /// See [`Bitset::atomic`]. pub(crate) struct AtomicBits<'a>(&'a [std::sync::atomic::AtomicU8]); -impl AtomicBits<'_> {- /// Set bit `idx`; true when this call is the one that set it. A plain load- /// first, so re-marking an already-set bit (most refs: a node is shared by- /// every way through it) never takes the cache line exclusive.- #[inline]- pub(crate) fn set(&self, idx: u64) -> bool {- use std::sync::atomic::Ordering::Relaxed;- let byte = &self.0[(idx / 8) as usize];- let mask = 1u8 << (idx % 8);- if byte.load(Relaxed) & mask != 0 {- return false;- }- byte.fetch_or(mask, Relaxed) & mask == 0- }-}--/// Dense addressing for the graph's nodes: which OSM ids are in the graph, and-/// which of those the file actually supplied coordinates for.-///-/// Both tests matter, and for different reasons. The mask is what makes-/// [`Bitset::dense`] meaningful. `present` is what keeps *dangling references*-/// out: pass 1 marks every ref of every routable way, including refs to nodes no-/// blob in the file defines — an extract clipped at a boundary is full of them —-/// and those slots never receive coordinates. Left in, each would read as-/// `(0, 0)`, a point in the Atlantic that corrupts distances, spatial keys and-/// polylines while leaving every count looking plausible.-pub(crate) struct NodeIndex {- pub(crate) mask: Bitset,- present: Bitset,-}--impl NodeIndex {- /// Dense id of a node that is both in the graph and really in the file.- #[inline]- pub(crate) fn dense(&self, osm_id: i64) -> Option<u32> {- if osm_id < 0 || osm_id as u64 >= BITSET_SIZE || !self.mask.get(osm_id as u64) {- return None;- }- let d = self.mask.dense(osm_id as u64);- self.present.get(u64::from(d)).then_some(d)- }-}--#[derive(Default)]-struct Pass1 {- /// Ids this chunk was the first to mark. Refs and stops are marked straight- /// into the shared mask from the decode workers (a set union, so order- /// cannot matter); only these two scalars reach the sink. Nothing about a- /// way is retained, because the ways pass re-reads them.- marked: u64,- /// Largest id this chunk marked or found already marked.- max_id: u64,-}--/// A region bbox filter, or `None` for a world build.-///-/// Passed by value into the block visitors (it is `Copy`): every routable way-/// whose nodes all fall outside is dropped, and a stop outside never enters-/// the graph. Ways are kept whole when any node touches — the same-/// `complete_ways` rule [`crate::bbox`] documents — so a road straddling the-/// border keeps its boundary stub rather than ending mid-segment.-pub type RegionFilter = Option<crate::bbox::BBox>;--include!("graph_build_part1.rs");-include!("graph_build_part2.rs");-include!("graph_build_part3.rs");-include!("graph_build_part4.rs");-include!("graph_build_part5.rs");-include!("graph_build_part11.rs");-#[cfg(test)]-mod tests {- include!("graph_build_part6.rs");- include!("graph_build_part7.rs");- include!("graph_build_part8.rs");- include!("graph_build_part9.rs");- include!("graph_build_part10.rs");-}+include!("graph_build_s1.rs");
scripts/maps/osm_ingest/src/graph_build_part1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part1.rs b/scripts/maps/osm_ingest/src/graph_build_part1.rsindex 40ab8b3576..a20961edaa 100644--- a/scripts/maps/osm_ingest/src/graph_build_part1.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part1.rs@@ -107,486 +107,5 @@ pub fn build(input: &Path, out_dir: &Path) -> Result<Stats> { build_with(input, out_dir, Options::default()) } -pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> {- if let Some(n) = opts.threads {- crate::par::set_threads(n);- }- // The region filter is validated up front: a later stage reads `graph/`- // assuming it covers the same region the tiles do, and a graph built for- // the wrong region is a silent layer mismatch, not a loud failure.- if let Some(b) = &opts.bbox {- println!(- "region filter: keeping ways touching {:.3},{:.3} .. {:.3},{:.3}",- b.min_lon, b.min_lat, b.max_lon, b.max_lat,- );- }- std::fs::create_dir_all(out_dir)- .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?;-- let mut timer = crate::timing::PhaseTimer::start("graph");- let blobs = pbf::scan_blobs(input)?;- println!("[graph] Scanned {} data blob(s) in {}", blobs.len(), input.display());- pbf::probe_compression(input, &blobs)?;-- let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));-- let mut mask = Bitset::new(BITSET_SIZE);- let mut marked: u64 = 0;- let mut max_id: u64 = 0;-- timer.switch("refs-stops");- // --- Pass 1: which nodes the graph needs ---------------------------------- // Folded through a sink rather than collected, so a chunk's ref list is- // consumed and freed while later chunks are still decoding. Nothing about a- // way survives this pass: the ways pass below re-reads the way blobs, which- // is far cheaper than caching every routable way and every ref it holds.- //- // The region filter needs way NODE LOCATIONS, but ways arrive before their- // nodes in a PBF — so pass 1 cannot filter ways. It marks every routable- // way's refs unconditionally; the way passes below (which run after the- // coordinates are resolved) apply the filter when they re-read the ways.- // Stop nodes ARE filtered here: a node's own coordinates arrive with it.- let filter = opts.bbox;- let blob_kinds = {- let bits = mask.atomic();- pbf::run_pass_sink(- input,- &blobs,- pbf::PassSpec { blob_kinds: None, want: KIND_NODES | KIND_WAYS, label: "Pass 1: refs + stops" },- Pass1::default,- |state, block| pass1_blob(state, block, filter, &bits),- |chunk| {- marked += chunk.marked;- max_id = max_id.max(chunk.max_id);- Ok(())- },- )?- };- println!("{marked} graph node(s) expected");- // Cache the complete blob-kinds mask beside the graph so a `mamaps_build` run over the same- // `.pbf` can skip its own full pass-1 scan. This pass inflated every blob with `None`, so the- // mask is complete. Best-effort: a write failure must not fail the graph build, which never- // reads the sidecar itself.- if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blobs, &blob_kinds) {- eprintln!("WARN: could not write blob-kinds sidecar: {e}");- }- let slots = cap_u32("marked graph node", marked)?;-- // --- The rank index ------------------------------------------------------- // From here on a node's address is the number of marked ids below its own, so- // the node array is implicitly ordered by OSM id and needs to store neither- // the id nor a sorted side table to look it up by.- timer.switch("rank-index");- let counted = mask.build_rank(max_id);- if counted != marked {- // The mask and the running count are maintained in the same loop, so a- // disagreement means one of the two is wrong about which ids were set,- // and every address derived from the rank would be off by however many.- return Err(Error(format!(- "rank index counted {counted} marked node(s) but pass 1 set {marked}"- )));- }-- // --- Pass 2: coordinates and stop codes for the marked nodes -------------- // Zero-initialised, so the slots belonging to dangling refs are never touched- // and never fault in: an untouched page of `coords` costs no real memory.- let mut coords: Vec<geom::Pt> = vec![(0, 0); slots as usize];- let mut present = Bitset::new(u64::from(slots));- let mut stop = Bitset::new(u64::from(slots));- let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new();- let mut node_count: u64 = 0;- timer.switch("node-scan");- // Coordinates scatter from the decode workers. Each node id claims its- // `present` bit atomically and only the claimant writes its slot, so every- // slot has exactly one writer. That equals the serial fold — which let the- // LAST occurrence of an id win — whenever ids are unique, as they are in- // any well-formed (sorted) PBF. If some id occurs twice, the race for its- // slot could pick a different occurrence, so the pass is redone with the- // original single-threaded fold, keeping the output exact either way.- // Stop codes stay in the ordered sink: their order is interning order.- let duplicate = std::sync::atomic::AtomicBool::new(false);- {- let pres = present.atomic();- let slots_out = par::SyncPtr(coords.as_mut_ptr());- let _ = pbf::run_pass_sink(- input,- &blobs,- pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan" },- Pass2::default,- |state, block| {- let kinds = pass2_blob(state, block, &mask)?;- for (dense, lat_e7, lon_e7) in state.locs.drain(..) {- if pres.set(u64::from(dense)) {- // SAFETY: `dense < slots` (a rank over the mask), and- // the `present` claim above makes this the only writer.- unsafe { slots_out.write(dense as usize, (lat_e7, lon_e7)) };- state.claimed += 1;- } else {- duplicate.store(true, Ordering::Relaxed);- }- }- Ok(kinds)- },- |chunk| {- node_count += chunk.claimed;- for (dense, code) in chunk.stops {- stop.set(u64::from(dense));- stop_codes.push((dense, code));- }- Ok(())- },- )?;- }- if duplicate.load(Ordering::Relaxed) {- eprintln!("WARN: a node id occurs more than once; redoing the node scan serially");- coords.iter_mut().for_each(|c| *c = (0, 0));- present = Bitset::new(u64::from(slots));- stop = Bitset::new(u64::from(slots));- stop_codes.clear();- node_count = 0;- let _ = pbf::run_pass_sink(- input,- &blobs,- pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan (serial)" },- Pass2::default,- |state, block| pass2_blob(state, block, &mask),- |chunk| {- for (dense, lat_e7, lon_e7) in chunk.locs {- coords[dense as usize] = (lat_e7, lon_e7);- if present.set(u64::from(dense)) {- node_count += 1;- }- }- for (dense, code) in chunk.stops {- stop.set(u64::from(dense));- stop_codes.push((dense, code));- }- Ok(())- },- )?;- }- println!(- "Located {node_count} node(s); {} marked id(s) had no coordinates in the file",- marked - node_count- );-- // Stop codes go into the pool only after every way name is in it, in the- // order pass 2 met them, so `road_names.bin` is unaffected by dense- // addressing and by where the way names are interned.- let index = NodeIndex { mask, present };-- // --- Collapse ------------------------------------------------------------- let spill_dir = opts.spill_dir.clone().unwrap_or_else(|| out_dir.to_path_buf());- let spill_pts_dir = opts.spill_pts_dir.clone().unwrap_or_else(|| spill_dir.clone());- timer.switch("collapse");- let mut collapsed = if opts.within_way_chains {- collapse_within_ways(- input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,- slots, filter, &mut pool, &mut timer,- )?- } else {- collapse_segments(- input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,- slots, filter, &mut pool, &mut timer,- )?- };-- let mut prog = crate::progress::Progress::new("Interning stop codes", stop_codes.len() as u64);- for (_, code) in &stop_codes {- pool.intern(code).map_err(io_err)?;- prog.inc();- }- prog.finish();- drop(stop_codes);- timer.switch("rank-survivors");-- // `saturating_sub` because a file with no routable ways and no stop nodes- // marks nothing, and there is then no largest id to index up to.- let kept_count = cap_u32(- "surviving node",- collapsed.kept.build_rank(u64::from(slots).saturating_sub(1)),- )?;- let kept = collapsed.kept;- println!(- "Collapsed {node_count} node(s) -> {kept_count} ({} chain(s), {} split(s) for the \- 256-point limit)",- collapsed.chain_count, collapsed.splits- );- cap_u32("chain", collapsed.chain_count)?;- let raw_edge_count = collapsed.raw_edge_count;-- // --- Morton order -------------------------------------------------------- // Deferred to here, and applied only to the survivors, because that is the- // only set the device ever binary-searches. Sorting before the collapse would- // have meant carrying a 64-bit spatial key through every node that was about- // to be collapsed away.- timer.switch("morton-sort");- println!("Sorting {kept_count} surviving node(s) by spatial key...");- // Keys on the pool, written in place: the kept bitset's rank says where- // each slot range's keys start, so every range fills its own disjoint- // slice and `keys` comes out exactly as the serial loop pushed it- // (ascending `dense`) with no second copy.- let mut keys: Vec<(u64, u32)> = vec![(0, 0); kept_count as usize];- {- const RANGE: usize = 1 << 20;- let ranges: Vec<(usize, usize)> = (0..(slots as usize).div_ceil(RANGE))- .map(|r| (r * RANGE, ((r + 1) * RANGE).min(slots as usize)))- .collect();- let mut pieces: Vec<KeyPiece<'_>> = Vec::with_capacity(ranges.len());- let mut rest: &mut [(u64, u32)] = &mut keys;- for &(lo, hi) in &ranges {- // Kept ids below `hi` minus those below `lo`.- let rank = |i: usize| -> usize {- if i >= slots as usize {- kept_count as usize- } else {- kept.dense(i as u64) as usize- }- };- let (mine, tail) = rest.split_at_mut(rank(hi) - rank(lo));- pieces.push(((lo, hi), mine));- rest = tail;- }- debug_assert!(rest.is_empty());- let coords = &coords;- let kept = &kept;- par::install(|| {- pieces.par_iter_mut().for_each(|((lo, hi), out)| {- let mut k = 0usize;- for i in *lo as u32..*hi as u32 {- if kept.get(u64::from(i)) {- let (lat_e7, lon_e7) = coords[i as usize];- out[k] = (spatial_from_e7(lat_e7, lon_e7), i);- k += 1;- }- }- debug_assert_eq!(k, out.len());- });- });- }- // The key is `(spatial, dense)`, and the keys are laid out with `dense`- // ascending, so this is exactly the order the previous STABLE- // `sort_by_key(spatial)` produced: ties there fell back to insertion order,- // which was ascending `dense`. Spelling the tie-break into the key makes the- // order total, and a total order is what lets an UNSTABLE parallel sort be- // substituted without changing a single final id -- and final ids are what- // `nodes.bin`, `edges.bin` and every offset in the pack are numbered by, so- // this is the one comparison in the build that must not move.- eprintln!("Sorting {kept_count} spatial key(s)...");- par::install(|| keys.par_sort_unstable());-- // Final ids on the pool. `final_of_kept` is a permutation write (every- // `dense` appears once in `keys`), `node_coords` an ordered map, and each- // byte of `stops_final` a pure function of its own eight final ids.- let mut final_of_kept = vec![0u32; kept_count as usize];- let mut stops_final = Bitset::new(u64::from(kept_count));- let node_coords: Vec<geom::Pt> = {- let out = par::SyncPtr(final_of_kept.as_mut_ptr());- let (keys, kept, coords, stop) = (&keys, &kept, &coords, &stop);- par::install(|| {- keys.par_iter().enumerate().for_each(|(final_id, (_, dense))| {- // SAFETY: `keys` holds each kept dense id exactly once, so each- // rank is written by exactly one iteration.- unsafe { out.write(kept.dense(u64::from(*dense)) as usize, final_id as u32) };- });- stops_final.bits.par_chunks_mut(1 << 16).enumerate().for_each(|(ci, chunk)| {- for (j, byte) in chunk.iter_mut().enumerate() {- let base = ((ci << 16) + j) * 8;- let mut v = 0u8;- for k in 0..8 {- if let Some((_, dense)) = keys.get(base + k) {- if stop.get(u64::from(*dense)) {- v |= 1 << k;- }- }- }- *byte = v;- }- });- keys.par_iter().map(|(_, dense)| coords[*dense as usize]).collect()- })- };- drop(keys);- drop(stop);- // The chain spill holds coordinates, so nothing downstream needs the array- // indexed by *marked* node — the largest in the build — any longer.- drop(coords);- drop(index);- let ids = FinalIds {- kept: &kept,- of_kept: &final_of_kept,- };-- // --- The edge index ------------------------------------------------------ timer.switch("edge-index");- let csr = build_csr(&collapsed.spill, kept_count, &ids, &mut timer)?;-- // --- Reconnect isolated transit stops ------------------------------------ timer.switch("components");- let rec = reconnect_isolated_stops(&node_coords, &stops_final, &csr);- let synth = rec.synth;- drop(stops_final);-- // --- Write --------------------------------------------------------------- // Load the optional DEM up front so a bad `--dem` path fails before the write starts. `None`- // leaves `elevation.bin` unwritten and every node's baked elevation at 0.- let dem = match &opts.dem {- Some(path) => Some(crate::dem::Dem::load(path)?),- None => None,- };- timer.switch("write");- let written = write_graph(- out_dir,- &node_coords,- &collapsed.spill,- &collapsed.lane_pool,- &csr,- &synth,- &ids,- opts.round_count(),- dem.as_ref(),- &mut timer,- )?;- collapsed.spill.remove();- let unique_names = pool.unique_count();- let name_bytes = pool.byte_len();- pool.finish().map_err(io_err)?;-- timer.finish();- println!(- "Done. Nodes: {} Edges: {} intermediate.bin: {} byte(s)",- kept_count, written.edge_count, written.intermediate_bytes- );- Ok(Stats {- node_count: u64::from(kept_count),- edge_count: written.edge_count,- unique_names,- name_bytes,- lcc_size: rec.lcc_size,- stops_already_connected: rec.already_connected,- reconnected_stops: synth.len() / 2,- stops_unreachable: rec.unreachable,- raw_node_count: node_count,- raw_edge_count,- chain_splits: collapsed.splits,- 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,- })-}--/// What either collapse strategy hands the writer.-///-/// Both produce the same thing — a chain spill plus the set of nodes that survive-/// — and differ only in how much memory it costs to get there and whether a chain-/// may cross from one OSM way into the next.-///-/// The chains are always on disk, even for the reference path that had them in-/// memory anyway, so that there is one writer. That also means `coords` — the-/// largest array in the build, and the only one indexed by *marked* rather than-/// surviving node — can be freed before the writer runs.-struct Collapsed {- spill: chains::Spill,- /// Dense ids that survive as graph nodes.- kept: Bitset,- lane_pool: Vec<u16>,- chain_count: u64,- splits: usize,- raw_edge_count: u64,-}--/// The reference path: build every segment, then collapse chains across way-/// boundaries with [`compact`].-///-/// Kept as the baseline the within-way path is measured against. Its cost is the-/// segment array and the incidence CSR over it, which together are the reason a-/// planet build does not fit.-#[allow(clippy::too_many_arguments)]-fn collapse_segments<W: std::io::Write + Send>(- input: &Path,- spill_dir: &Path,- spill_pts_dir: &Path,- blobs: &[pbf::BlobLoc],- blob_kinds: &[u8],- index: &NodeIndex,- coords: &[geom::Pt],- stop: &Bitset,- slots: u32,- filter: RegionFilter,- pool: &mut NamePool<W>,- timer: &mut crate::timing::PhaseTimer,-) -> Result<Collapsed> {- timer.switch("collapse-segments");- // One record per consecutive way-node pair, still carrying both directions'- // lane data. Splitting into directed edges is deferred until after- // compaction, because pairing a `u -> v` edge with its `v -> u` twin is only- // unambiguous while they are still one object.- let mut segs: Vec<Seg> = Vec::new();- let mut lane_pool: Vec<u16> = Vec::new();- let way_kinds = pbf::run_pass_sink(- input,- blobs,- pbf::PassSpec { blob_kinds: Some(blob_kinds), want: KIND_WAYS, label: "Pass 3: segments" },- WayPass::default,- |state, block| way_blob(state, block, index, coords, filter),- |chunk| {- let name_map = chunk.names.flush(pool).map_err(io_err)?;- let lane_base = lane_pool.len() as u32;- lane_pool.extend_from_slice(&chunk.lanes);- cap_lane_pool(lane_pool.len())?;- segs.reserve(chunk.segs.len());- for mut s in chunk.segs {- s.name_offset = if s.name_offset == u32::MAX {- NO_NAME- } else {- name_map[s.name_offset as usize]- };- if s.fwd_lane_count > 0 {- s.fwd_lane_off += lane_base;- }- if s.bwd_lane_count > 0 {- s.bwd_lane_off += lane_base;- }- segs.push(s);- }- Ok(())- },- )?;- report_way_blobs(blobs.len(), &way_kinds);-- let raw_edge_count: u64 = segs.iter().map(|s| if s.oneway { 1u64 } else { 2 }).sum();- println!(- "Built {} segment(s) ({raw_edge_count} directed edge(s) before compaction)",- segs.len()- );-- timer.switch("collapse-compact");- let comp = compact::compact(slots, &segs, &lane_pool, |n| coords[n as usize], |n| {- stop.get(u64::from(n))- });- drop(segs);-- // A slot with no coordinates has no segments either, so compaction has no- // reason to collapse it and would hand it a real node id. Filter it out here- // instead: this is the second half of the dangling-reference guard.- let mut kept = Bitset::new(u64::from(slots));- for i in 0..slots {- if comp.new_id[i as usize] != REMOVED && index.present.get(u64::from(i)) {- kept.set(u64::from(i));- }- }- let spill = chains::Spill::split(spill_dir, spill_pts_dir);- spill.write(&comp.chains, &comp.pts, coords)?;- Ok(Collapsed {- spill,- kept,- lane_pool,- chain_count: comp.chains.len() as u64,- splits: comp.splits,- raw_edge_count,- })-}+include!("graph_build_part1_s1.rs");+include!("graph_build_part1_s2.rs");
scripts/maps/osm_ingest/src/graph_build_part11.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part11.rs b/scripts/maps/osm_ingest/src/graph_build_part11.rsindex fe7589c911..e08d5396a7 100644--- a/scripts/maps/osm_ingest/src/graph_build_part11.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part11.rs@@ -428,90 +428,4 @@ const SCAN_CHUNK: usize = 1 << 16; /// a compress-force filesystem every extent costs CPU. const WRITE_BUF_BYTES: usize = 8 << 20; -/// Write one round's nodes `lo..hi` from its sorted edge buffer, whose first-/// edge is absolute index `round_base`.-///-/// Batches of [`WRITE_BATCH_NODES`] nodes bake on the pool a wave at a time;-/// while wave `k` drains on this thread, wave `k + 1` bakes. Each batch's edge-/// slice is found by binary search on the source-sorted buffer, and its base is-/// `round_base` plus the edges before it, so no batch depends on another.-#[allow(clippy::too_many_arguments)]-fn write_round(- buffer: &[TmpEdge],- lo: u32,- hi: u32,- round_base: u64,- node_coords: &[geom::Pt],- lane_pool: &[u16],- csr: &Csr,- synth: &[Synth],- points: &crate::mem::Mapped,- sinks: &mut WriteSinks,- round: u32,- rounds: u32,-) -> Result<()> {- let n_batches = (hi - lo).div_ceil(WRITE_BATCH_NODES) as usize;- let wave = (par::threads() * WAVE_BATCHES_PER_THREAD).max(1);- let n_waves = n_batches.div_ceil(wave);- let span_of = |bi: usize| -> (u32, u32) {- let first = lo + bi as u32 * WRITE_BATCH_NODES;- (first, first.saturating_add(WRITE_BATCH_NODES).min(hi))- };- let bake_wave = |w: usize| -> Vec<(u64, Result<BakedBatch>)> {- let b0 = w * wave;- let b1 = (b0 + wave).min(n_batches);- (b0..b1)- .into_par_iter()- .map(|bi| {- let (first, end) = span_of(bi);- let e0 = buffer.partition_point(|e| e.source < first);- let e1 = buffer.partition_point(|e| e.source < end);- let base = round_base + e0 as u64;- let baked = bake_batch(- &buffer[e0..e1],- first,- end,- base,- node_coords,- lane_pool,- csr,- synth,- points,- );- (base, baked)- })- .collect()- };- let mut prog = crate::progress::Progress::new(- format!("Round {}/{rounds}: write", round + 1),- u64::from(hi - lo),- );- let drain_wave = |baked: Vec<(u64, Result<BakedBatch>)>,- sinks: &mut WriteSinks,- prog: &mut crate::progress::Progress|- -> Result<()> {- for (base, b) in baked {- let b = b?;- drain_batch(sinks, &b, base)?;- prog.add((b.node_recs.len() / 12) as u64);- }- Ok(())- };- par::install(|| -> Result<()> {- let mut pending = if n_waves > 0 { Some(bake_wave(0)) } else { None };- for w in 0..n_waves {- let cur = pending.take().expect("a baked wave is pending");- let (drained, next) = rayon::join(- || drain_wave(cur, sinks, &mut prog),- || (w + 1 < n_waves).then(|| bake_wave(w + 1)),- );- drained?;- pending = next;- }- Ok(())- })?;- prog.finish();- debug_assert_eq!(sinks.edges.pushed, round_base + buffer.len() as u64);- Ok(())-}-+include!("graph_build_part11_s1.rs");
scripts/maps/osm_ingest/src/graph_build_part11_s1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part11_s1.rs b/scripts/maps/osm_ingest/src/graph_build_part11_s1.rsnew file mode 100644index 0000000000..821fdedbcf--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part11_s1.rs@@ -0,0 +1,87 @@+/// Write one round's nodes `lo..hi` from its sorted edge buffer, whose first+/// edge is absolute index `round_base`.+///+/// Batches of [`WRITE_BATCH_NODES`] nodes bake on the pool a wave at a time;+/// while wave `k` drains on this thread, wave `k + 1` bakes. Each batch's edge+/// slice is found by binary search on the source-sorted buffer, and its base is+/// `round_base` plus the edges before it, so no batch depends on another.+#[allow(clippy::too_many_arguments)]+fn write_round(+ buffer: &[TmpEdge],+ lo: u32,+ hi: u32,+ round_base: u64,+ node_coords: &[geom::Pt],+ lane_pool: &[u16],+ csr: &Csr,+ synth: &[Synth],+ points: &crate::mem::Mapped,+ sinks: &mut WriteSinks,+ round: u32,+ rounds: u32,+) -> Result<()> {+ let n_batches = (hi - lo).div_ceil(WRITE_BATCH_NODES) as usize;+ let wave = (par::threads() * WAVE_BATCHES_PER_THREAD).max(1);+ let n_waves = n_batches.div_ceil(wave);+ let span_of = |bi: usize| -> (u32, u32) {+ let first = lo + bi as u32 * WRITE_BATCH_NODES;+ (first, first.saturating_add(WRITE_BATCH_NODES).min(hi))+ };+ let bake_wave = |w: usize| -> Vec<(u64, Result<BakedBatch>)> {+ let b0 = w * wave;+ let b1 = (b0 + wave).min(n_batches);+ (b0..b1)+ .into_par_iter()+ .map(|bi| {+ let (first, end) = span_of(bi);+ let e0 = buffer.partition_point(|e| e.source < first);+ let e1 = buffer.partition_point(|e| e.source < end);+ let base = round_base + e0 as u64;+ let baked = bake_batch(+ &buffer[e0..e1],+ first,+ end,+ base,+ node_coords,+ lane_pool,+ csr,+ synth,+ points,+ );+ (base, baked)+ })+ .collect()+ };+ let mut prog = crate::progress::Progress::new(+ format!("Round {}/{rounds}: write", round + 1),+ u64::from(hi - lo),+ );+ let drain_wave = |baked: Vec<(u64, Result<BakedBatch>)>,+ sinks: &mut WriteSinks,+ prog: &mut crate::progress::Progress|+ -> Result<()> {+ for (base, b) in baked {+ let b = b?;+ drain_batch(sinks, &b, base)?;+ prog.add((b.node_recs.len() / 12) as u64);+ }+ Ok(())+ };+ par::install(|| -> Result<()> {+ let mut pending = if n_waves > 0 { Some(bake_wave(0)) } else { None };+ for w in 0..n_waves {+ let cur = pending.take().expect("a baked wave is pending");+ let (drained, next) = rayon::join(+ || drain_wave(cur, sinks, &mut prog),+ || (w + 1 < n_waves).then(|| bake_wave(w + 1)),+ );+ drained?;+ pending = next;+ }+ Ok(())+ })?;+ prog.finish();+ debug_assert_eq!(sinks.edges.pushed, round_base + buffer.len() as u64);+ Ok(())+}+
scripts/maps/osm_ingest/src/graph_build_part1_s1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part1_s1.rs b/scripts/maps/osm_ingest/src/graph_build_part1_s1.rsnew file mode 100644index 0000000000..55cbf0efa4--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part1_s1.rs@@ -0,0 +1,392 @@+pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> {+ if let Some(n) = opts.threads {+ crate::par::set_threads(n);+ }+ // The region filter is validated up front: a later stage reads `graph/`+ // assuming it covers the same region the tiles do, and a graph built for+ // the wrong region is a silent layer mismatch, not a loud failure.+ if let Some(b) = &opts.bbox {+ println!(+ "region filter: keeping ways touching {:.3},{:.3} .. {:.3},{:.3}",+ b.min_lon, b.min_lat, b.max_lon, b.max_lat,+ );+ }+ std::fs::create_dir_all(out_dir)+ .map_err(|e| Error(format!("cannot create {}: {e}", out_dir.display())))?;++ let mut timer = crate::timing::PhaseTimer::start("graph");+ let blobs = pbf::scan_blobs(input)?;+ println!("[graph] Scanned {} data blob(s) in {}", blobs.len(), input.display());+ pbf::probe_compression(input, &blobs)?;++ let mut pool = NamePool::new(BufWriter::new(create(&out_dir.join("road_names.bin"))?));++ let mut mask = Bitset::new(BITSET_SIZE);+ let mut marked: u64 = 0;+ let mut max_id: u64 = 0;++ timer.switch("refs-stops");+ // --- Pass 1: which nodes the graph needs ---------------------------------+ // Folded through a sink rather than collected, so a chunk's ref list is+ // consumed and freed while later chunks are still decoding. Nothing about a+ // way survives this pass: the ways pass below re-reads the way blobs, which+ // is far cheaper than caching every routable way and every ref it holds.+ //+ // The region filter needs way NODE LOCATIONS, but ways arrive before their+ // nodes in a PBF — so pass 1 cannot filter ways. It marks every routable+ // way's refs unconditionally; the way passes below (which run after the+ // coordinates are resolved) apply the filter when they re-read the ways.+ // Stop nodes ARE filtered here: a node's own coordinates arrive with it.+ let filter = opts.bbox;+ let blob_kinds = {+ let bits = mask.atomic();+ pbf::run_pass_sink(+ input,+ &blobs,+ pbf::PassSpec { blob_kinds: None, want: KIND_NODES | KIND_WAYS, label: "Pass 1: refs + stops" },+ Pass1::default,+ |state, block| pass1_blob(state, block, filter, &bits),+ |chunk| {+ marked += chunk.marked;+ max_id = max_id.max(chunk.max_id);+ Ok(())+ },+ )?+ };+ println!("{marked} graph node(s) expected");+ // Cache the complete blob-kinds mask beside the graph so a `mamaps_build` run over the same+ // `.pbf` can skip its own full pass-1 scan. This pass inflated every blob with `None`, so the+ // mask is complete. Best-effort: a write failure must not fail the graph build, which never+ // reads the sidecar itself.+ if let Err(e) = pbf::write_blob_kinds(out_dir, input, &blobs, &blob_kinds) {+ eprintln!("WARN: could not write blob-kinds sidecar: {e}");+ }+ let slots = cap_u32("marked graph node", marked)?;++ // --- The rank index ------------------------------------------------------+ // From here on a node's address is the number of marked ids below its own, so+ // the node array is implicitly ordered by OSM id and needs to store neither+ // the id nor a sorted side table to look it up by.+ timer.switch("rank-index");+ let counted = mask.build_rank(max_id);+ if counted != marked {+ // The mask and the running count are maintained in the same loop, so a+ // disagreement means one of the two is wrong about which ids were set,+ // and every address derived from the rank would be off by however many.+ return Err(Error(format!(+ "rank index counted {counted} marked node(s) but pass 1 set {marked}"+ )));+ }++ // --- Pass 2: coordinates and stop codes for the marked nodes -------------+ // Zero-initialised, so the slots belonging to dangling refs are never touched+ // and never fault in: an untouched page of `coords` costs no real memory.+ let mut coords: Vec<geom::Pt> = vec![(0, 0); slots as usize];+ let mut present = Bitset::new(u64::from(slots));+ let mut stop = Bitset::new(u64::from(slots));+ let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new();+ let mut node_count: u64 = 0;+ timer.switch("node-scan");+ // Coordinates scatter from the decode workers. Each node id claims its+ // `present` bit atomically and only the claimant writes its slot, so every+ // slot has exactly one writer. That equals the serial fold — which let the+ // LAST occurrence of an id win — whenever ids are unique, as they are in+ // any well-formed (sorted) PBF. If some id occurs twice, the race for its+ // slot could pick a different occurrence, so the pass is redone with the+ // original single-threaded fold, keeping the output exact either way.+ // Stop codes stay in the ordered sink: their order is interning order.+ let duplicate = std::sync::atomic::AtomicBool::new(false);+ {+ let pres = present.atomic();+ let slots_out = par::SyncPtr(coords.as_mut_ptr());+ let _ = pbf::run_pass_sink(+ input,+ &blobs,+ pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan" },+ Pass2::default,+ |state, block| {+ let kinds = pass2_blob(state, block, &mask)?;+ for (dense, lat_e7, lon_e7) in state.locs.drain(..) {+ if pres.set(u64::from(dense)) {+ // SAFETY: `dense < slots` (a rank over the mask), and+ // the `present` claim above makes this the only writer.+ unsafe { slots_out.write(dense as usize, (lat_e7, lon_e7)) };+ state.claimed += 1;+ } else {+ duplicate.store(true, Ordering::Relaxed);+ }+ }+ Ok(kinds)+ },+ |chunk| {+ node_count += chunk.claimed;+ for (dense, code) in chunk.stops {+ stop.set(u64::from(dense));+ stop_codes.push((dense, code));+ }+ Ok(())+ },+ )?;+ }+ if duplicate.load(Ordering::Relaxed) {+ eprintln!("WARN: a node id occurs more than once; redoing the node scan serially");+ coords.iter_mut().for_each(|c| *c = (0, 0));+ present = Bitset::new(u64::from(slots));+ stop = Bitset::new(u64::from(slots));+ stop_codes.clear();+ node_count = 0;+ let _ = pbf::run_pass_sink(+ input,+ &blobs,+ pbf::PassSpec { blob_kinds: Some(&blob_kinds), want: KIND_NODES, label: "Pass 2: node scan (serial)" },+ Pass2::default,+ |state, block| pass2_blob(state, block, &mask),+ |chunk| {+ for (dense, lat_e7, lon_e7) in chunk.locs {+ coords[dense as usize] = (lat_e7, lon_e7);+ if present.set(u64::from(dense)) {+ node_count += 1;+ }+ }+ for (dense, code) in chunk.stops {+ stop.set(u64::from(dense));+ stop_codes.push((dense, code));+ }+ Ok(())+ },+ )?;+ }+ println!(+ "Located {node_count} node(s); {} marked id(s) had no coordinates in the file",+ marked - node_count+ );++ // Stop codes go into the pool only after every way name is in it, in the+ // order pass 2 met them, so `road_names.bin` is unaffected by dense+ // addressing and by where the way names are interned.+ let index = NodeIndex { mask, present };++ // --- Collapse ------------------------------------------------------------+ let spill_dir = opts.spill_dir.clone().unwrap_or_else(|| out_dir.to_path_buf());+ let spill_pts_dir = opts.spill_pts_dir.clone().unwrap_or_else(|| spill_dir.clone());+ timer.switch("collapse");+ let mut collapsed = if opts.within_way_chains {+ collapse_within_ways(+ input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,+ slots, filter, &mut pool, &mut timer,+ )?+ } else {+ collapse_segments(+ input, &spill_dir, &spill_pts_dir, &blobs, &blob_kinds, &index, &coords, &stop,+ slots, filter, &mut pool, &mut timer,+ )?+ };++ let mut prog = crate::progress::Progress::new("Interning stop codes", stop_codes.len() as u64);+ for (_, code) in &stop_codes {+ pool.intern(code).map_err(io_err)?;+ prog.inc();+ }+ prog.finish();+ drop(stop_codes);+ timer.switch("rank-survivors");++ // `saturating_sub` because a file with no routable ways and no stop nodes+ // marks nothing, and there is then no largest id to index up to.+ let kept_count = cap_u32(+ "surviving node",+ collapsed.kept.build_rank(u64::from(slots).saturating_sub(1)),+ )?;+ let kept = collapsed.kept;+ println!(+ "Collapsed {node_count} node(s) -> {kept_count} ({} chain(s), {} split(s) for the \+ 256-point limit)",+ collapsed.chain_count, collapsed.splits+ );+ cap_u32("chain", collapsed.chain_count)?;+ let raw_edge_count = collapsed.raw_edge_count;++ // --- Morton order -------------------------------------------------------+ // Deferred to here, and applied only to the survivors, because that is the+ // only set the device ever binary-searches. Sorting before the collapse would+ // have meant carrying a 64-bit spatial key through every node that was about+ // to be collapsed away.+ timer.switch("morton-sort");+ println!("Sorting {kept_count} surviving node(s) by spatial key...");+ // Keys on the pool, written in place: the kept bitset's rank says where+ // each slot range's keys start, so every range fills its own disjoint+ // slice and `keys` comes out exactly as the serial loop pushed it+ // (ascending `dense`) with no second copy.+ let mut keys: Vec<(u64, u32)> = vec![(0, 0); kept_count as usize];+ {+ const RANGE: usize = 1 << 20;+ let ranges: Vec<(usize, usize)> = (0..(slots as usize).div_ceil(RANGE))+ .map(|r| (r * RANGE, ((r + 1) * RANGE).min(slots as usize)))+ .collect();+ let mut pieces: Vec<KeyPiece<'_>> = Vec::with_capacity(ranges.len());+ let mut rest: &mut [(u64, u32)] = &mut keys;+ for &(lo, hi) in &ranges {+ // Kept ids below `hi` minus those below `lo`.+ let rank = |i: usize| -> usize {+ if i >= slots as usize {+ kept_count as usize+ } else {+ kept.dense(i as u64) as usize+ }+ };+ let (mine, tail) = rest.split_at_mut(rank(hi) - rank(lo));+ pieces.push(((lo, hi), mine));+ rest = tail;+ }+ debug_assert!(rest.is_empty());+ let coords = &coords;+ let kept = &kept;+ par::install(|| {+ pieces.par_iter_mut().for_each(|((lo, hi), out)| {+ let mut k = 0usize;+ for i in *lo as u32..*hi as u32 {+ if kept.get(u64::from(i)) {+ let (lat_e7, lon_e7) = coords[i as usize];+ out[k] = (spatial_from_e7(lat_e7, lon_e7), i);+ k += 1;+ }+ }+ debug_assert_eq!(k, out.len());+ });+ });+ }+ // The key is `(spatial, dense)`, and the keys are laid out with `dense`+ // ascending, so this is exactly the order the previous STABLE+ // `sort_by_key(spatial)` produced: ties there fell back to insertion order,+ // which was ascending `dense`. Spelling the tie-break into the key makes the+ // order total, and a total order is what lets an UNSTABLE parallel sort be+ // substituted without changing a single final id -- and final ids are what+ // `nodes.bin`, `edges.bin` and every offset in the pack are numbered by, so+ // this is the one comparison in the build that must not move.+ eprintln!("Sorting {kept_count} spatial key(s)...");+ par::install(|| keys.par_sort_unstable());++ // Final ids on the pool. `final_of_kept` is a permutation write (every+ // `dense` appears once in `keys`), `node_coords` an ordered map, and each+ // byte of `stops_final` a pure function of its own eight final ids.+ let mut final_of_kept = vec![0u32; kept_count as usize];+ let mut stops_final = Bitset::new(u64::from(kept_count));+ let node_coords: Vec<geom::Pt> = {+ let out = par::SyncPtr(final_of_kept.as_mut_ptr());+ let (keys, kept, coords, stop) = (&keys, &kept, &coords, &stop);+ par::install(|| {+ keys.par_iter().enumerate().for_each(|(final_id, (_, dense))| {+ // SAFETY: `keys` holds each kept dense id exactly once, so each+ // rank is written by exactly one iteration.+ unsafe { out.write(kept.dense(u64::from(*dense)) as usize, final_id as u32) };+ });+ stops_final.bits.par_chunks_mut(1 << 16).enumerate().for_each(|(ci, chunk)| {+ for (j, byte) in chunk.iter_mut().enumerate() {+ let base = ((ci << 16) + j) * 8;+ let mut v = 0u8;+ for k in 0..8 {+ if let Some((_, dense)) = keys.get(base + k) {+ if stop.get(u64::from(*dense)) {+ v |= 1 << k;+ }+ }+ }+ *byte = v;+ }+ });+ keys.par_iter().map(|(_, dense)| coords[*dense as usize]).collect()+ })+ };+ drop(keys);+ drop(stop);+ // The chain spill holds coordinates, so nothing downstream needs the array+ // indexed by *marked* node — the largest in the build — any longer.+ drop(coords);+ drop(index);+ let ids = FinalIds {+ kept: &kept,+ of_kept: &final_of_kept,+ };++ // --- The edge index -----------------------------------------------------+ timer.switch("edge-index");+ let csr = build_csr(&collapsed.spill, kept_count, &ids, &mut timer)?;++ // --- Reconnect isolated transit stops -----------------------------------+ timer.switch("components");+ let rec = reconnect_isolated_stops(&node_coords, &stops_final, &csr);+ let synth = rec.synth;+ drop(stops_final);++ // --- Write --------------------------------------------------------------+ // Load the optional DEM up front so a bad `--dem` path fails before the write starts. `None`+ // leaves `elevation.bin` unwritten and every node's baked elevation at 0.+ let dem = match &opts.dem {+ Some(path) => Some(crate::dem::Dem::load(path)?),+ None => None,+ };+ timer.switch("write");+ let written = write_graph(+ out_dir,+ &node_coords,+ &collapsed.spill,+ &collapsed.lane_pool,+ &csr,+ &synth,+ &ids,+ opts.round_count(),+ dem.as_ref(),+ &mut timer,+ )?;+ collapsed.spill.remove();+ let unique_names = pool.unique_count();+ let name_bytes = pool.byte_len();+ pool.finish().map_err(io_err)?;++ timer.finish();+ println!(+ "Done. Nodes: {} Edges: {} intermediate.bin: {} byte(s)",+ kept_count, written.edge_count, written.intermediate_bytes+ );+ Ok(Stats {+ node_count: u64::from(kept_count),+ edge_count: written.edge_count,+ unique_names,+ name_bytes,+ lcc_size: rec.lcc_size,+ stops_already_connected: rec.already_connected,+ reconnected_stops: synth.len() / 2,+ stops_unreachable: rec.unreachable,+ raw_node_count: node_count,+ raw_edge_count,+ chain_splits: collapsed.splits,+ 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,+ })+}++/// What either collapse strategy hands the writer.+///+/// Both produce the same thing — a chain spill plus the set of nodes that survive+/// — and differ only in how much memory it costs to get there and whether a chain+/// may cross from one OSM way into the next.+///+/// The chains are always on disk, even for the reference path that had them in+/// memory anyway, so that there is one writer. That also means `coords` — the+/// largest array in the build, and the only one indexed by *marked* rather than+/// surviving node — can be freed before the writer runs.+struct Collapsed {+ spill: chains::Spill,+ /// Dense ids that survive as graph nodes.+ kept: Bitset,+ lane_pool: Vec<u16>,+ chain_count: u64,+ splits: usize,+ raw_edge_count: u64,+}+
scripts/maps/osm_ingest/src/graph_build_part1_s2.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part1_s2.rs b/scripts/maps/osm_ingest/src/graph_build_part1_s2.rsnew file mode 100644index 0000000000..0c7f35c4c4--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part1_s2.rs@@ -0,0 +1,91 @@+/// The reference path: build every segment, then collapse chains across way+/// boundaries with [`compact`].+///+/// Kept as the baseline the within-way path is measured against. Its cost is the+/// segment array and the incidence CSR over it, which together are the reason a+/// planet build does not fit.+#[allow(clippy::too_many_arguments)]+fn collapse_segments<W: std::io::Write + Send>(+ input: &Path,+ spill_dir: &Path,+ spill_pts_dir: &Path,+ blobs: &[pbf::BlobLoc],+ blob_kinds: &[u8],+ index: &NodeIndex,+ coords: &[geom::Pt],+ stop: &Bitset,+ slots: u32,+ filter: RegionFilter,+ pool: &mut NamePool<W>,+ timer: &mut crate::timing::PhaseTimer,+) -> Result<Collapsed> {+ timer.switch("collapse-segments");+ // One record per consecutive way-node pair, still carrying both directions'+ // lane data. Splitting into directed edges is deferred until after+ // compaction, because pairing a `u -> v` edge with its `v -> u` twin is only+ // unambiguous while they are still one object.+ let mut segs: Vec<Seg> = Vec::new();+ let mut lane_pool: Vec<u16> = Vec::new();+ let way_kinds = pbf::run_pass_sink(+ input,+ blobs,+ pbf::PassSpec { blob_kinds: Some(blob_kinds), want: KIND_WAYS, label: "Pass 3: segments" },+ WayPass::default,+ |state, block| way_blob(state, block, index, coords, filter),+ |chunk| {+ let name_map = chunk.names.flush(pool).map_err(io_err)?;+ let lane_base = lane_pool.len() as u32;+ lane_pool.extend_from_slice(&chunk.lanes);+ cap_lane_pool(lane_pool.len())?;+ segs.reserve(chunk.segs.len());+ for mut s in chunk.segs {+ s.name_offset = if s.name_offset == u32::MAX {+ NO_NAME+ } else {+ name_map[s.name_offset as usize]+ };+ if s.fwd_lane_count > 0 {+ s.fwd_lane_off += lane_base;+ }+ if s.bwd_lane_count > 0 {+ s.bwd_lane_off += lane_base;+ }+ segs.push(s);+ }+ Ok(())+ },+ )?;+ report_way_blobs(blobs.len(), &way_kinds);++ let raw_edge_count: u64 = segs.iter().map(|s| if s.oneway { 1u64 } else { 2 }).sum();+ println!(+ "Built {} segment(s) ({raw_edge_count} directed edge(s) before compaction)",+ segs.len()+ );++ timer.switch("collapse-compact");+ let comp = compact::compact(slots, &segs, &lane_pool, |n| coords[n as usize], |n| {+ stop.get(u64::from(n))+ });+ drop(segs);++ // A slot with no coordinates has no segments either, so compaction has no+ // reason to collapse it and would hand it a real node id. Filter it out here+ // instead: this is the second half of the dangling-reference guard.+ let mut kept = Bitset::new(u64::from(slots));+ for i in 0..slots {+ if comp.new_id[i as usize] != REMOVED && index.present.get(u64::from(i)) {+ kept.set(u64::from(i));+ }+ }+ let spill = chains::Spill::split(spill_dir, spill_pts_dir);+ spill.write(&comp.chains, &comp.pts, coords)?;+ Ok(Collapsed {+ spill,+ kept,+ lane_pool,+ chain_count: comp.chains.len() as u64,+ splits: comp.splits,+ raw_edge_count,+ })+}
scripts/maps/osm_ingest/src/graph_build_part2.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part2.rs b/scripts/maps/osm_ingest/src/graph_build_part2.rsindex e41c0847a6..7a84b7073c 100644--- a/scripts/maps/osm_ingest/src/graph_build_part2.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part2.rs@@ -376,173 +376,4 @@ pub(crate) struct WayAttrs { pub bwd_lane_count: u16, } -fn way_blob(- state: &mut WayPass,- block: &pbf::PrimitiveBlock,- index: &NodeIndex,- coords: &[geom::Pt],- filter: RegionFilter,-) -> Result<u8> {- let mut kinds = 0u8;- visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {- let Element::Way(w) = el else {- return Ok(());- };- let type_ = tags::get_hw_id(w.tags.get_str("highway"));- if type_ == 0 {- return Ok(());- }- // Region filter: keep the way when ANY node touches the box (the- // `complete_ways` rule — truncating at the boundary would invent a- // vertex). Coordinates are resolved by now, so this is a direct test.- if let Some(b) = filter.as_ref() {- let mut touches = false;- for r in w.refs {- if let Some(d) = index.dense(*r) {- let (lat_e7, lon_e7) = coords[d as usize];- if b.contains_e7(lat_e7, lon_e7) {- touches = true;- break;- }- }- }- if !touches {- return Ok(());- }- }- let attrs = way_attrs(&w, type_, &mut state.lanes, &mut state.names);- for pair in w.refs.windows(2) {- // The same predicate the within-way path uses, so the two collapse- // paths agree on what a segment is. Asking a different question here- // would make the reference path emit a zero-length self-loop for a- // repeated ref, and the byte-identity comparison between the two would- // stop meaning anything.- let Some((u, v)) = chains::segment(index, pair[0], pair[1]) else {- continue;- };- let (a, b) = (coords[u as usize], coords[v as usize]);- state.segs.push(Seg {- u,- v,- dist_mm: accurate_dist_mm(a.0, a.1, b.0, b.1),- name_offset: attrs.name,- type_: attrs.type_,- speed_limit: attrs.speed_limit,- oneway: attrs.oneway,- fwd_lane_off: attrs.fwd_lane_off,- fwd_lane_count: attrs.fwd_lane_count,- bwd_lane_off: attrs.bwd_lane_off,- bwd_lane_count: attrs.bwd_lane_count,- });- }- Ok(())- })?;- Ok(kinds)-}--/// Lane masks are pushed into `lanes` and the name interned into `names`, both-/// chunk-local: the sink rebases the offsets when it folds the chunk in.-pub(crate) fn way_attrs(- w: &crate::osm::WayView,- type_: u8,- lanes: &mut Vec<u16>,- names: &mut LocalNames,-) -> WayAttrs {- let name = match w.tags.get("name") {- Some(n) => names.id(n),- None => u32::MAX,- };- let speed_limit = tags::parse_maxspeed(w.tags.get_str("maxspeed"));- let oneway = w.tags.get_str("oneway") == Some("yes");-- // Forward lanes come from turn:lanes:forward, or from plain turn:lanes on a- // oneway; backward from turn:lanes:backward. Plain `lanes*` only refine the- // count. No turn:lanes at all means no lane data, and the router infers lanes- // from junction topology instead.- let tl = w.tags.get_str("turn:lanes");- let tlf = w.tags.get_str("turn:lanes:forward");- let tlb = w.tags.get_str("turn:lanes:backward");- let count_all = tags::parse_int_tag(w.tags.get_str("lanes"));- let count_fwd = tags::parse_int_tag(w.tags.get_str("lanes:forward"));- let count_bwd = tags::parse_int_tag(w.tags.get_str("lanes:backward"));-- let fwd_spec = tlf.or(if oneway { tl } else { None });- let fwd_hint = if count_fwd > 0 {- count_fwd- } else if oneway {- count_all- } else {- 0- };- let bwd_spec = if oneway { None } else { tlb };- let fwd = tags::build_dir_lanes(fwd_spec, fwd_hint);- let bwd = tags::build_dir_lanes(bwd_spec, count_bwd);-- let mut push_lanes = |masks: &[u16]| -> (u32, u16) {- if masks.is_empty() {- return (NO_LANES, 0);- }- let off = lanes.len() as u32;- lanes.extend_from_slice(masks);- (off, masks.len() as u16)- };- let (fwd_lane_off, fwd_lane_count) = push_lanes(&fwd);- let (bwd_lane_off, bwd_lane_count) = push_lanes(&bwd);-- WayAttrs {- name,- type_,- speed_limit,- oneway,- fwd_lane_off,- fwd_lane_count,- bwd_lane_off,- bwd_lane_count,- }-}--fn pass2_blob(state: &mut Pass2, block: &pbf::PrimitiveBlock, mask: &Bitset) -> Result<u8> {- let mut kinds = 0u8;- visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {- if let Element::Node(n) = el {- if n.id < 0 || n.id as u64 >= BITSET_SIZE || !mask.get(n.id as u64) {- return Ok(());- }- let dense = mask.dense(n.id as u64);- // A `gtfs:stop_code:<feed>` tag means this node is a matched GTFS- // stop; its `name` (or the code itself) becomes the stop label the- // transit planner shows. Otherwise fall back to the plain OSM stop- // tags.- let gtfs_code = n- .tags- .iter()- .find(|(k, _)| k.starts_with(b"gtfs:stop_code:"))- .map(|(_, v)| n.tags.get("name").unwrap_or(v));- let stop_code = match gtfs_code {- Some(code) => Some(code),- None => tags::is_stop_node(- n.tags.get_str("highway"),- n.tags.get_str("railway"),- n.tags.get_str("public_transport"),- )- .then(|| n.tags.get("name").unwrap_or(UNNAMED_STOP)),- };- state.locs.push((dense, n.lat_e7, n.lon_e7));- if let Some(code) = stop_code {- state.stops.push((dense, code.to_vec()));- }- }- Ok(())- })?;- Ok(kinds)-}--/// What one stop-reconnection pass did, for [`Stats`] and for the log line that-/// makes [`MIN_ROUTABLE_COMPONENT`] auditable.-struct Reconnected {- lcc_size: u64,- /// Bidirectional connectors, sorted by `(source, target)`.- synth: Vec<Synth>,- already_connected: usize,- unreachable: usize,-}+include!("graph_build_part2_s1.rs");
scripts/maps/osm_ingest/src/graph_build_part2_s1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part2_s1.rs b/scripts/maps/osm_ingest/src/graph_build_part2_s1.rsnew file mode 100644index 0000000000..dfc580f8d1--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part2_s1.rs@@ -0,0 +1,170 @@+fn way_blob(+ state: &mut WayPass,+ block: &pbf::PrimitiveBlock,+ index: &NodeIndex,+ coords: &[geom::Pt],+ filter: RegionFilter,+) -> Result<u8> {+ let mut kinds = 0u8;+ visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {+ let Element::Way(w) = el else {+ return Ok(());+ };+ let type_ = tags::get_hw_id(w.tags.get_str("highway"));+ if type_ == 0 {+ return Ok(());+ }+ // Region filter: keep the way when ANY node touches the box (the+ // `complete_ways` rule — truncating at the boundary would invent a+ // vertex). Coordinates are resolved by now, so this is a direct test.+ if let Some(b) = filter.as_ref() {+ let mut touches = false;+ for r in w.refs {+ if let Some(d) = index.dense(*r) {+ let (lat_e7, lon_e7) = coords[d as usize];+ if b.contains_e7(lat_e7, lon_e7) {+ touches = true;+ break;+ }+ }+ }+ if !touches {+ return Ok(());+ }+ }+ let attrs = way_attrs(&w, type_, &mut state.lanes, &mut state.names);+ for pair in w.refs.windows(2) {+ // The same predicate the within-way path uses, so the two collapse+ // paths agree on what a segment is. Asking a different question here+ // would make the reference path emit a zero-length self-loop for a+ // repeated ref, and the byte-identity comparison between the two would+ // stop meaning anything.+ let Some((u, v)) = chains::segment(index, pair[0], pair[1]) else {+ continue;+ };+ let (a, b) = (coords[u as usize], coords[v as usize]);+ state.segs.push(Seg {+ u,+ v,+ dist_mm: accurate_dist_mm(a.0, a.1, b.0, b.1),+ name_offset: attrs.name,+ type_: attrs.type_,+ speed_limit: attrs.speed_limit,+ oneway: attrs.oneway,+ fwd_lane_off: attrs.fwd_lane_off,+ fwd_lane_count: attrs.fwd_lane_count,+ bwd_lane_off: attrs.bwd_lane_off,+ bwd_lane_count: attrs.bwd_lane_count,+ });+ }+ Ok(())+ })?;+ Ok(kinds)+}++/// Lane masks are pushed into `lanes` and the name interned into `names`, both+/// chunk-local: the sink rebases the offsets when it folds the chunk in.+pub(crate) fn way_attrs(+ w: &crate::osm::WayView,+ type_: u8,+ lanes: &mut Vec<u16>,+ names: &mut LocalNames,+) -> WayAttrs {+ let name = match w.tags.get("name") {+ Some(n) => names.id(n),+ None => u32::MAX,+ };+ let speed_limit = tags::parse_maxspeed(w.tags.get_str("maxspeed"));+ let oneway = w.tags.get_str("oneway") == Some("yes");++ // Forward lanes come from turn:lanes:forward, or from plain turn:lanes on a+ // oneway; backward from turn:lanes:backward. Plain `lanes*` only refine the+ // count. No turn:lanes at all means no lane data, and the router infers lanes+ // from junction topology instead.+ let tl = w.tags.get_str("turn:lanes");+ let tlf = w.tags.get_str("turn:lanes:forward");+ let tlb = w.tags.get_str("turn:lanes:backward");+ let count_all = tags::parse_int_tag(w.tags.get_str("lanes"));+ let count_fwd = tags::parse_int_tag(w.tags.get_str("lanes:forward"));+ let count_bwd = tags::parse_int_tag(w.tags.get_str("lanes:backward"));++ let fwd_spec = tlf.or(if oneway { tl } else { None });+ let fwd_hint = if count_fwd > 0 {+ count_fwd+ } else if oneway {+ count_all+ } else {+ 0+ };+ let bwd_spec = if oneway { None } else { tlb };+ let fwd = tags::build_dir_lanes(fwd_spec, fwd_hint);+ let bwd = tags::build_dir_lanes(bwd_spec, count_bwd);++ let mut push_lanes = |masks: &[u16]| -> (u32, u16) {+ if masks.is_empty() {+ return (NO_LANES, 0);+ }+ let off = lanes.len() as u32;+ lanes.extend_from_slice(masks);+ (off, masks.len() as u16)+ };+ let (fwd_lane_off, fwd_lane_count) = push_lanes(&fwd);+ let (bwd_lane_off, bwd_lane_count) = push_lanes(&bwd);++ WayAttrs {+ name,+ type_,+ speed_limit,+ oneway,+ fwd_lane_off,+ fwd_lane_count,+ bwd_lane_off,+ bwd_lane_count,+ }+}++fn pass2_blob(state: &mut Pass2, block: &pbf::PrimitiveBlock, mask: &Bitset) -> Result<u8> {+ let mut kinds = 0u8;+ visit_block(block, KIND_NODES, &mut kinds, &mut |el: Element| {+ if let Element::Node(n) = el {+ if n.id < 0 || n.id as u64 >= BITSET_SIZE || !mask.get(n.id as u64) {+ return Ok(());+ }+ let dense = mask.dense(n.id as u64);+ // A `gtfs:stop_code:<feed>` tag means this node is a matched GTFS+ // stop; its `name` (or the code itself) becomes the stop label the+ // transit planner shows. Otherwise fall back to the plain OSM stop+ // tags.+ let gtfs_code = n+ .tags+ .iter()+ .find(|(k, _)| k.starts_with(b"gtfs:stop_code:"))+ .map(|(_, v)| n.tags.get("name").unwrap_or(v));+ let stop_code = match gtfs_code {+ Some(code) => Some(code),+ None => tags::is_stop_node(+ n.tags.get_str("highway"),+ n.tags.get_str("railway"),+ n.tags.get_str("public_transport"),+ )+ .then(|| n.tags.get("name").unwrap_or(UNNAMED_STOP)),+ };+ state.locs.push((dense, n.lat_e7, n.lon_e7));+ if let Some(code) = stop_code {+ state.stops.push((dense, code.to_vec()));+ }+ }+ Ok(())+ })?;+ Ok(kinds)+}++/// What one stop-reconnection pass did, for [`Stats`] and for the log line that+/// makes [`MIN_ROUTABLE_COMPONENT`] auditable.+struct Reconnected {+ lcc_size: u64,+ /// Bidirectional connectors, sorted by `(source, target)`.+ synth: Vec<Synth>,+ already_connected: usize,+ unreachable: usize,+}
scripts/maps/osm_ingest/src/graph_build_part3.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part3.rs b/scripts/maps/osm_ingest/src/graph_build_part3.rsindex 3ae5f689f9..cceb93a9a7 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -191,392 +191,4 @@ struct Written { census: Census, } -/// Write the pack in `rounds` source-partitioned rounds.-///-/// # Why rounds, and not computed offsets-///-/// The obvious alternative is to compute each edge's index and `pwrite` it into-/// place. That is sound for `edges.bin` — fixed 14-byte records in a pre-sized-/// file — but wrong for the two blob files. The reader derives a polyline's length-/// from the next offset entry and a lane run's from the next index entry, so-/// `intermediate.bin` and `lanes.bin` are forced into edge-index order with-/// monotonic offsets, and writing a blob at a computed offset would mean knowing-/// every earlier blob's length first: a per-edge length array, a prefix sum and a-/// second encode pass.-///-/// Partitioning by source instead makes every write an append. Each round takes a-/// contiguous range of final node ids, scans the chain spill for the edges whose-/// *source* falls in that range, sorts that buffer, and writes both blobs, the-/// presence bitmap, the offset tables, `edges.bin` and `nodes.bin` sequentially.-/// Offsets come out monotonic by construction, `nodes.bin`'s running edge counter-/// works because the rounds ascend, and the `(source, target)` grouping the reader-/// and [`twin_is_unique`] depend on is restored within each round.-///-/// The cost is `rounds` sequential reads of the spill instead of one.-#[allow(clippy::too_many_arguments)]-fn write_graph(- out_dir: &Path,- node_coords: &[geom::Pt],- spill: &chains::Spill,- lane_pool: &[u16],- csr: &Csr,- synth: &[Synth],- ids: &FinalIds,- rounds: u32,- dem: Option<&crate::dem::Dem>,- timer: &mut crate::timing::PhaseTimer,-) -> Result<Written> {- let kept = node_coords.len() as u32;- let edge_count = csr.edge_count() + synth.len() as u64;- // `nodes.bin`'s `edge_ptr` is a `u32`, so an edge count past that ceiling would- // wrap and point a node at another node's edge range.- cap_u32("directed edge", edge_count)?;- println!("Writing {edge_count} edge(s) in {rounds} round(s)...");- let chain_total = spill.chain_count()?;-- let mut nodes_blocked = ParBlocked::create(12, &out_dir.join("nodes.blocked.tmp"))- .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?;- 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- // (see [`GeomFile`]). `lanes.bin` is sparse and so cannot size its index up- // front; its blob streams to scratch instead and the index is written in front- // of it.- let mut inter = GeomFile::create(out_dir, "intermediate.bin", edge_count)?;- let mut lanes = LaneFile::create(out_dir, "lanes.bin")?;-- let mut buffer: Vec<TmpEdge> = Vec::new();- let points = spill.points()?;- let pmap = chains::points_map(&points);- let mut edge_ptr: u64 = 0;- let mut geometry_edges: u64 = 0;- let mut reversed_edges: u64 = 0;- let mut census = Census::default();- // One assignment scan instead of one scan per round: every chain's round- // is a pure function of its endpoints' final ids, so a single pass over- // the mapped headers records each chain's index per round and every round- // gathers only its chains. Chain order within a round is ascending index —- // the order the old per-round scan visited — so the buffer, the sort, and- // everything downstream are identical.- //- // Parallel: fixed contiguous chunks of chain indices, each producing its- // own per-round lists, concatenated in chunk order — so every list is still- // ascending and identical to the serial scan's.- timer.switch("write-scan");- let headers = spill.headers_mapped()?;- let chain_total_now = headers.len()?;- if chain_total_now != chain_total {- return Err(Error(format!(- "chains.hdr holds {chain_total_now} chain(s), expected {chain_total}"- )));- }- let round_lo = |round: u32| (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;- let by_round: Vec<Vec<u32>> = {- let n_chunks = (chain_total as usize).div_ceil(SCAN_CHUNK);- let chunk_ids: Vec<usize> = (0..n_chunks).collect();- let parts: Vec<Result<Vec<Vec<u32>>>> = par::map_chunks(&chunk_ids, 1, |_, ch| {- let c0 = (ch[0] * SCAN_CHUNK) as u64;- let c1 = (c0 + SCAN_CHUNK as u64).min(chain_total);- let mut mine: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];- for ci in c0..c1 {- let c = headers.get(ci)?;- let (a, b) = (ids.get(c.first), ids.get(c.last));- // A chain enters a round when the old scan would have buffered an- // edge for it there: source endpoint in range, or (two-way) target- // endpoint in range. One entry per qualifying round — a chain whose- // endpoints straddle a boundary is gathered twice, once per round,- // exactly as the old scan buffered it twice.- for round in 0..rounds {- let (lo, hi) = (round_lo(round), round_lo(round + 1));- if (lo..hi).contains(&a) || (!c.oneway && (lo..hi).contains(&b)) {- mine[round as usize].push(ci as u32);- }- }- }- Ok(mine)- });- let mut by_round: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];- let mut sizes = vec![0usize; rounds as usize];- for p in parts.iter().filter_map(|p| p.as_ref().ok()) {- for (r, v) in p.iter().enumerate() {- sizes[r] += v.len();- }- }- for (r, v) in by_round.iter_mut().enumerate() {- v.reserve_exact(sizes[r]);- }- for p in parts {- for (r, v) in p?.into_iter().enumerate() {- by_round[r].extend_from_slice(&v);- }- }- by_round- };-- for round in 0..rounds {- // Split by node count. Contiguous and ascending, so the four output streams- // stay append-only across the whole run.- let lo = round_lo(round);- let hi = round_lo(round + 1);- timer.switch("write-scan");-- // Gather: this round's chains in ascending index order — the visit- // order of the old per-round scan. Parallel over fixed chunks of the- // round's list, concatenated in chunk order, so the buffer is the- // serial one element for element.- buffer.clear();- let gathered: Vec<Result<Vec<TmpEdge>>> =- par::map_chunks(&by_round[round as usize], SCAN_CHUNK, |_, chunk| {- let mut out = Vec::with_capacity(chunk.len() + chunk.len() / 2);- for &ci in chunk {- let c = headers.get(u64::from(ci))?;- let (a, b) = (ids.get(c.first), ids.get(c.last));- if (lo..hi).contains(&a) {- out.push(chain_edge(&c, ci, a, b, false));- }- if !c.oneway && (lo..hi).contains(&b) {- out.push(chain_edge(&c, ci, b, a, true));- }- }- Ok(out)- });- let synth_lo = synth.partition_point(|s| s.source < lo);- let synth_hi = synth.partition_point(|s| s.source < hi);- let gathered_len: usize = gathered.iter().map(|g| g.as_ref().map_or(0, Vec::len)).sum();- buffer.reserve_exact(gathered_len + (synth_hi - synth_lo));- for g in gathered {- buffer.extend_from_slice(&g?);- }- for s in &synth[synth_lo..synth_hi] {- buffer.push(TmpEdge {- source: s.source,- target: s.target,- dist_mm: s.dist_mm,- name_offset: NO_NAME,- type_: RECONNECT_TYPE,- speed_limit: RECONNECT_SPEED,- lane_off: NO_LANES,- lane_count: 0,- chain: NO_CHAIN,- chain_rev: false,- pts_start: 0,- pts_len: 0,- });- }-- // The CSR already knows how many edges this range owns. Checking against it- // catches both an edge landing in the wrong round and an edge whose source- // is not a surviving node — which is what the old- // `assert_eq!(cursor, edges.len())` was for, now checked per round and- // before anything is written rather than after everything is.- let expected = csr.edge_ptr[hi as usize] - csr.edge_ptr[lo as usize]- + (synth_hi - synth_lo) as u64;- if buffer.len() as u64 != expected {- return Err(Error(format!(- "round {round} covering node(s) {lo}..{hi} collected {} edge(s), \- but the edge index says {expected}",- buffer.len()- )));- }-- // Grouped by source for the reader, then by target so a node's parallel- // edges are adjacent, then by chain so the order is total.- //- // This was a STABLE sort on `(source, target, chain)` over a buffer built- // in chain order. The only elements that key leaves tied and that still- // differ are the two directions of a two-way self-loop chain — same- // source, target and chain — which the gather emits forward- // (`chain_rev == false`) first. Appending `chain_rev` to the key breaks- // exactly that tie the same way, and anything still tied is a- // byte-identical duplicate (a repeated connector), whose relative order- // cannot show. So the order is total over distinguishable elements and an- // UNSTABLE parallel in-place sort yields the stable sort's sequence — with- // no merge buffer, which at planet scale would be another 17 GB.- par::install(|| {- buffer.par_sort_unstable_by_key(|e| (e.source, e.target, e.chain, e.chain_rev))- });-- // --- write-write: parallel bake, in-order drain ------------------------- timer.switch("write-write");- write_round(- &buffer,- lo,- hi,- edge_ptr,- node_coords,- lane_pool,- csr,- synth,- pmap,- &mut WriteSinks {- nodes: &mut nodes_blocked,- edges: &mut edges_out,- inter: &mut inter,- lanes: &mut lanes,- census: &mut census,- geometry_edges: &mut geometry_edges,- reversed_edges: &mut reversed_edges,- },- round,- rounds,- )?;- edge_ptr += buffer.len() as u64;- }- drop(buffer);-- if edge_ptr != edge_count {- return Err(Error(format!(- "wrote {edge_ptr} edge(s) into a file sized for {edge_count}"- )));- }- finish_pack(- out_dir,- kept,- edge_count,- edge_ptr,- geometry_edges,- reversed_edges,- nodes_blocked,- edges_out,- inter,- lanes,- census,- node_coords,- dem,- )-}--/// Finish the four output streams and the metadata: the tail of `write_graph`-/// after the last round drains. Unchanged from the serial loop — the drain-/// above stages identical bytes, so everything downstream (sentinel, sanity-/// parses, metadata, elevation) is untouched.-#[allow(clippy::too_many_arguments)]-fn finish_pack(- out_dir: &Path,- kept: u32,- edge_count: u64,- edge_ptr: u64,- geometry_edges: u64,- reversed_edges: u64,- nodes_blocked: ParBlocked,- edges_out: EdgeFile,- inter: GeomFile,- lanes: LaneFile,- census: Census,- node_coords: &[geom::Pt],- dem: Option<&crate::dem::Dem>,-) -> Result<Written> {- let mut nodes_blocked = nodes_blocked;- // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of- // node v's edge range.- let mut sentinel = [0u8; 12];- sentinel[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());- nodes_blocked- .push(&sentinel)- .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;- // Streamed straight into the file (no in-memory copy of the section),- // then checked against the mapped result.- {- let mut out = BufWriter::with_capacity(WRITE_BUF_BYTES, create(&out_dir.join("nodes.bin"))?);- nodes_blocked- .finish_into(&mut out)- .map_err(|e| Error(format!("cannot finish nodes.bin: {e}")))?;- out.flush().map_err(io_err)?;- }- let nodes_map = crate::mem::Mapped::open(&out_dir.join("nodes.bin")).map_err(Error)?;- // Sanity: the blocked section must unpack to exactly the pushed records.- let parsed = tilecodec::blocked::Blocked::parse(&nodes_map).map_err(|e| {- Error(format!(- "freshly blocked nodes.bin does not parse: {e}"- ))- })?;- // Sanity: the blocked section must unpack to exactly the pushed records.- if parsed.unpacked_len() != (u64::from(kept) + 1) * 12 {- return Err(Error(format!(- "nodes.bin unpacks to {} byte(s) ({} 12-byte record(s)), not the {} record(s) \- pushed ({} byte(s))",- parsed.unpacked_len(),- parsed.unpacked_len() / 12,- u64::from(kept) + 1,- (u64::from(kept) + 1) * 12- )));- }- drop(nodes_map);- 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()?;- finish_pack_tail(- out_dir,- kept,- edge_count,- escape_count,- named_edges,- node_coords,- dem,- )?;- Ok(Written {- edge_count,- geometry_edges,- reversed_edges,- intermediate_bytes,- edges_bytes,- escape_count,- named_edges,- census,- })-}--/// Metadata + elevation tail of `write_graph`, after every stream finishes.-/// Split out so the round loop above reads as plan/bake/drain without the-/// file-assembly tail inline. Byte-identical: moved whole, order untouched.-#[allow(clippy::too_many_arguments)]-fn finish_pack_tail(- out_dir: &Path,- kept: u32,- edge_count: u64,- escape_count: u64,- named_edges: u64,- node_coords: &[geom::Pt],- dem: Option<&crate::dem::Dem>,-) -> Result<()> {- // metadata.bin's magic + version let the device refuse a pack directory- // holding files from two different vintages instead of misreading it, and its- // counts are what every other file's length is validated against.- let mut meta = create(&out_dir.join("metadata.bin"))?;- meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;- meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;- meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;- meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;- meta.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)?;- // elevation.bin: `i16[node_count]` metres, one per node in final-id order — an OPTIONAL sidecar- // like road_names.bin/lanes.bin, so a build without a DEM simply omits it and the device reads- // every node's elevation as 0. `node_coords` is already indexed by final node id, so a single- // forward pass matches the order `nodes.bin` was written in. Blocked like- // nodes/edges under the v7 layout (magic-dispatched on read, so absence- // still reads as all-zero).- if let Some(dem) = dem {- let mut elev_blocked = tilecodec::blocked::BlockedStreamWriter::create(- 2,- &out_dir.join("elevation.blocked.tmp"),- )- .map_err(|e| Error(format!("cannot stage elevation.bin: {e}")))?;- for &(lat_e7, lon_e7) in node_coords {- let lat = f64::from(lat_e7) * 1e-7;- let lon = f64::from(lon_e7) * 1e-7;- let metres = dem.sample_metres(lon, lat).unwrap_or(0);- elev_blocked- .push(&metres.to_le_bytes())- .map_err(|e| Error(format!("cannot stage elevation record: {e}")))?;- }- let elev_bytes = elev_blocked- .finish()- .map_err(|e| Error(format!("cannot finish elevation.bin: {e}")))?;- std::fs::write(out_dir.join("elevation.bin"), &elev_bytes).map_err(io_err)?;- }- Ok(())-}+include!("graph_build_part3_s1.rs");
scripts/maps/osm_ingest/src/graph_build_part3_s1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part3_s1.rs b/scripts/maps/osm_ingest/src/graph_build_part3_s1.rsnew file mode 100644index 0000000000..b26530d5ee--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part3_s1.rs@@ -0,0 +1,389 @@+/// Write the pack in `rounds` source-partitioned rounds.+///+/// # Why rounds, and not computed offsets+///+/// The obvious alternative is to compute each edge's index and `pwrite` it into+/// place. That is sound for `edges.bin` — fixed 14-byte records in a pre-sized+/// file — but wrong for the two blob files. The reader derives a polyline's length+/// from the next offset entry and a lane run's from the next index entry, so+/// `intermediate.bin` and `lanes.bin` are forced into edge-index order with+/// monotonic offsets, and writing a blob at a computed offset would mean knowing+/// every earlier blob's length first: a per-edge length array, a prefix sum and a+/// second encode pass.+///+/// Partitioning by source instead makes every write an append. Each round takes a+/// contiguous range of final node ids, scans the chain spill for the edges whose+/// *source* falls in that range, sorts that buffer, and writes both blobs, the+/// presence bitmap, the offset tables, `edges.bin` and `nodes.bin` sequentially.+/// Offsets come out monotonic by construction, `nodes.bin`'s running edge counter+/// works because the rounds ascend, and the `(source, target)` grouping the reader+/// and [`twin_is_unique`] depend on is restored within each round.+///+/// The cost is `rounds` sequential reads of the spill instead of one.+#[allow(clippy::too_many_arguments)]+fn write_graph(+ out_dir: &Path,+ node_coords: &[geom::Pt],+ spill: &chains::Spill,+ lane_pool: &[u16],+ csr: &Csr,+ synth: &[Synth],+ ids: &FinalIds,+ rounds: u32,+ dem: Option<&crate::dem::Dem>,+ timer: &mut crate::timing::PhaseTimer,+) -> Result<Written> {+ let kept = node_coords.len() as u32;+ let edge_count = csr.edge_count() + synth.len() as u64;+ // `nodes.bin`'s `edge_ptr` is a `u32`, so an edge count past that ceiling would+ // wrap and point a node at another node's edge range.+ cap_u32("directed edge", edge_count)?;+ println!("Writing {edge_count} edge(s) in {rounds} round(s)...");+ let chain_total = spill.chain_count()?;++ let mut nodes_blocked = ParBlocked::create(12, &out_dir.join("nodes.blocked.tmp"))+ .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?;+ 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+ // (see [`GeomFile`]). `lanes.bin` is sparse and so cannot size its index up+ // front; its blob streams to scratch instead and the index is written in front+ // of it.+ let mut inter = GeomFile::create(out_dir, "intermediate.bin", edge_count)?;+ let mut lanes = LaneFile::create(out_dir, "lanes.bin")?;++ let mut buffer: Vec<TmpEdge> = Vec::new();+ let points = spill.points()?;+ let pmap = chains::points_map(&points);+ let mut edge_ptr: u64 = 0;+ let mut geometry_edges: u64 = 0;+ let mut reversed_edges: u64 = 0;+ let mut census = Census::default();+ // One assignment scan instead of one scan per round: every chain's round+ // is a pure function of its endpoints' final ids, so a single pass over+ // the mapped headers records each chain's index per round and every round+ // gathers only its chains. Chain order within a round is ascending index —+ // the order the old per-round scan visited — so the buffer, the sort, and+ // everything downstream are identical.+ //+ // Parallel: fixed contiguous chunks of chain indices, each producing its+ // own per-round lists, concatenated in chunk order — so every list is still+ // ascending and identical to the serial scan's.+ timer.switch("write-scan");+ let headers = spill.headers_mapped()?;+ let chain_total_now = headers.len()?;+ if chain_total_now != chain_total {+ return Err(Error(format!(+ "chains.hdr holds {chain_total_now} chain(s), expected {chain_total}"+ )));+ }+ let round_lo = |round: u32| (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;+ let by_round: Vec<Vec<u32>> = {+ let n_chunks = (chain_total as usize).div_ceil(SCAN_CHUNK);+ let chunk_ids: Vec<usize> = (0..n_chunks).collect();+ let parts: Vec<Result<Vec<Vec<u32>>>> = par::map_chunks(&chunk_ids, 1, |_, ch| {+ let c0 = (ch[0] * SCAN_CHUNK) as u64;+ let c1 = (c0 + SCAN_CHUNK as u64).min(chain_total);+ let mut mine: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];+ for ci in c0..c1 {+ let c = headers.get(ci)?;+ let (a, b) = (ids.get(c.first), ids.get(c.last));+ // A chain enters a round when the old scan would have buffered an+ // edge for it there: source endpoint in range, or (two-way) target+ // endpoint in range. One entry per qualifying round — a chain whose+ // endpoints straddle a boundary is gathered twice, once per round,+ // exactly as the old scan buffered it twice.+ for round in 0..rounds {+ let (lo, hi) = (round_lo(round), round_lo(round + 1));+ if (lo..hi).contains(&a) || (!c.oneway && (lo..hi).contains(&b)) {+ mine[round as usize].push(ci as u32);+ }+ }+ }+ Ok(mine)+ });+ let mut by_round: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];+ let mut sizes = vec![0usize; rounds as usize];+ for p in parts.iter().filter_map(|p| p.as_ref().ok()) {+ for (r, v) in p.iter().enumerate() {+ sizes[r] += v.len();+ }+ }+ for (r, v) in by_round.iter_mut().enumerate() {+ v.reserve_exact(sizes[r]);+ }+ for p in parts {+ for (r, v) in p?.into_iter().enumerate() {+ by_round[r].extend_from_slice(&v);+ }+ }+ by_round+ };++ for round in 0..rounds {+ // Split by node count. Contiguous and ascending, so the four output streams+ // stay append-only across the whole run.+ let lo = round_lo(round);+ let hi = round_lo(round + 1);+ timer.switch("write-scan");++ // Gather: this round's chains in ascending index order — the visit+ // order of the old per-round scan. Parallel over fixed chunks of the+ // round's list, concatenated in chunk order, so the buffer is the+ // serial one element for element.+ buffer.clear();+ let gathered: Vec<Result<Vec<TmpEdge>>> =+ par::map_chunks(&by_round[round as usize], SCAN_CHUNK, |_, chunk| {+ let mut out = Vec::with_capacity(chunk.len() + chunk.len() / 2);+ for &ci in chunk {+ let c = headers.get(u64::from(ci))?;+ let (a, b) = (ids.get(c.first), ids.get(c.last));+ if (lo..hi).contains(&a) {+ out.push(chain_edge(&c, ci, a, b, false));+ }+ if !c.oneway && (lo..hi).contains(&b) {+ out.push(chain_edge(&c, ci, b, a, true));+ }+ }+ Ok(out)+ });+ let synth_lo = synth.partition_point(|s| s.source < lo);+ let synth_hi = synth.partition_point(|s| s.source < hi);+ let gathered_len: usize = gathered.iter().map(|g| g.as_ref().map_or(0, Vec::len)).sum();+ buffer.reserve_exact(gathered_len + (synth_hi - synth_lo));+ for g in gathered {+ buffer.extend_from_slice(&g?);+ }+ for s in &synth[synth_lo..synth_hi] {+ buffer.push(TmpEdge {+ source: s.source,+ target: s.target,+ dist_mm: s.dist_mm,+ name_offset: NO_NAME,+ type_: RECONNECT_TYPE,+ speed_limit: RECONNECT_SPEED,+ lane_off: NO_LANES,+ lane_count: 0,+ chain: NO_CHAIN,+ chain_rev: false,+ pts_start: 0,+ pts_len: 0,+ });+ }++ // The CSR already knows how many edges this range owns. Checking against it+ // catches both an edge landing in the wrong round and an edge whose source+ // is not a surviving node — which is what the old+ // `assert_eq!(cursor, edges.len())` was for, now checked per round and+ // before anything is written rather than after everything is.+ let expected = csr.edge_ptr[hi as usize] - csr.edge_ptr[lo as usize]+ + (synth_hi - synth_lo) as u64;+ if buffer.len() as u64 != expected {+ return Err(Error(format!(+ "round {round} covering node(s) {lo}..{hi} collected {} edge(s), \+ but the edge index says {expected}",+ buffer.len()+ )));+ }++ // Grouped by source for the reader, then by target so a node's parallel+ // edges are adjacent, then by chain so the order is total.+ //+ // This was a STABLE sort on `(source, target, chain)` over a buffer built+ // in chain order. The only elements that key leaves tied and that still+ // differ are the two directions of a two-way self-loop chain — same+ // source, target and chain — which the gather emits forward+ // (`chain_rev == false`) first. Appending `chain_rev` to the key breaks+ // exactly that tie the same way, and anything still tied is a+ // byte-identical duplicate (a repeated connector), whose relative order+ // cannot show. So the order is total over distinguishable elements and an+ // UNSTABLE parallel in-place sort yields the stable sort's sequence — with+ // no merge buffer, which at planet scale would be another 17 GB.+ par::install(|| {+ buffer.par_sort_unstable_by_key(|e| (e.source, e.target, e.chain, e.chain_rev))+ });++ // --- write-write: parallel bake, in-order drain ------------------------+ timer.switch("write-write");+ write_round(+ &buffer,+ lo,+ hi,+ edge_ptr,+ node_coords,+ lane_pool,+ csr,+ synth,+ pmap,+ &mut WriteSinks {+ nodes: &mut nodes_blocked,+ edges: &mut edges_out,+ inter: &mut inter,+ lanes: &mut lanes,+ census: &mut census,+ geometry_edges: &mut geometry_edges,+ reversed_edges: &mut reversed_edges,+ },+ round,+ rounds,+ )?;+ edge_ptr += buffer.len() as u64;+ }+ drop(buffer);++ if edge_ptr != edge_count {+ return Err(Error(format!(+ "wrote {edge_ptr} edge(s) into a file sized for {edge_count}"+ )));+ }+ finish_pack(+ out_dir,+ kept,+ edge_count,+ edge_ptr,+ geometry_edges,+ reversed_edges,+ nodes_blocked,+ edges_out,+ inter,+ lanes,+ census,+ node_coords,+ dem,+ )+}++/// Finish the four output streams and the metadata: the tail of `write_graph`+/// after the last round drains. Unchanged from the serial loop — the drain+/// above stages identical bytes, so everything downstream (sentinel, sanity+/// parses, metadata, elevation) is untouched.+#[allow(clippy::too_many_arguments)]+fn finish_pack(+ out_dir: &Path,+ kept: u32,+ edge_count: u64,+ edge_ptr: u64,+ geometry_edges: u64,+ reversed_edges: u64,+ nodes_blocked: ParBlocked,+ edges_out: EdgeFile,+ inter: GeomFile,+ lanes: LaneFile,+ census: Census,+ node_coords: &[geom::Pt],+ dem: Option<&crate::dem::Dem>,+) -> Result<Written> {+ let mut nodes_blocked = nodes_blocked;+ // Trailing sentinel so `graph.rs` can read node(v + 1).edge_ptr as the end of+ // node v's edge range.+ let mut sentinel = [0u8; 12];+ sentinel[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());+ nodes_blocked+ .push(&sentinel)+ .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;+ // Streamed straight into the file (no in-memory copy of the section),+ // then checked against the mapped result.+ {+ let mut out = BufWriter::with_capacity(WRITE_BUF_BYTES, create(&out_dir.join("nodes.bin"))?);+ nodes_blocked+ .finish_into(&mut out)+ .map_err(|e| Error(format!("cannot finish nodes.bin: {e}")))?;+ out.flush().map_err(io_err)?;+ }+ let nodes_map = crate::mem::Mapped::open(&out_dir.join("nodes.bin")).map_err(Error)?;+ // Sanity: the blocked section must unpack to exactly the pushed records.+ let parsed = tilecodec::blocked::Blocked::parse(&nodes_map).map_err(|e| {+ Error(format!(+ "freshly blocked nodes.bin does not parse: {e}"+ ))+ })?;+ // Sanity: the blocked section must unpack to exactly the pushed records.+ if parsed.unpacked_len() != (u64::from(kept) + 1) * 12 {+ return Err(Error(format!(+ "nodes.bin unpacks to {} byte(s) ({} 12-byte record(s)), not the {} record(s) \+ pushed ({} byte(s))",+ parsed.unpacked_len(),+ parsed.unpacked_len() / 12,+ u64::from(kept) + 1,+ (u64::from(kept) + 1) * 12+ )));+ }+ drop(nodes_map);+ 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()?;+ finish_pack_tail(+ out_dir,+ kept,+ edge_count,+ escape_count,+ named_edges,+ node_coords,+ dem,+ )?;+ Ok(Written {+ edge_count,+ geometry_edges,+ reversed_edges,+ intermediate_bytes,+ edges_bytes,+ escape_count,+ named_edges,+ census,+ })+}++/// Metadata + elevation tail of `write_graph`, after every stream finishes.+/// Split out so the round loop above reads as plan/bake/drain without the+/// file-assembly tail inline. Byte-identical: moved whole, order untouched.+#[allow(clippy::too_many_arguments)]+fn finish_pack_tail(+ out_dir: &Path,+ kept: u32,+ edge_count: u64,+ escape_count: u64,+ named_edges: u64,+ node_coords: &[geom::Pt],+ dem: Option<&crate::dem::Dem>,+) -> Result<()> {+ // metadata.bin's magic + version let the device refuse a pack directory+ // holding files from two different vintages instead of misreading it, and its+ // counts are what every other file's length is validated against.+ let mut meta = create(&out_dir.join("metadata.bin"))?;+ meta.write_all(&GRAPH_MAGIC.to_le_bytes()).map_err(io_err)?;+ meta.write_all(&GRAPH_VERSION.to_le_bytes()).map_err(io_err)?;+ meta.write_all(&u64::from(kept).to_le_bytes()).map_err(io_err)?;+ meta.write_all(&edge_count.to_le_bytes()).map_err(io_err)?;+ meta.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)?;+ // elevation.bin: `i16[node_count]` metres, one per node in final-id order — an OPTIONAL sidecar+ // like road_names.bin/lanes.bin, so a build without a DEM simply omits it and the device reads+ // every node's elevation as 0. `node_coords` is already indexed by final node id, so a single+ // forward pass matches the order `nodes.bin` was written in. Blocked like+ // nodes/edges under the v7 layout (magic-dispatched on read, so absence+ // still reads as all-zero).+ if let Some(dem) = dem {+ let mut elev_blocked = tilecodec::blocked::BlockedStreamWriter::create(+ 2,+ &out_dir.join("elevation.blocked.tmp"),+ )+ .map_err(|e| Error(format!("cannot stage elevation.bin: {e}")))?;+ for &(lat_e7, lon_e7) in node_coords {+ let lat = f64::from(lat_e7) * 1e-7;+ let lon = f64::from(lon_e7) * 1e-7;+ let metres = dem.sample_metres(lon, lat).unwrap_or(0);+ elev_blocked+ .push(&metres.to_le_bytes())+ .map_err(|e| Error(format!("cannot stage elevation record: {e}")))?;+ }+ let elev_bytes = elev_blocked+ .finish()+ .map_err(|e| Error(format!("cannot finish elevation.bin: {e}")))?;+ std::fs::write(out_dir.join("elevation.bin"), &elev_bytes).map_err(io_err)?;+ }+ Ok(())+}
scripts/maps/osm_ingest/src/graph_build_s1.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_s1.rs b/scripts/maps/osm_ingest/src/graph_build_s1.rsnew file mode 100644index 0000000000..ec6efdaffa--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_s1.rs@@ -0,0 +1,77 @@+impl AtomicBits<'_> {+ /// Set bit `idx`; true when this call is the one that set it. A plain load+ /// first, so re-marking an already-set bit (most refs: a node is shared by+ /// every way through it) never takes the cache line exclusive.+ #[inline]+ pub(crate) fn set(&self, idx: u64) -> bool {+ use std::sync::atomic::Ordering::Relaxed;+ let byte = &self.0[(idx / 8) as usize];+ let mask = 1u8 << (idx % 8);+ if byte.load(Relaxed) & mask != 0 {+ return false;+ }+ byte.fetch_or(mask, Relaxed) & mask == 0+ }+}++/// Dense addressing for the graph's nodes: which OSM ids are in the graph, and+/// which of those the file actually supplied coordinates for.+///+/// Both tests matter, and for different reasons. The mask is what makes+/// [`Bitset::dense`] meaningful. `present` is what keeps *dangling references*+/// out: pass 1 marks every ref of every routable way, including refs to nodes no+/// blob in the file defines — an extract clipped at a boundary is full of them —+/// and those slots never receive coordinates. Left in, each would read as+/// `(0, 0)`, a point in the Atlantic that corrupts distances, spatial keys and+/// polylines while leaving every count looking plausible.+pub(crate) struct NodeIndex {+ pub(crate) mask: Bitset,+ present: Bitset,+}++impl NodeIndex {+ /// Dense id of a node that is both in the graph and really in the file.+ #[inline]+ pub(crate) fn dense(&self, osm_id: i64) -> Option<u32> {+ if osm_id < 0 || osm_id as u64 >= BITSET_SIZE || !self.mask.get(osm_id as u64) {+ return None;+ }+ let d = self.mask.dense(osm_id as u64);+ self.present.get(u64::from(d)).then_some(d)+ }+}++#[derive(Default)]+struct Pass1 {+ /// Ids this chunk was the first to mark. Refs and stops are marked straight+ /// into the shared mask from the decode workers (a set union, so order+ /// cannot matter); only these two scalars reach the sink. Nothing about a+ /// way is retained, because the ways pass re-reads them.+ marked: u64,+ /// Largest id this chunk marked or found already marked.+ max_id: u64,+}++/// A region bbox filter, or `None` for a world build.+///+/// Passed by value into the block visitors (it is `Copy`): every routable way+/// whose nodes all fall outside is dropped, and a stop outside never enters+/// the graph. Ways are kept whole when any node touches — the same+/// `complete_ways` rule [`crate::bbox`] documents — so a road straddling the+/// border keeps its boundary stub rather than ending mid-segment.+pub type RegionFilter = Option<crate::bbox::BBox>;++include!("graph_build_part1.rs");+include!("graph_build_part2.rs");+include!("graph_build_part3.rs");+include!("graph_build_part4.rs");+include!("graph_build_part5.rs");+include!("graph_build_part11.rs");+#[cfg(test)]+mod tests {+ include!("graph_build_part6.rs");+ include!("graph_build_part7.rs");+ include!("graph_build_part8.rs");+ include!("graph_build_part9.rs");+ include!("graph_build_part10.rs");+}
scripts/maps/osm_ingest/src/mem.rs
diff --git a/scripts/maps/osm_ingest/src/mem.rs b/scripts/maps/osm_ingest/src/mem.rsindex df2f9f4609..afe066c349 100644--- a/scripts/maps/osm_ingest/src/mem.rs+++ b/scripts/maps/osm_ingest/src/mem.rs@@ -425,128 +425,4 @@ mod platform { } } -/// Ask the filesystem to store an EMPTY scratch file uncompressed. Best effort: a no-op-/// anywhere but Linux, and any refusal (not btrfs, flag unsupported, file already has-/// data) is ignored -- the file then behaves exactly as it did before.-///-/// Why this exists: the build box mounts btrfs with `compress-force=zstd:3`, which-/// compresses every extent in 128 KiB units regardless of whether the data shrinks. For-/// `nodeloc`'s 83 GB coordinate table (planet) the data does not shrink (`compsize`: 94%)-/// and the access is random 8-byte reads through a mapping, so every 4 KiB page fault that-/// misses the page cache inflates a whole 128 KiB extent: ~32x read amplification and a-/// zstd decode per fault. Measured on the Nov 10 planet build, the lane-inheritance scan-/// ran at 4-5 cores with ~190 threads in `D` state on those faults.-///-/// btrfs only skips compression (even under `compress-force`) for a NOCOW inode-/// (`FS_NOCOW_FL`, `chattr +C`), and NOCOW only takes on a file with no data yet -- so-/// call this right after `create`/`truncate`, before the first write. Scratch only: NOCOW-/// also drops data checksums, which is fine for a file the same process deletes.-///-/// Bytes read back are identical either way; this changes only how the filesystem stores-/// them.-/// Where named scratch files go: `MAPS_SCRATCH_DIR` if set, else the directory a tool set with-/// [`set_scratch_dir`] (mamaps_build: the build's own scratch directory, next to its spills),-/// else the system temp dir. Path only: nothing written there is observable in any output.-pub fn scratch_dir() -> std::path::PathBuf {- if let Some(dir) = std::env::var_os("MAPS_SCRATCH_DIR").filter(|d| !d.is_empty()) {- return std::path::PathBuf::from(dir);- }- SCRATCH_DIR.lock().expect("the scratch dir setting").clone().unwrap_or_else(std::env::temp_dir)-}--/// Set the default for [`scratch_dir`] (the `MAPS_SCRATCH_DIR` override still wins).-pub fn set_scratch_dir(dir: Option<std::path::PathBuf>) {- *SCRATCH_DIR.lock().expect("the scratch dir setting") = dir;-}--static SCRATCH_DIR: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);--/// Unlink a scratch file the caller keeps open (and possibly mapped), so the kernel frees its-/// blocks when the last handle closes -- on any exit, a kill included -- instead of leaving it on-/// disk. Returns whether the name is gone; on platforms that cannot delete an open file (Windows)-/// it does nothing and returns `false`, and the caller keeps deleting the file on drop.-pub fn unlink_open_scratch(path: &std::path::Path) -> bool {- #[cfg(unix)]- {- std::fs::remove_file(path).is_ok()- }- #[cfg(not(unix))]- {- let _ = path;- false- }-}--pub fn mark_scratch_uncompressed(file: &std::fs::File) {- #[cfg(target_os = "linux")]- {- use std::os::fd::AsRawFd;- const FS_NOCOW_FL: libc::c_long = 0x0080_0000;- let fd = file.as_raw_fd();- // `c_long` per the ioctl's declared size; the kernel reads/writes the low int.- let mut flags: libc::c_long = 0;- // SAFETY: `fd` is a live descriptor owned by `file`; both ioctls only read or write- // the flag word through the pointer, which outlives the calls.- unsafe {- if libc::ioctl(fd, libc::FS_IOC_GETFLAGS, &mut flags as *mut libc::c_long) != 0 {- return;- }- if flags & FS_NOCOW_FL != 0 {- return;- }- flags |= FS_NOCOW_FL;- let _ = libc::ioctl(fd, libc::FS_IOC_SETFLAGS, &flags as *const libc::c_long);- }- }- #[cfg(not(target_os = "linux"))]- {- let _ = file;- }-}--#[cfg(test)]-mod tests {- use super::*;-- /// Best effort means it must never fail or disturb the file: whatever the filesystem- /// under the temp dir, the file stays writable and reads back what was written.- #[test]- fn marking_scratch_uncompressed_never_changes_the_bytes() {- use std::io::{Read, Seek, Write};- let path = std::env::temp_dir().join(format!("osm_nocow_test_{}.bin", std::process::id()));- let mut f = std::fs::OpenOptions::new()- .read(true)- .write(true)- .create(true)- .truncate(true)- .open(&path)- .unwrap();- mark_scratch_uncompressed(&f);- f.write_all(b"same bytes either way").unwrap();- f.rewind().unwrap();- let mut back = String::new();- f.read_to_string(&mut back).unwrap();- drop(f);- let _ = std::fs::remove_file(&path);- assert_eq!(back, "same bytes either way");- }-- #[test]- fn vm_hwm_is_read_in_kilobytes() {- let status =- "Name:\troad_graph\nVmPeak:\t 9999999 kB\nVmHWM:\t 5212672 kB\nVmRSS:\t 12 kB\n";- assert_eq!(parse_vm_hwm(status), Some(5_212_672 * 1024));- // VmRSS must not be mistaken for the high-water mark, and a status file- // without the field (older kernels, or a sandbox) is absent, not zero.- assert_eq!(parse_vm_hwm("VmRSS:\t 12 kB\n"), None);- assert_eq!(parse_vm_hwm("VmHWM:\n"), None);- }-- #[test]- fn the_report_is_a_string_on_every_platform() {- let s = peak_rss_report();- assert!(!s.is_empty());- #[cfg(target_os = "linux")]- assert!(s.ends_with(" GB"), "{s}");- }-}+include!("mem_s1.rs");
scripts/maps/osm_ingest/src/mem_s1.rs
diff --git a/scripts/maps/osm_ingest/src/mem_s1.rs b/scripts/maps/osm_ingest/src/mem_s1.rsnew file mode 100644index 0000000000..db4da4f67b--- /dev/null+++ b/scripts/maps/osm_ingest/src/mem_s1.rs@@ -0,0 +1,125 @@+/// Ask the filesystem to store an EMPTY scratch file uncompressed. Best effort: a no-op+/// anywhere but Linux, and any refusal (not btrfs, flag unsupported, file already has+/// data) is ignored -- the file then behaves exactly as it did before.+///+/// Why this exists: the build box mounts btrfs with `compress-force=zstd:3`, which+/// compresses every extent in 128 KiB units regardless of whether the data shrinks. For+/// `nodeloc`'s 83 GB coordinate table (planet) the data does not shrink (`compsize`: 94%)+/// and the access is random 8-byte reads through a mapping, so every 4 KiB page fault that+/// misses the page cache inflates a whole 128 KiB extent: ~32x read amplification and a+/// zstd decode per fault. Measured on the Nov 10 planet build, the lane-inheritance scan+/// ran at 4-5 cores with ~190 threads in `D` state on those faults.+///+/// btrfs only skips compression (even under `compress-force`) for a NOCOW inode+/// (`FS_NOCOW_FL`, `chattr +C`), and NOCOW only takes on a file with no data yet -- so+/// call this right after `create`/`truncate`, before the first write. Scratch only: NOCOW+/// also drops data checksums, which is fine for a file the same process deletes.+///+/// Bytes read back are identical either way; this changes only how the filesystem stores+/// them.+/// Where named scratch files go: `MAPS_SCRATCH_DIR` if set, else the directory a tool set with+/// [`set_scratch_dir`] (mamaps_build: the build's own scratch directory, next to its spills),+/// else the system temp dir. Path only: nothing written there is observable in any output.+pub fn scratch_dir() -> std::path::PathBuf {+ if let Some(dir) = std::env::var_os("MAPS_SCRATCH_DIR").filter(|d| !d.is_empty()) {+ return std::path::PathBuf::from(dir);+ }+ SCRATCH_DIR.lock().expect("the scratch dir setting").clone().unwrap_or_else(std::env::temp_dir)+}++/// Set the default for [`scratch_dir`] (the `MAPS_SCRATCH_DIR` override still wins).+pub fn set_scratch_dir(dir: Option<std::path::PathBuf>) {+ *SCRATCH_DIR.lock().expect("the scratch dir setting") = dir;+}++static SCRATCH_DIR: std::sync::Mutex<Option<std::path::PathBuf>> = std::sync::Mutex::new(None);++/// Unlink a scratch file the caller keeps open (and possibly mapped), so the kernel frees its+/// blocks when the last handle closes -- on any exit, a kill included -- instead of leaving it on+/// disk. Returns whether the name is gone; on platforms that cannot delete an open file (Windows)+/// it does nothing and returns `false`, and the caller keeps deleting the file on drop.+pub fn unlink_open_scratch(path: &std::path::Path) -> bool {+ #[cfg(unix)]+ {+ std::fs::remove_file(path).is_ok()+ }+ #[cfg(not(unix))]+ {+ let _ = path;+ false+ }+}++pub fn mark_scratch_uncompressed(file: &std::fs::File) {+ #[cfg(target_os = "linux")]+ {+ use std::os::fd::AsRawFd;+ const FS_NOCOW_FL: libc::c_long = 0x0080_0000;+ let fd = file.as_raw_fd();+ // `c_long` per the ioctl's declared size; the kernel reads/writes the low int.+ let mut flags: libc::c_long = 0;+ // SAFETY: `fd` is a live descriptor owned by `file`; both ioctls only read or write+ // the flag word through the pointer, which outlives the calls.+ unsafe {+ if libc::ioctl(fd, libc::FS_IOC_GETFLAGS, &mut flags as *mut libc::c_long) != 0 {+ return;+ }+ if flags & FS_NOCOW_FL != 0 {+ return;+ }+ flags |= FS_NOCOW_FL;+ let _ = libc::ioctl(fd, libc::FS_IOC_SETFLAGS, &flags as *const libc::c_long);+ }+ }+ #[cfg(not(target_os = "linux"))]+ {+ let _ = file;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Best effort means it must never fail or disturb the file: whatever the filesystem+ /// under the temp dir, the file stays writable and reads back what was written.+ #[test]+ fn marking_scratch_uncompressed_never_changes_the_bytes() {+ use std::io::{Read, Seek, Write};+ let path = std::env::temp_dir().join(format!("osm_nocow_test_{}.bin", std::process::id()));+ let mut f = std::fs::OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .truncate(true)+ .open(&path)+ .unwrap();+ mark_scratch_uncompressed(&f);+ f.write_all(b"same bytes either way").unwrap();+ f.rewind().unwrap();+ let mut back = String::new();+ f.read_to_string(&mut back).unwrap();+ drop(f);+ let _ = std::fs::remove_file(&path);+ assert_eq!(back, "same bytes either way");+ }++ #[test]+ fn vm_hwm_is_read_in_kilobytes() {+ let status =+ "Name:\troad_graph\nVmPeak:\t 9999999 kB\nVmHWM:\t 5212672 kB\nVmRSS:\t 12 kB\n";+ assert_eq!(parse_vm_hwm(status), Some(5_212_672 * 1024));+ // VmRSS must not be mistaken for the high-water mark, and a status file+ // without the field (older kernels, or a sandbox) is absent, not zero.+ assert_eq!(parse_vm_hwm("VmRSS:\t 12 kB\n"), None);+ assert_eq!(parse_vm_hwm("VmHWM:\n"), None);+ }++ #[test]+ fn the_report_is_a_string_on_every_platform() {+ let s = peak_rss_report();+ assert!(!s.is_empty());+ #[cfg(target_os = "linux")]+ assert!(s.ends_with(" GB"), "{s}");+ }+}
scripts/maps/osm_ingest/src/nodeloc.rs
diff --git a/scripts/maps/osm_ingest/src/nodeloc.rs b/scripts/maps/osm_ingest/src/nodeloc.rsindex 81f0215386..ff5f4075d1 100644--- a/scripts/maps/osm_ingest/src/nodeloc.rs+++ b/scripts/maps/osm_ingest/src/nodeloc.rs@@ -386,134 +386,4 @@ fn get_uvarint(bytes: &[u8]) -> (u64, usize) { (value, bytes.len()) } -impl NodeLocations {- /// `ids` need not be sorted or unique; both are done here.- ///- /// Fallible because the coordinate array is a mapped file, and a temporary directory that is full- /// or read-only is a real thing to report rather than to panic on.- pub fn new(mut ids: Vec<i64>) -> Result<NodeLocations> {- ids.sort_unstable();- ids.dedup();- let index = NodeIds::build(&ids);- // The plain vector goes here rather than being kept alongside: it is 8 bytes per id against- // the index's ~1.2, and holding both would give back the saving. Freed before the coordinate- // array is mapped, so the two never peak together.- drop(ids);- let locs = Locs::new(index.len())?;- Ok(NodeLocations { ids: index, locs })- }-- /// The same table from an **ascending, unique** id stream of known length.- ///- /// [`Self::new`] takes a vector because most callers have one. A continental or planet extract- /// does not want one: [`crate::extract`]-shaped callers hold the needed ids as a bitset over the- /// node id space, which is a fixed ~1.7 GB for any extract, and turning that back into 8 bytes an- /// id to hand it over would be the allocation the bitset exists to avoid.- ///- /// **Sorted and unique is a precondition, not a request.** It is what makes every gap positive,- /// and an out-of-order id would encode as a ten-byte varint and quietly corrupt the index. A- /// bitset walked low to high satisfies it by construction, which is the only reason this is safe- /// to expose.- pub fn from_sorted(ids: impl Iterator<Item = i64>, len: usize) -> Result<NodeLocations> {- let index = NodeIds::build_sorted(ids, len);- let locs = Locs::new(index.len())?;- Ok(NodeLocations { ids: index, locs })- }-- /// The same table from an already-populated bitset over the id space, taking ownership of its- /// words: bit `i` set iff id `i` is needed, `len` the number of set bits.- ///- /// [`Self::from_sorted`] walks the caller's bitset into ids and re-sets them here, holding two- /// words arrays at once. This moves the words across and builds the rank directory in place, so- /// the peak is one bitset rather than two. The only production caller is the planet ref- /// collector; the vector path ([`Self::new`]) is untouched.- pub fn from_bitset(words: Vec<u64>, len: usize) -> Result<NodeLocations> {- let index = NodeIds::from_words(words, len);- let locs = Locs::new(index.len())?;- Ok(NodeLocations { ids: index, locs })- }-- pub fn len(&self) -> usize {- self.ids.len()- }-- pub fn is_empty(&self) -> bool {- self.ids.len() == 0- }-- fn index_of(&self, id: i64) -> Option<u64> {- self.ids.find(id)- }-- /// Whether `id` is one of the ids this table was built for.- ///- /// Distinct from [`Self::get`] returning `None`, which also means "in the set but the node pass- /// never found it" -- the legitimate case at an extract's cut edges.- pub fn contains(&self, id: i64) -> bool {- self.index_of(id).is_some()- }-- pub fn get(&self, id: i64) -> Option<(i32, i32)> {- self.locs.get(self.index_of(id)? as usize)- }-- /// Every ref's table index into `out` (cleared first), `false` as soon as one ref has no- /// coordinate -- exactly the refs [`Self::line`] would drop. Reads only the in-memory id index- /// and resolved bits, never the coordinate array: a caller that needs only some of a way's- /// coordinates (its ends, or a prefix) can then read just those with [`Self::coord_at`].- pub fn indices_if_complete(&self, refs: &[i64], out: &mut Vec<usize>) -> bool {- out.clear();- for &id in refs {- match self.index_of(id) {- Some(i) if self.locs.is_resolved(i as usize) => out.push(i as usize),-
Diff truncated.