maps: re-land parallel road_graph write pipeline (#perf)
- Commit
2987ad6c20d1573ebfa1f6768a214b7559a70a85- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-10 19:15 UTC (25 days ago)
- Parents
017a48a
road_graph's write-write subphase was a single-threaded loop: 814.7 s of a 1658 s planet build (49%), 8.4 s of 25.4 s on California. This re-lands the parallel bake/drain pipeline that was reverted, following the TODO(write-pipe) re-entry checklist in order. Step 1 - bake_batch unit-tested on synthetic buffers before any pool or drain existed (graph_build_part10.rs). The test reproduced the framing bug against the old bake_batch: it opened only the nodes up to its last edge's source, so the edgeless nodes at the END of a batch, and every node of an edgeless batch, never got a record (6 openers for a 10-node span; 0 for an edgeless span). The "12x nodes.bin duplication" was the gate's own message: it printed the unpacked BYTE count beside the expected RECORD count, so a slightly short nodes.bin read as 12x too long. bake_batch now walks the node span (the serial loop's own shape) and refuses any edge outside it; the gate message prints records and bytes on both sides. Step 2 - pool + in-order drain behind that test (graph_build_part11.rs): - each round's node range is cut into fixed 4096-node batches; a batch is a pure function of the sorted buffer, its span and its absolute first edge index (found by binary search), so it bakes anywhere; - batches bake on the pool a wave at a time while the main thread drains the previous wave strictly in batch order (rayon::join double buffering); a batch carries node records, narrowed edge records, escape/name/geometry/lane side tables keyed by edge offset, and its own census (sums and maxima only, merged exactly); - nodes.bin/edges.bin zstd blocks compress on the pool: tilecodec gains compress_block() + BlockedStreamWriter::push_frames(); each frame is a fresh level-10 encoder over one 4096-record block, so a frame is a pure function of its block. 256 blocks per flush, so scratch appends are 7-12 MiB instead of one ~10 KB write per block; - intermediate.bin gets an 8 MiB BufWriter and one write per batch. write-scan is parallel too: the round assignment and each round's gather run over fixed 64Ki-chain chunks concatenated in chunk order (identical lists/buffer), and the round sort is par_sort_unstable on (source, target, chain, chain_rev). The old stable sort on (source, target, chain) only left two distinguishable elements tied: the two directions of a two-way self-loop chain, emitted forward first, which chain_rev now orders the same way; anything still tied is a byte-identical duplicate. In-place, so no 17 GB merge buffer at planet scale. Step 3 - verified on california-latest.osm.pbf --region california, sha256 of all 7 output files vs the frozen baseline-bin/road_graph: identical at --rounds 1 and 3, and at --threads 1, 8 (rounds 3) and 192. cargo test -p osm_ingest: 300 passed. tilecodec's new frames-vs-records test passes (two pre-existing blocked tests fail on a test-helper bug that always emits 12-byte records; untouched). California wall (192 threads, Phase 4 running): 25.4 s -> 16.1 s; write-write 8.38 -> 1.29 s, write-scan 3.87 -> 0.83 s.
Diff
library/tilecodec/src/main/rust/src/blocked.rs
diff --git a/library/tilecodec/src/main/rust/src/blocked.rs b/library/tilecodec/src/main/rust/src/blocked.rsindex 084a7e8f03..83bfba4aec 100644--- a/library/tilecodec/src/main/rust/src/blocked.rs+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -262,6 +262,23 @@ pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> assemble_blocked(record_len, per_block, records.len(), &frames) } +/// One block's zstd frame: a fresh level-10 encoder over `block`, exactly what+/// [`BlockedStreamWriter`] writes for it. Public so a caller can compress+/// blocks on its own thread pool and hand the frames to+/// [`BlockedStreamWriter::push_frames`] in order.+#[cfg(feature = "write")]+pub fn compress_block(block: &[u8]) -> Vec<u8> {+ let cfg = zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ };+ let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");+ let mut frame = Vec::new();+ enc.compress(block, None, &mut frame)+ .expect("zstd encode of an in-memory block");+ frame+}+ /// Lay out header + offset table + frames. Shared by the whole-slice and /// streaming writers so the two cannot drift. #[cfg(feature = "write")]@@ -343,20 +360,42 @@ impl BlockedStreamWriter { fn flush_block(&mut self) -> std::io::Result<()> { use std::io::Write as _; let n = self.per_block as usize * self.record_len;- let cfg = zstd_rs::CompressionConfig {- level: 10,- ..zstd_rs::CompressionConfig::DEFAULT- };- let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");- let mut frame = Vec::new();- enc.compress(&self.block[..n], None, &mut frame)- .expect("zstd encode of an in-memory block");+ let frame = compress_block(&self.block[..n]); self.frames_out.write_all(&frame)?; self.frame_lens.push(frame.len() as u64); self.block.drain(..n); Ok(()) } + /// Bytes in one full block (`records_per_block * record_len`): the unit+ /// [`compress_block`] frames for [`BlockedStreamWriter::push_frames`].+ pub fn block_bytes(&self) -> usize {+ self.per_block as usize * self.record_len+ }++ /// Append whole blocks the caller already compressed with+ /// [`compress_block`] — the parallel form of [`BlockedStreamWriter::push`].+ ///+ /// Byte-identical to pushing the same records: every frame is an+ /// independent zstd frame of exactly one block, compressed by a fresh+ /// encoder at the same level, so a frame is a pure function of its block+ /// whoever compresses it. Only valid on a block boundary (nothing staged+ /// by `push`), and every frame must hold a full block. The frames go out in+ /// one write, so the scratch file sees large sequential appends.+ pub fn push_frames(&mut self, frames: &[Vec<u8>]) -> std::io::Result<()> {+ use std::io::Write as _;+ assert!(self.block.is_empty(), "push_frames needs a block boundary");+ let total: usize = frames.iter().map(Vec::len).sum();+ let mut joined = Vec::with_capacity(total);+ for f in frames {+ joined.extend_from_slice(f);+ self.frame_lens.push(f.len() as u64);+ }+ self.frames_out.write_all(&joined)?;+ self.records += frames.len() as u64 * u64::from(self.per_block);+ Ok(())+ }+ /// Compress the tail block, assemble header + table + frames, remove the /// scratch file, and return the section bytes. pub fn finish(mut self) -> std::io::Result<Vec<u8>> {@@ -364,14 +403,7 @@ impl BlockedStreamWriter { if !self.block.is_empty() { // Tail block: fewer than per_block records. Same framing; the // reader derives record counts from unpacked_len, never from drum-tight blocks.- let cfg = zstd_rs::CompressionConfig {- level: 10,- ..zstd_rs::CompressionConfig::DEFAULT- };- let mut enc = zstd_rs::Compressor::new(cfg).expect("valid zstd level");- let mut frame = Vec::new();- enc.compress(&self.block, None, &mut frame)- .expect("zstd encode of an in-memory block");+ let frame = compress_block(&self.block); self.frames_out.write_all(&frame)?; self.frame_lens.push(frame.len() as u64); }@@ -477,4 +509,23 @@ mod tests { records[9999 * 12..10_000 * 12] ); }++ #[test]+ fn pushing_precompressed_frames_matches_pushing_records() {+ let records = pattern_records(10_000, 12);+ let dir = std::env::temp_dir();+ let a = dir.join("tilecodec_blocked_frames_a.tmp");+ let b = dir.join("tilecodec_blocked_frames_b.tmp");+ let mut plain = BlockedStreamWriter::create(12, &a).expect("create");+ plain.push(&records).expect("push");+ let plain = plain.finish().expect("finish");+ let mut framed = BlockedStreamWriter::create(12, &b).expect("create");+ let bb = framed.block_bytes();+ let full = records.len() / bb * bb;+ let frames: Vec<Vec<u8>> = records[..full].chunks(bb).map(compress_block).collect();+ framed.push_frames(&frames).expect("frames");+ framed.push(&records[full..]).expect("tail");+ let framed = framed.finish().expect("finish");+ assert_eq!(framed, plain, "frames compressed elsewhere must be byte-identical");+ } }
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 6b1cc0b585..53892709bd 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -461,6 +461,7 @@ 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");
scripts/maps/osm_ingest/src/graph_build_part10.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part10.rs b/scripts/maps/osm_ingest/src/graph_build_part10.rsindex 9cc3299cf4..cf1d4320f4 100644--- a/scripts/maps/osm_ingest/src/graph_build_part10.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part10.rs@@ -160,3 +160,95 @@ assert!(parse_args(&["a".into(), "b".into()]).is_err()); assert!(parse_args(&["--wat".into()]).is_err()); }++ // ---------------------------------------------------------------------+ // TODO(write-pipe) re-entry checklist, step 1: bake_batch on a synthetic+ // buffer, before any pool or drain exists.+ // ---------------------------------------------------------------------++ /// A one-point `chains.pts` mapping: the synthetic edges carry no chain,+ /// so nothing reads it, but `bake_batch` takes the shared mapping.+ fn dummy_points(tag: &str) -> crate::mem::Mapped {+ let dir = std::env::temp_dir().join(format!("osm_ingest_bake_{tag}"));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(&dir).unwrap();+ let path = dir.join("chains.pts");+ std::fs::write(&path, [0u8; 8]).unwrap();+ crate::mem::Mapped::open(&path).unwrap()+ }++ /// `(node id, edge_ptr)` of every opener, in bake order.+ fn bake_openers(b: &BakedBatch) -> Vec<(u32, u32)> {+ (0..b.node_count())+ .map(|i| {+ let (lat, _, ptr) = b.opener(i);+ (lat as u32, ptr)+ })+ .collect()+ }++ #[test]+ fn bake_batch_opens_every_node_in_its_span_at_base_plus_run_offset() {+ // Nodes 10..20, whose lat_e7 is the node id so an opener names its node.+ let kept = 24u32;+ let node_coords: Vec<geom::Pt> = (0..kept).map(|i| (i as i32, 0)).collect();+ // Runs: 11 x2, 13 x1, 15 x3. Edgeless: 10 (leading), 12, 14 (interior),+ // 16..20 (trailing) — the trailing ones are the case a batch that ends+ // on an edgeless node must still open.+ let spec: &[(u32, u32)] = &[(11, 3), (11, 4), (13, 2), (15, 1), (15, 5), (15, 6)];+ let mut edges: Vec<TmpEdge> = spec.iter().map(|(s, t)| tmp_edge(*s, *t, 1000)).collect();+ // One escaped (dist past u24) and one named edge, to pin their offsets.+ edges[2].dist_mm = DIST_MM_ESCAPE;+ edges[4].name_offset = 77;+ let csr = csr_of(kept, spec);+ let points = dummy_points("span");+ let (first, end, base) = (10u32, 20u32, 100u64);+ let b =+ bake_batch(&edges, first, end, base, &node_coords, &[], &csr, &[], &points).unwrap();+ let openers = bake_openers(&b);+ assert_eq!(+ openers.len(),+ (end - first) as usize,+ "opener count must equal the node span"+ );+ let want: Vec<(u32, u32)> = vec![+ (10, 100),+ (11, 100),+ (12, 102),+ (13, 102),+ (14, 103),+ (15, 103),+ (16, 106),+ (17, 106),+ (18, 106),+ (19, 106),+ ];+ assert_eq!(openers, want, "opener edge_ptrs must be base + run offsets");+ // One record per edge, side tables keyed by the edge's offset in the batch.+ assert_eq!(b.edge_count, edges.len() as u64);+ assert_eq!(b.edge_recs.len(), edges.len() * EDGE_REC_BYTES as usize);+ assert_eq!(b.escapes, vec![(2, 2, DIST_MM_ESCAPE)]);+ assert_eq!(b.names, vec![(4, 77)]);+ // The census saw every node of the span, edgeless ones included.+ assert_eq!(b.census.degree_zero_nodes, 7);+ assert_eq!(b.census.max_degree, 3);+ }++ #[test]+ fn bake_batch_refuses_an_edge_outside_its_span() {+ let node_coords: Vec<geom::Pt> = (0..8).map(|i| (i, 0)).collect();+ let csr = csr_of(8, &[(6, 1)]);+ let points = dummy_points("stray");+ let edges = [tmp_edge(6, 1, 10)];+ assert!(bake_batch(&edges, 2, 6, 0, &node_coords, &[], &csr, &[], &points).is_err());+ }++ #[test]+ fn bake_batch_opens_a_wholly_edgeless_span() {+ let node_coords: Vec<geom::Pt> = (0..8).map(|i| (i, 0)).collect();+ let csr = csr_of(8, &[]);+ let points = dummy_points("edgeless");+ let b = bake_batch(&[], 2, 6, 7, &node_coords, &[], &csr, &[], &points).unwrap();+ assert_eq!(bake_openers(&b), vec![(2, 7), (3, 7), (4, 7), (5, 7)]);+ assert_eq!(b.edge_count, 0);+ }
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.rsnew file mode 100644index 0000000000..2bb1a80033--- /dev/null+++ b/scripts/maps/osm_ingest/src/graph_build_part11.rs@@ -0,0 +1,473 @@+// ---- the parallel write-write pipeline -----------------------------------+//+// Re-landed per the TODO(write-pipe) checklist: `bake_batch` is unit-tested on+// synthetic buffers (`graph_build_part10.rs`) for opener count == node span and+// opener edge_ptr == base + run offset, and the pool + in-order drain below sit+// behind that test. The framing bug that sank the first attempt was in+// `bake_batch`: it opened only the nodes up to its last edge's source, so the+// edgeless nodes at the END of a batch (and every node of an edgeless batch)+// never got a record. The "12x" reading was the gate's own message, which+// printed the unpacked BYTE count next to the expected RECORD count — so a+// slightly short nodes.bin read as twelve times too long.+//+// Shape: each round's node range is cut into fixed batches of+// [`WRITE_BATCH_NODES`] nodes. A batch is a pure function of the sorted round+// buffer, its node span and its absolute first edge index, so the pool bakes+// batches in any order; the main thread drains them strictly in batch order,+// which reproduces the serial byte sequence exactly. Baking a wave of batches+// overlaps with draining the previous wave (double buffering), and the two+// zstd-blocked streams compress whole 4096-record blocks on the pool+// ([`ParBlocked`]) instead of one block at a time on the drain thread.++/// Nodes per bake batch. A constant rather than a function of the thread+/// count, although nothing in the output depends on it: batches drain in+/// order, and a batch's bytes are exactly what the serial loop produced for+/// its span.+const WRITE_BATCH_NODES: u32 = 4096;++/// Batches baked per wave, per pool thread. A wave is what the drain consumes+/// while the next one bakes, so it bounds the bytes in flight to two waves.+const WAVE_BATCHES_PER_THREAD: usize = 4;++/// Whole blocks a [`ParBlocked`] stages before compressing them on the pool.+/// 256 blocks is 12 MiB of node records or 7 MiB of edge records per+/// parallel flush, which also makes each scratch-file append that large.+const PAR_BLOCKS: usize = 256;++/// A [`tilecodec::blocked::BlockedStreamWriter`] whose full blocks are+/// compressed on the pool.+///+/// Records stage here until [`PAR_BLOCKS`] whole blocks are waiting, then+/// those blocks compress in parallel ([`tilecodec::blocked::compress_block`]+/// is a pure function of one block) and go to the writer in order as frames.+/// The tail that never fills a block goes through the writer's own `push`, so+/// `finish` frames it exactly as before. Byte-identical to pushing every+/// record straight into the writer.+struct ParBlocked {+ w: tilecodec::blocked::BlockedStreamWriter,+ staged: Vec<u8>,+ block_bytes: usize,+}++impl ParBlocked {+ fn create(record_len: usize, scratch: &Path) -> std::io::Result<ParBlocked> {+ let w = tilecodec::blocked::BlockedStreamWriter::create(record_len, scratch)?;+ let block_bytes = w.block_bytes();+ Ok(ParBlocked {+ w,+ staged: Vec::with_capacity(block_bytes * PAR_BLOCKS * 2),+ block_bytes,+ })+ }++ /// Append whole records.+ #[inline]+ fn push(&mut self, records: &[u8]) -> std::io::Result<()> {+ self.staged.extend_from_slice(records);+ if self.staged.len() >= self.block_bytes * PAR_BLOCKS {+ self.flush_full()?;+ }+ Ok(())+ }++ /// Compress every whole staged block on the pool and hand the frames over+ /// in order; keep the partial tail staged.+ fn flush_full(&mut self) -> std::io::Result<()> {+ let full = self.staged.len() / self.block_bytes * self.block_bytes;+ if full == 0 {+ return Ok(());+ }+ let bb = self.block_bytes;+ let staged = &self.staged[..full];+ let frames: Vec<Vec<u8>> = par::install(|| {+ staged+ .par_chunks(bb)+ .map(tilecodec::blocked::compress_block)+ .collect()+ });+ self.w.push_frames(&frames)?;+ self.staged.drain(..full);+ Ok(())+ }++ fn finish(mut self) -> std::io::Result<Vec<u8>> {+ self.flush_full()?;+ let tail = std::mem::take(&mut self.staged);+ self.w.push(&tail)?;+ self.w.finish()+ }+}++/// One baked write batch: every byte the serial loop would have produced for+/// one span of nodes, staged per output stream.+///+/// Positional: `node_recs` holds one 12-byte record per node of the span+/// (edgeless ones included) with its ABSOLUTE `edge_ptr`; every per-edge side+/// table is keyed by the edge's offset within the batch, which the drain turns+/// into an absolute index by adding the batch's base. Nothing in here depends+/// on any other batch, which is what lets the pool bake them in any order.+#[derive(Default)]+struct BakedBatch {+ /// Node records, 12 B each, one per node of the span, in node order.+ node_recs: Vec<u8>,+ /// Edges in the batch.+ edge_count: u64,+ /// Edge records, 7 B each, already narrowed (escape sentinels in place).+ edge_recs: Vec<u8>,+ /// `(edge offset, target, dist_mm)` for each escaped edge, ascending.+ escapes: Vec<(u32, u32, u32)>,+ /// `(edge offset, name_offset)` for each named edge, ascending.+ names: Vec<(u32, u32)>,+ /// Encoded interior polylines of the storing edges, concatenated in order.+ geom: Vec<u8>,+ /// `(edge offset, blob length)` per storing edge, ascending.+ geom_runs: Vec<(u32, u32)>,+ /// Lane masks (`u16` LE) of the lane-bearing edges, concatenated in order.+ lanes: Vec<u8>,+ /// `(edge offset, byte length)` per lane-bearing edge, ascending.+ lane_runs: Vec<(u32, u32)>,+ /// The census over this batch's nodes and edges. Sums and maxima only, so+ /// merging batch censuses in any order equals the serial census.+ census: Census,+ geometry_edges: u64,+ reversed_edges: u64,+}++impl BakedBatch {+ /// Nodes in the batch's span.+ #[cfg(test)]+ fn node_count(&self) -> usize {+ self.node_recs.len() / 12+ }++ /// Node record `i` of the span as `(lat_e7, lon_e7, edge_ptr)`.+ #[cfg(test)]+ fn opener(&self, i: usize) -> (i32, i32, u32) {+ let r = &self.node_recs[i * 12..i * 12 + 12];+ (+ i32::from_le_bytes(r[0..4].try_into().expect("4 bytes")),+ i32::from_le_bytes(r[4..8].try_into().expect("4 bytes")),+ u32::from_le_bytes(r[8..12].try_into().expect("4 bytes")),+ )+ }+}++impl Census {+ /// Fold another census in. Every field is a count or a maximum, so this is+ /// order-independent and equals recording both sets of items into one.+ fn merge(&mut self, o: &Census) {+ for (a, b) in self.delta_bits.iter_mut().zip(o.delta_bits.iter()) {+ *a += *b;+ }+ self.delta_escapes += o.delta_escapes;+ self.dist_escapes += o.dist_escapes;+ self.escapes += o.escapes;+ self.max_delta = self.max_delta.max(o.max_delta);+ self.max_dist_mm = self.max_dist_mm.max(o.max_dist_mm);+ self.max_degree = self.max_degree.max(o.max_degree);+ self.degree_zero_nodes += o.degree_zero_nodes;+ self.named_edges += o.named_edges;+ }+}++/// Bake one write batch: the node span `first_node..end_node`, whose edges are+/// exactly `edges` (a source-sorted slice of the round buffer), with the+/// batch's first edge at absolute index `batch_edge_base`.+///+/// Walks the SPAN, not the edges — the serial loop's own shape — so every node+/// opens exactly once whether or not it has edges, and each opener's+/// `edge_ptr` is the base plus the edges before it in the batch. Per edge it+/// mirrors the serial body exactly: census, twin-check-before-read, polyline+/// read + reverse + `geom::fits` + `assert_endpoints` + encode, the narrowing+/// of [`EdgeFile::push`], name and lanes.+///+/// Pure over shared tables (`node_coords`, `lane_pool`, `csr`, `synth`, the+/// `chains.pts` mapping): safe across the pool. Fallible only like the serial+/// loop was — a truncated `chains.pts` fails the build rather than shortening+/// it — and the drain reports the first failure in batch order.+#[allow(clippy::too_many_arguments)]+fn bake_batch(+ edges: &[TmpEdge],+ first_node: u32,+ end_node: u32,+ batch_edge_base: u64,+ node_coords: &[geom::Pt],+ lane_pool: &[u16],+ csr: &Csr,+ synth: &[Synth],+ points: &crate::mem::Mapped,+) -> Result<BakedBatch> {+ let span = (end_node - first_node) as usize;+ let mut b = BakedBatch {+ node_recs: Vec::with_capacity(span * 12),+ edge_recs: Vec::with_capacity(edges.len() * EDGE_REC_BYTES as usize),+ ..BakedBatch::default()+ };+ let mut scratch: Vec<geom::Pt> = Vec::new();+ let mut cursor = 0usize;+ for v in first_node..end_node {+ let node = node_coords[v as usize];+ let edge_ptr = batch_edge_base + cursor as u64;+ b.node_recs.extend_from_slice(&node.0.to_le_bytes());+ b.node_recs.extend_from_slice(&node.1.to_le_bytes());+ b.node_recs.extend_from_slice(&(edge_ptr as u32).to_le_bytes());+ let degree_base = cursor;+ while cursor < edges.len() && edges[cursor].source == v {+ let e = &edges[cursor];+ let local = cursor as u32;+ let named = e.name_offset != NO_NAME;+ b.census.edge(e.source, e.target, e.dist_mm, named);++ // --- geometry ---+ let mut type_ = e.type_;+ // A two-point chain is just the chord between the edge's own+ // endpoints, and under the interior-only encoding that is what an+ // absent blob already means, so storing it would cost a presence+ // bit to say nothing — and a read to find that out.+ if e.chain != NO_CHAIN && e.pts_len >= 3 {+ if e.chain_rev+ && e.source != e.target+ && twin_is_unique(csr, synth, e.source, e.target)+ {+ type_ |= REVERSE_GEOMETRY_FLAG;+ b.reversed_edges += 1;+ } else {+ // Only now is the polyline needed: this is the only random+ // read in the writer, so every edge that defers to its twin+ // is one read saved. Shared mapping, no lock.+ chains::PointReader::read_shared(points, e.pts_start, e.pts_len, &mut scratch)?;+ if e.chain_rev {+ scratch.reverse();+ }+ assert!(+ geom::fits(&scratch),+ "chain of {} points cannot be encoded; the collapse should \+ have split it",+ scratch.len()+ );+ // The blob holds only the interior, so the reader rebuilds+ // both ends out of `nodes.bin`.+ assert_endpoints(&scratch, node_coords, e.source, e.target, e.chain);+ let before = b.geom.len();+ let n = geom::encode(&scratch, &mut b.geom);+ debug_assert_eq!(n as usize, geom::encoded_points(&scratch) as usize);+ b.geom_runs.push((local, (b.geom.len() - before) as u32));+ b.geometry_edges += 1;+ }+ }++ // --- the edge record: `EdgeFile::push`'s narrowing, verbatim ---+ let (delta, dist) = match target_delta(e.source, e.target) {+ Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm),+ _ => {+ b.escapes.push((local, e.target, e.dist_mm));+ (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)+ }+ };+ let mut rec = [0u8; EDGE_REC_BYTES as usize];+ rec[0..2].copy_from_slice(&delta.to_le_bytes());+ rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);+ rec[5] = type_;+ rec[6] = e.speed_limit;+ b.edge_recs.extend_from_slice(&rec);+ if named {+ b.names.push((local, e.name_offset));+ }++ // --- lanes ---+ if e.lane_count > 0 && e.lane_off != NO_LANES {+ let start = e.lane_off as usize;+ let before = b.lanes.len();+ for m in &lane_pool[start..start + e.lane_count as usize] {+ b.lanes.extend_from_slice(&m.to_le_bytes());+ }+ b.lane_runs.push((local, (b.lanes.len() - before) as u32));+ }+ cursor += 1;+ }+ b.census.node((cursor - degree_base) as u32);+ }+ // Every edge handed to the batch must belong to a node of its span: an edge+ // left over here would silently vanish from the pack.+ if cursor != edges.len() {+ return Err(Error(format!(+ "write batch over node(s) {first_node}..{end_node} left {} edge(s) unbaked \+ (first stray source {})",+ edges.len() - cursor,+ edges[cursor].source+ )));+ }+ b.edge_count = edges.len() as u64;+ Ok(b)+}++/// Everything the in-order drain appends to.+struct WriteSinks<'a> {+ nodes: &'a mut ParBlocked,+ edges: &'a mut EdgeFile,+ inter: &'a mut GeomFile,+ lanes: &'a mut LaneFile,+ census: &'a mut Census,+ geometry_edges: &'a mut u64,+ reversed_edges: &'a mut u64,+}++/// Append one baked batch, whose first edge is absolute index `base`.+///+/// Strictly positional, and the only writer into the streams: node records,+/// edge records, escape rows, name bits, presence bits and offsets, polyline+/// bytes and lane runs all go out exactly as the serial loop emitted them.+fn drain_batch(s: &mut WriteSinks, b: &BakedBatch, base: u64) -> Result<()> {+ debug_assert_eq!(s.edges.pushed, base, "batches drained out of order");+ s.nodes+ .push(&b.node_recs)+ .map_err(|e| Error(format!("cannot stage node record: {e}")))?;+ s.edges.push_baked(b, base)?;+ s.inter.store_batch(base, b)?;+ let mut at = 0usize;+ for &(local, len) in &b.lane_runs {+ s.lanes.push(base + u64::from(local), &b.lanes[at..at + len as usize])?;+ at += len as usize;+ }+ s.census.merge(&b.census);+ *s.geometry_edges += b.geometry_edges;+ *s.reversed_edges += b.reversed_edges;+ Ok(())+}++impl EdgeFile {+ /// Append a baked batch's records and side tables, its first edge being+ /// absolute index `base`. Same rows, bits and offsets as calling+ /// [`EdgeFile::push`] once per edge.+ fn push_baked(&mut self, b: &BakedBatch, base: u64) -> Result<()> {+ for &(local, target, dist) in &b.escapes {+ let idx = cap_u32("escaped edge index", base + u64::from(local))?;+ self.escapes.push((idx, target, dist));+ }+ self.blocked+ .push(&b.edge_recs)+ .map_err(|e| Error(format!("cannot stage edge record: {e}")))?;+ for &(local, off) in &b.names {+ self.named.set(base + u64::from(local));+ self.name_offsets.push(off);+ }+ self.pushed += b.edge_count;+ Ok(())+ }+}++impl GeomFile {+ /// Append a baked batch: presence bits, offset entries and polyline bytes+ /// for its storing edges, a skip for every other edge. Same state as the+ /// serial sequence of [`GeomFile::store`] / [`GeomFile::skip`] calls, with+ /// the batch's blob going out as one write.+ fn store_batch(&mut self, base: u64, b: &BakedBatch) -> Result<()> {+ for &(local, len) in &b.geom_runs {+ debug_assert!(len > 0, "an interior-only blob of no bytes is the chord");+ self.pushed = base + u64::from(local);+ self.present.set(self.pushed);+ self.push_entry();+ self.blob_len += u64::from(len);+ self.stored += 1;+ }+ self.out.write_all(&b.geom).map_err(io_err)?;+ self.pushed = base + b.edge_count;+ Ok(())+ }+}++/// Chains per parallel scan/gather chunk in the writer. Fixed, so chunking+/// cannot depend on the thread count (nor could it change the output: chunks+/// concatenate in order).+const SCAN_CHUNK: usize = 1 << 16;++/// Buffer for the writer's sequential output streams: large appends, since on+/// 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(())+}
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 032a06ebbe..3a2d1f55b0 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -191,64 +191,6 @@ struct Written { census: Census, } -/// One write worker's output for a batch of edges, in batch order.-///-/// Two shapes, interleaved in visit order: node openers (one per node the-/// batch owns, edgeless ones included) and edge items (one per edge). The-/// serial append folds them positionally — node record, then its edges — so-/// concatenation reproduces the serial byte sequence exactly. The geometry-/// decision rides along per edge (computed on the pool from the shared-/// mapping); census inputs ride along too (the census is additive, replayed-/// verbatim); node openers carry their own `edge_ptr` snapshot and degree so-/// the drain never recomputes running state.-enum BakedItem {- /// Open a node: stage its record, count its degree, tick it.- Node {- /// Node-record bytes (12 B) with the absolute edge pointer.- rec: [u8; 12],- /// Out-degree, for the census replay.- degree: u32,- },- /// One edge: census inputs, record inputs, geometry outcome, lanes.- /// Boxed: edges outnumber nodes ~3:1 and the small `Node` variant would- /// otherwise bloat every item to the edge size (the pool holds a whole- /// round's items at once).- Edge(Box<BakedEdge>),-}--/// One decided edge: record inputs, geometry outcome, census inputs, lanes.-struct BakedEdge {- /// Census inputs for the edge: source, target, dist, named. The edge- /// census is a pure function of these (histogram increments, maxima,- /// escape predicates), so the drain replays `Census::edge` verbatim.- cen_source: u32,- cen_target: u32,- cen_dist: u32,- cen_named: bool,- /// Edge record inputs: the delta/dist pair (or the escape sentinel with- /// its row), the final type byte, speed, and name.- delta: i16,- dist: u32,- escaped: Option<(u32, u32)>,- type_: u8,- speed_limit: u8,- name_offset: u32,- /// Geometry outcome: encoded interior blob, reverse-flag, or absent.- geom: BakedGeom,- /// Lane run values when the edge carries lanes.- lanes: Vec<u16>,-}--/// What the pool decided about one edge's geometry.-enum BakedGeom {- /// No blob: two-point chord, short chain, or no chain.- Absent,- /// Defer to the twin: set the reverse flag, store nothing.- Reversed,- /// Encoded interior blob, ready to stage.- Blob(Vec<u8>),-}- /// Write the pack in `rounds` source-partitioned rounds. /// /// # Why rounds, and not computed offsets@@ -292,11 +234,8 @@ fn write_graph( println!("Writing {edge_count} edge(s) in {rounds} round(s)..."); let chain_total = spill.chain_count()?; - let mut nodes_blocked = tilecodec::blocked::BlockedStreamWriter::create(- 12,- &out_dir.join("nodes.blocked.tmp"),- )- .map_err(|e| Error(format!("cannot stage nodes.bin: {e}")))?;+ 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@@ -307,13 +246,9 @@ fn write_graph( let mut inter = GeomFile::create(out_dir, "intermediate.bin", edge_count)?; let mut lanes = LaneFile::create(out_dir, "lanes.bin")?; - // Per-batch scratch lives on the workers in the pipeline design;- // the restored serial loop below reuses one triple, as before.- let mut scratch: Vec<geom::Pt> = Vec::new();- let mut encoded: Vec<u8> = Vec::new();- let mut lane_bytes: Vec<u8> = Vec::new(); let mut buffer: Vec<TmpEdge> = Vec::new();- let mut points = spill.points()?;+ 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;@@ -321,11 +256,13 @@ fn write_graph( // 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. `rounds` sequential header passes become one- // (the mapping stays resident for the gathers). Chain order within a- // round is ascending index — the order the old per-round scan visited —- // so the buffer, the sort (stable), and everything downstream are- // identical.+ // 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()?;@@ -334,55 +271,85 @@ fn write_graph( "chains.hdr holds {chain_total_now} chain(s), expected {chain_total}" ))); }- let mut by_round: Vec<Vec<u32>> = vec![Vec::new(); rounds as usize];- {- let mut prog =- crate::progress::Progress::new("Assign rounds".to_string(), chain_total);- // `ids.get` is two array lookups; the decode is 48 bytes. Both are- // dwarfed by the I/O the old code paid re-streaming per round.- for ci in 0..chain_total as u32 {- let c = headers.get(ci as u64)?;- 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 = (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;- let hi =- (u64::from(kept) * u64::from(round + 1) / u64::from(rounds)) as u32;- if (lo..hi).contains(&a) || (!c.oneway && (lo..hi).contains(&b)) {- by_round[round as usize].push(ci);+ 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 {+ if let Ok(p) = p {+ for (r, v) in p.iter().enumerate() {+ sizes[r] += v.len(); } }- prog.inc(); }- prog.finish();- }+ 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 = (u64::from(kept) * u64::from(round) / u64::from(rounds)) as u32;- let hi = (u64::from(kept) * u64::from(round + 1) / u64::from(rounds)) as u32;+ let lo = round_lo(round);+ let hi = round_lo(round + 1);+ timer.switch("write-scan"); - buffer.clear(); // Gather: this round's chains in ascending index order — the visit- // order of the old per-round scan, so buffer order pre-sort (and- // therefore post-sort, stable) is unchanged.- for &ci in &by_round[round as usize] {- let c = headers.get(ci as u64)?;- let (a, b) = (ids.get(c.first), ids.get(c.last));- if (lo..hi).contains(&a) {- buffer.push(chain_edge(&c, ci, a, b, false));- }- if !c.oneway && (lo..hi).contains(&b) {- buffer.push(chain_edge(&c, ci, b, a, true));- }- }+ // 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,@@ -416,118 +383,49 @@ fn write_graph( } // 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. The sort is- // stable and the buffer was built in chain order, so the two directions of- // a self-loop keep the order they were emitted in.- buffer.sort_by_key(|e| (e.source, e.target, e.chain));-- // --- write-write: serial drain over the sorted buffer ----------------- //- // A parallel bake/drain pipeline lived here (positional batches baked- // on the pool, drained in order). It failed the build's own gate:- // nodes.bin unpacked to 12x the pushed records while every counter- // (bake openers, drain openers, drain pushes) read exactly right —- // and the same 12x appeared with the bake forced single-threaded, so- // the duplication is not a threading race. The prime suspect is the- // batch/item framing itself (spans, bases, or the opener splice- // double-covering nodes), but rather than debug the framing blind,- // this restores the serial loop verbatim and keeps the pipeline- // design (plus the failing counters to re-prove against) in the- // task notes. The single-scan assignment above stays: it is proven- // (byte-identical CA hashes) and independent of the drain shape.+ // edges are adjacent, then by chain so the order is total. //- // TODO(write-pipe): re-land the pipeline. Re-entry checklist:- // 1. unit test bake_batch on a synthetic buffer FIRST (no build- // needed): assert opener count == node span and opener edge_ptrs- // == base + run offsets, before any pool or drain exists;- // 2. reintroduce pool + drain behind that test;- // 3. CA hash must equal the serial hash before any planet run.- timer.switch("write-write");- {- let mut wprog = crate::progress::Progress::new(- format!("Round {}/{rounds}: write", round + 1),- u64::from(hi - lo),- );- let mut cursor = 0usize;- for v in lo..hi {- let node = node_coords[v as usize];- let mut rec = [0u8; 12];- rec[0..4].copy_from_slice(&node.0.to_le_bytes());- rec[4..8].copy_from_slice(&node.1.to_le_bytes());- rec[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());- nodes_blocked- .push(&rec)- .map_err(|e| Error(format!("cannot stage node record: {e}")))?;- let degree_base = edge_ptr;- while cursor < buffer.len() && buffer[cursor].source == v {- let e = &buffer[cursor];- census.edge(e.source, e.target, e.dist_mm, e.name_offset != NO_NAME);+ // 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))+ }); - // --- geometry ---- let mut type_ = e.type_;- let mut stores = false;- // A two-point chain is just the chord between the edge's own- // endpoints, and under the interior-only encoding that is what an- // absent blob already means, so storing it would cost a presence- // bit to say nothing — and, more to the point here, a read to find- // that out.- if e.chain != NO_CHAIN && e.pts_len >= 3 {- if e.chain_rev- && e.source != e.target- && twin_is_unique(csr, synth, e.source, e.target)- {- type_ |= REVERSE_GEOMETRY_FLAG;- reversed_edges += 1;- } else {- // Only now is the polyline actually needed. Deciding the- // flag first matters more than it looks: this is the only- // random read in the writer, so every edge that defers to- // its twin is one seek saved, and on a filesystem whose- // syscalls are expensive that dominated the whole build.- points.read(e.pts_start, e.pts_len, &mut scratch)?;- if e.chain_rev {- scratch.reverse();- }- assert!(- geom::fits(&scratch),- "chain of {} points cannot be encoded; the collapse should \- have split it",- scratch.len()- );- // The blob holds only the interior, so the reader rebuilds- // both ends out of `nodes.bin`.- assert_endpoints(&scratch, node_coords, e.source, e.target, e.chain);- encoded.clear();- let n = geom::encode(&scratch, &mut encoded);- debug_assert_eq!(n as usize, geom::encoded_points(&scratch) as usize);- inter.store(&encoded)?;- geometry_edges += 1;- stores = true;- }- }- if !stores {- inter.skip();- }-- edges_out.push(e, type_)?;- if e.lane_count > 0 && e.lane_off != NO_LANES {- let start = e.lane_off as usize;- lane_bytes.clear();- for m in &lane_pool[start..start + e.lane_count as usize] {- lane_bytes.extend_from_slice(&m.to_le_bytes());- }- lanes.push(edge_ptr, &lane_bytes)?;- }- edge_ptr += 1;- cursor += 1;- }- census.node((edge_ptr - degree_base) as u32);- wprog.inc();- }- wprog.finish();- debug_assert_eq!(cursor, buffer.len(), "the round left edges unwritten");- }+ // --- 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!(@@ -563,7 +461,7 @@ fn finish_pack( edge_ptr: u64, geometry_edges: u64, reversed_edges: u64,- nodes_blocked: tilecodec::blocked::BlockedStreamWriter,+ nodes_blocked: ParBlocked, edges_out: EdgeFile, inter: GeomFile, lanes: LaneFile,@@ -594,9 +492,12 @@ fn finish_pack( // 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), not {} 12-byte records",+ "nodes.bin unpacks to {} byte(s) ({} 12-byte record(s)), not the {} record(s) \+ pushed ({} byte(s))", parsed.unpacked_len(),- u64::from(kept) + 1+ parsed.unpacked_len() / 12,+ u64::from(kept) + 1,+ (u64::from(kept) + 1) * 12 ))); } std::fs::write(out_dir.join("nodes.bin"), &nodes_bytes).map_err(io_err)?;@@ -677,207 +578,3 @@ fn finish_pack_tail( } Ok(()) }--/// Bake one write batch: every node record and edge record's bytes, decided.-///-/// Positional over the sorted edge buffer: `edges` are the buffer slice this-/// batch owns (one or more whole nodes' runs — batch boundaries fall on node-/// boundaries by construction), `first_node` the batch's first node id, and-/// `batch_edge_base` its edge index in the global order (so node records-/// carry their own absolute `edge_ptr`). Returns node openers interleaved-/// with their edges in the exact order the serial loop visited them (node-/// record, then its edges).-///-/// Pure over shared tables (`node_coords`, `lane_pool`, `csr`, `synth`,-/// `points`): safe across the pool. Fallible only like the serial loop was —-/// a truncated `chains.pts` fails the build rather than shortening it — and-/// the drain reports the first failure in batch order. `assert_endpoints` and-/// the `geom::fits` gate run here, on the worker that encoded: same-/// predicate, same message, same abort.-#[allow(clippy::too_many_arguments)]-fn bake_batch(- edges: &[TmpEdge],- first_node: u32,- batch_edge_base: u64,- node_coords: &[geom::Pt],- lane_pool: &[u16],- csr: &Csr,- synth: &[Synth],- points: &crate::mem::Mapped,-) -> Result<Vec<BakedItem>> {- let mut out: Vec<BakedItem> = Vec::new();- let mut scratch: Vec<geom::Pt> = Vec::new();- let mut encoded: Vec<u8> = Vec::new();- // The slice starts on a node boundary (batches partition the node range)- // but its first edge may belong to a later node than `first_node`:- // nodes between hold no edges (degree 0) and still open a record each.- let mut node = first_node;- let mut i = 0usize;- let mut edge_idx = batch_edge_base;- while i < edges.len() {- while node < edges[i].source {- out.push(baked_node(node, node_coords, edge_idx, 0));- node += 1;- }- // This run's edges, in slice order (source-sorted, then target, then- // chain — the serial order).- let source = edges[i].source;- debug_assert_eq!(source, node, "batch slices split a node's run");- let run_start = out.len();- let mut degree = 0u32;- while i < edges.len() && edges[i].source == source {- out.push(BakedItem::Edge(Box::new(bake_edge(- &edges[i],- lane_pool,- csr,- synth,- points,- node_coords,- &mut scratch,- &mut encoded,- )?)));- degree += 1;- edge_idx += 1;- i += 1;- }- // The opener comes FIRST in drain order (node record, then its- // edges): splice it before the run just baked. Runs are short- // (degree ones mostly), so the shift is cheap — and positional- // exactness is the whole contract.- out.insert(run_start, baked_node(source, node_coords, edge_idx - degree as u64, degree));- node += 1;- }- Ok(out)-}--/// One node opener: its record bytes with the absolute edge pointer, plus its-/// out-degree for the census replay.-fn baked_node(node: u32, node_coords: &[geom::Pt], edge_ptr: u64, degree: u32) -> BakedItem {- let coords = node_coords[node as usize];- let mut rec = [0u8; 12];- rec[0..4].copy_from_slice(&coords.0.to_le_bytes());- rec[4..8].copy_from_slice(&coords.1.to_le_bytes());- rec[8..12].copy_from_slice(&(edge_ptr as u32).to_le_bytes());- BakedItem::Node { rec, degree }-}--/// One edge, decided: record inputs, geometry outcome, census inputs, lanes.-///-/// Mirrors the serial loop's per-edge body exactly: escape narrowing (same-/// predicate, same sentinel rows), the twin-check-before-read (same flag),-/// polyline read + reverse + gates + encode, lane run copy. Census inputs-/// are the edge's own fields (replayed verbatim by the drain).-fn bake_edge(- e: &TmpEdge,- lane_pool: &[u16],- csr: &Csr,- synth: &[Synth],- points: &crate::mem::Mapped,- node_coords: &[geom::Pt],- scratch: &mut Vec<geom::Pt>,- encoded: &mut Vec<u8>,-) -> Result<BakedEdge> {- // Narrow first, exactly as `EdgeFile::push` does: the drain replays the- // narrowing verbatim through `push_baked_edge`, so the predicate lives in- // one place (there) and here only the escape ROW is decided... simpler:- // decide everything here and carry the outcome.- let (delta, dist, escaped) = match target_delta(e.source, e.target) {- Some(d) if e.dist_mm < DIST_MM_ESCAPE => (d, e.dist_mm, None),- _ => (- TARGET_DELTA_ESCAPE,- DIST_MM_ESCAPE,- Some((e.target, e.dist_mm)),- ),- };- // --- geometry ---- let mut type_ = e.type_;- let mut geom = BakedGeom::Absent;- // A two-point chain is just the chord between the edge's own endpoints,- // and under the interior-only encoding that is what an absent blob- // already means, so storing it would cost a presence bit to say nothing —- // and, more to the point here, a read to find that out.- if e.chain != NO_CHAIN && e.pts_len >= 3 {- if e.chain_rev && e.source != e.target && twin_is_unique(csr, synth, e.source, e.target)- {- type_ |= REVERSE_GEOMETRY_FLAG;- geom = BakedGeom::Reversed;- } else {- // Only now is the polyline actually needed. Deciding the flag- // first matters more than it looks: this is the only random read- // in the writer, so every edge that defers to its twin is one- // seek saved. Shared mapping, no lock: `read_shared` slices the- // same pages the serial loop faulted.- chains::PointReader::read_shared(points, e.pts_start, e.pts_len, scratch)?;- if e.chain_rev {- scratch.reverse();- }- assert!(- geom::fits(scratch),- "chain of {} points cannot be encoded; the collapse should \- have split it",- scratch.len()- );- // The blob holds only the interior, so the reader rebuilds- // both ends out of `nodes.bin`.- assert_endpoints(scratch, node_coords, e.source, e.target, e.chain);- encoded.clear();- let n = geom::encode(scratch, encoded);- debug_assert_eq!(n as usize, geom::encoded_points(scratch) as usize);- geom = BakedGeom::Blob(std::mem::take(encoded));- }- }- let lanes = if e.lane_count > 0 && e.lane_off != NO_LANES {- let start = e.lane_off as usize;- lane_pool[start..start + e.lane_count as usize].to_vec()- } else {- Vec::new()- };- Ok(BakedEdge {- cen_source: e.source,- cen_target: e.target,- cen_dist: e.dist_mm,- cen_named: e.name_offset != NO_NAME,- delta,- dist,- escaped,- type_,- speed_limit: e.speed_limit,- name_offset: e.name_offset,- geom,- lanes,- })-}--/// Stage one baked edge's record: the narrowing replayed verbatim.-///-/// `EdgeFile::push` narrows from the live edge; this narrows from the baked-/// decision. Same predicate, same rows, same bitmap updates — the function-/// exists so the two cannot drift: any change to narrowing updates both-/// call sites' shared outcome type... (they share `BakedEdge`'s fields, and-/// this function is the drain's only writer into `edges_out`).-fn push_baked_edge(edges_out: &mut EdgeFile, item: &BakedEdge) -> Result<()> {- let (delta, dist) = match item.escaped {- Some((target, dist)) => {- let idx = edges_out.pushed as u32;- edges_out.escapes.push((idx, target, dist));- (TARGET_DELTA_ESCAPE, DIST_MM_ESCAPE)- }- None => (item.delta, item.dist),- };- let mut rec = [0u8; EDGE_REC_BYTES as usize];- rec[0..2].copy_from_slice(&delta.to_le_bytes());- rec[2..5].copy_from_slice(&dist.to_le_bytes()[..3]);- rec[5] = item.type_;- rec[6] = item.speed_limit;- edges_out- .blocked- .push(&rec)- .map_err(|e| Error(format!("cannot stage edge record: {e}")))?;- if item.name_offset != NO_NAME {- edges_out.named.set(edges_out.pushed);- edges_out.name_offsets.push(item.name_offset);- }- edges_out.pushed += 1;- Ok(())-}-
scripts/maps/osm_ingest/src/graph_build_part4.rs
diff --git a/scripts/maps/osm_ingest/src/graph_build_part4.rs b/scripts/maps/osm_ingest/src/graph_build_part4.rsindex 4b7ec314af..127792f451 100644--- a/scripts/maps/osm_ingest/src/graph_build_part4.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part4.rs@@ -108,7 +108,9 @@ impl GeomFile { fn create(dir: &Path, name: &str, edge_count: u64) -> Result<GeomFile> { let path = dir.join(name); Ok(GeomFile {- out: BufWriter::new(create(&path)?),+ // Large appends: the drain hands over one batch's blobs at a time, and+ // on a compress-force filesystem every extent costs CPU.+ out: BufWriter::with_capacity(WRITE_BUF_BYTES, create(&path)?), path, blob_len: 0, present: PresenceBitmap::new(edge_count),@@ -311,7 +313,7 @@ struct EdgeFile { path: PathBuf, /// Blocked record staging: 7 B records stream here (one block in memory, /// frames to scratch), finished into the file head at [`EdgeFile::finish`].- blocked: tilecodec::blocked::BlockedStreamWriter,+ blocked: ParBlocked, /// `(edge_idx, target, dist_mm)` for the edges a record cannot hold, in /// ascending `edge_idx` — which is the order they are pushed in, because the /// rounds ascend and each round writes its edges in index order.@@ -340,7 +342,7 @@ impl EdgeFile { let path = dir.join(name); let scratch = dir.join(format!("{name}.blocked.tmp")); Ok(EdgeFile {- blocked: tilecodec::blocked::BlockedStreamWriter::create(EDGE_REC_BYTES as usize, &scratch)+ blocked: ParBlocked::create(EDGE_REC_BYTES as usize, &scratch) .map_err(|e| Error(format!("cannot stage {}: {e}", scratch.display())))?, path, escapes: Vec::new(),
scripts/maps/osm_ingest/src/progress.rs
diff --git a/scripts/maps/osm_ingest/src/progress.rs b/scripts/maps/osm_ingest/src/progress.rsindex 1cd8b80ae2..9bee45054e 100644--- a/scripts/maps/osm_ingest/src/progress.rs+++ b/scripts/maps/osm_ingest/src/progress.rs@@ -53,6 +53,17 @@ impl Progress { } } + /// Record `n` items done at once (a parallel stage's batch), redrawing at+ /// most once per [`REDRAW_STEP`].+ #[inline]+ pub(crate) fn add(&mut self, n: u64) {+ self.done += n;+ if self.done >= self.next {+ self.next = self.done + REDRAW_STEP;+ self.draw();+ }+ }+ fn draw(&self) { let pct = (self.done * 100).checked_div(self.total).unwrap_or(100); let elapsed = self.start.elapsed().as_secs_f64();