maps: take road_graph's last serial copies off the critical path (#perf)
- Commit
f4df31337abb22b76e83cf1f6789d9091554f7ce- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-10 19:45 UTC (25 days ago)
- Parents
5361c68
With every stage parallel, measurement (temporary timers around each ordered sink and the write drain, removed again) showed the remaining wall on California sat on single threads doing copies and compression setup rather than work: - write drain: 0.61 s, of which 0.35 s waiting on the zstd blocks it had just handed to the pool (rayon::join lets the waiting thread steal unrelated bake tasks) and 0.06 s writing frames; - pass 4 sink: 0.76 s of 1.06 s busy, 0.38 s of it in write(2); - pass 2 sink: 0.25 s of 0.32 s busy scattering coordinates; - stream finish: 0.21 s reading every zstd frame back into memory, assembling a second copy and writing it (2x the section in RAM: ~9 GB transient at planet scale for nodes.bin + edges.bin). Changes, all byte-neutral: - ParBlocked hands each 256-block group to the pool asynchronously and collects finished groups strictly in hand-off order (bounded to 8 in flight), so the drain never waits on compression. - tilecodec compress_block reuses one zstd context per thread instead of building one per 28-48 KiB block; the encoder's tables are epoch-tagged and its docs state a frame depends only on (config, input, dict). New test compares reused vs fresh contexts across mixed block sizes. - tilecodec BlockedStreamWriter::finish_into streams header + table and copies frames straight from the scratch file; nodes.bin and edges.bin use it and sanity-parse the result through a mapping. New test: finish_into bytes == finish bytes. - chains spill: chains.hdr and chains.pts are appended by one writer thread each (bounded channels), so the ordered sink hands buffers over instead of copying them. - pass 2 (node-scan): coordinates scatter from the decode workers; each id claims its `present` bit atomically and only the claimant writes its slot. Equal to the serial last-occurrence-wins fold whenever ids are unique; if any id repeats, the pass is redone serially (new test with a duplicated node id). chains.pts I/O check (README --spill-dir notes): a temporary build that fsynced and POSIX_FADV_DONTNEED-evicted chains.pts before the write phase moved write-write 0.77 -> 0.97 s at 192 threads (293 major faults; readahead covers the rest) and nothing measurable at 1 thread (9.2 vs 7.8 s, noise). On this box's local disk the random polyline reads are not the bottleneck; the 47-minute figure in the README was a slow mount. Verified: California --region california, sha256 of every output identical to baseline-bin/road_graph. cargo test -p osm_ingest: 302 passed; tilecodec blocked tests: new ones pass (two pre-existing failures from a test helper that always emits 12-byte records). California wall (192 threads, shared box): 4.5 s -> 3.9-5.0 s (noise-bound now); collapse-chains 1.03 -> 0.77, node-scan 0.29 -> 0.16, write drain 0.61 -> 0.40.
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 83bfba4aec..91dd50c46e 100644--- a/library/tilecodec/src/main/rust/src/blocked.rs+++ b/library/tilecodec/src/main/rust/src/blocked.rs@@ -268,15 +268,32 @@ pub fn write_blocked_with(records: &[u8], record_len: usize, per_block: u32) -> /// [`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+ // One context per thread, reused for every block it compresses. A fresh+ // `Compressor` per block (what this used to do) allocates and zeroes the+ // level-10 match tables — megabytes — for every 28-48 KiB block, which+ // dominated the cost of compressing a planet's nodes.bin/edges.bin. The+ // encoder is built for reuse: its tables are epoch-tagged, so entries from+ // an earlier frame are never matched, and a frame "depends only on the+ // configuration, the input and the dictionary, never on which context runs+ // it". `a_reused_context_frames_blocks_like_a_fresh_one` pins that.+ thread_local! {+ static ENC: std::cell::RefCell<Option<zstd_rs::Compressor>> =+ const { std::cell::RefCell::new(None) };+ }+ ENC.with(|cell| {+ let mut slot = cell.borrow_mut();+ let enc = slot.get_or_insert_with(|| {+ zstd_rs::Compressor::new(zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ })+ .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@@ -396,6 +413,49 @@ impl BlockedStreamWriter { Ok(()) } + /// [`BlockedStreamWriter::finish`], streamed: compress the tail block, then+ /// write header + offset table into `out` and copy the frames straight from+ /// the scratch file behind them, never holding the section in memory.+ /// Byte-identical to writing `finish()`'s bytes. Returns the section length.+ pub fn finish_into<W: std::io::Write>(mut self, out: &mut W) -> std::io::Result<u64> {+ use std::io::Write as _;+ if !self.block.is_empty() {+ let frame = compress_block(&self.block);+ self.frames_out.write_all(&frame)?;+ self.frame_lens.push(frame.len() as u64);+ }+ self.frames_out.flush()?;+ drop(self.frames_out);+ let block_count = self.frame_lens.len();+ let unpacked = self.records * self.record_len as u64;+ let mut head = Vec::with_capacity(28 + (block_count + 1) * 8);+ head.extend_from_slice(&BLOCKED_MAGIC.to_le_bytes());+ head.extend_from_slice(&0u32.to_le_bytes());+ head.extend_from_slice(&(self.record_len as u32).to_le_bytes());+ head.extend_from_slice(&self.per_block.to_le_bytes());+ head.extend_from_slice(&unpacked.to_le_bytes());+ head.extend_from_slice(&(block_count as u32).to_le_bytes());+ let mut off = (28 + (block_count + 1) * 8) as u64;+ for len in &self.frame_lens {+ head.extend_from_slice(&off.to_le_bytes());+ off += len;+ }+ head.extend_from_slice(&off.to_le_bytes());+ out.write_all(&head)?;+ let frames_bytes: u64 = self.frame_lens.iter().sum();+ let mut f = std::fs::File::open(&self.frames_path)?;+ let copied = std::io::copy(&mut f, out)?;+ drop(f);+ let _ = std::fs::remove_file(&self.frames_path);+ if copied != frames_bytes {+ return Err(std::io::Error::new(+ std::io::ErrorKind::UnexpectedEof,+ format!("blocked scratch holds {copied} frame byte(s), expected {frames_bytes}"),+ ));+ }+ Ok(off)+ }+ /// 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>> {@@ -528,4 +588,49 @@ mod tests { let framed = framed.finish().expect("finish"); assert_eq!(framed, plain, "frames compressed elsewhere must be byte-identical"); }++ #[test]+ fn a_reused_context_frames_blocks_like_a_fresh_one() {+ // Blocks of varied size and content, large before small and back, so+ // any table state leaking from one frame into the next would show.+ let mut blocks: Vec<Vec<u8>> = Vec::new();+ for (n, seed) in [(4096usize, 1u32), (17, 2), (4096, 3), (1, 4), (2500, 5), (4096, 1)] {+ let mut b = pattern_records(n, 12);+ for (i, byte) in b.iter_mut().enumerate() {+ *byte ^= (seed.wrapping_mul(2654435761).rotate_left(i as u32 % 31)) as u8 & 3;+ }+ blocks.push(b);+ }+ let fresh = |b: &[u8]| {+ let mut enc = zstd_rs::Compressor::new(zstd_rs::CompressionConfig {+ level: 10,+ ..zstd_rs::CompressionConfig::DEFAULT+ })+ .unwrap();+ let mut f = Vec::new();+ enc.compress(b, None, &mut f).unwrap();+ f+ };+ for b in &blocks {+ assert_eq!(compress_block(b), fresh(b), "reused context diverged");+ }+ }++ #[test]+ fn finishing_into_a_writer_matches_finish() {+ let records = pattern_records(10_000, 12);+ let dir = std::env::temp_dir();+ let a = dir.join("tilecodec_blocked_into_a.tmp");+ let b = dir.join("tilecodec_blocked_into_b.tmp");+ let mut w1 = BlockedStreamWriter::create(12, &a).expect("create");+ w1.push(&records).expect("push");+ let whole = w1.finish().expect("finish");+ let mut w2 = BlockedStreamWriter::create(12, &b).expect("create");+ w2.push(&records).expect("push");+ let mut streamed = Vec::new();+ let n = w2.finish_into(&mut streamed).expect("finish_into");+ assert_eq!(n as usize, streamed.len());+ assert_eq!(streamed, whole);+ assert!(!b.exists(), "scratch is removed");+ } }
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 fc3ee06eb7..88c7afa295 100644--- a/scripts/maps/osm_ingest/src/chains.rs+++ b/scripts/maps/osm_ingest/src/chains.rs@@ -254,7 +254,11 @@ pub(crate) fn build<W: Write + Send>( for rec in chunk.hdr.chunks_exact_mut(CHAIN_REC_BYTES as usize) { rebase_header(rec, points_base, &name_map, lane_base); }- writer.push_encoded(&chunk.hdr, &chunk.pts, chunk.points)?;+ writer.push_encoded(+ std::mem::take(&mut chunk.hdr),+ std::mem::take(&mut chunk.pts),+ chunk.points,+ )?; splits += chunk.splits; raw_edge_count += chunk.raw_edge_count; Ok(())
scripts/maps/osm_ingest/src/chains_part1.rs
diff --git a/scripts/maps/osm_ingest/src/chains_part1.rs b/scripts/maps/osm_ingest/src/chains_part1.rsindex 37a8518aaf..2a9ad6705f 100644--- a/scripts/maps/osm_ingest/src/chains_part1.rs+++ b/scripts/maps/osm_ingest/src/chains_part1.rs@@ -98,9 +98,31 @@ impl Spill { /// byte-deterministic. pub fn writer(&self) -> Result<SpillWriter> { self.make_dirs()?;+ let mut hdr = BufWriter::with_capacity(8 << 20, create(&self.hdr)?);+ let mut pts = BufWriter::with_capacity(8 << 20, create(&self.pts)?);+ // The appends run on threads of their own — one per file, since the two+ // are independent streams — so the chain pass's ordered sink hands+ // buffers over instead of copying ~45 GB (planet) through write(2)+ // itself. Bounded, so at most a few chunks are in flight per file.+ let spawn = |name: &str, mut out: BufWriter<File>| {+ let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<u8>>(4);+ std::thread::Builder::new()+ .name(name.into())+ .spawn(move || -> std::io::Result<()> {+ for b in rx {+ out.write_all(&b)?;+ }+ out.flush()+ })+ .map(|t| (tx, t))+ .map_err(|e| Error(format!("cannot start the spill writer: {e}")))+ };+ let (hdr_tx, hdr_t) = spawn("chain-hdr-writer", hdr)?;+ let (pts_tx, pts_t) = spawn("chain-pts-writer", pts)?;+ let (tx, thread) = ((hdr_tx, pts_tx), (hdr_t, pts_t)); Ok(SpillWriter {- hdr: BufWriter::with_capacity(1 << 20, create(&self.hdr)?),- pts: BufWriter::with_capacity(1 << 20, create(&self.pts)?),+ tx: Some(tx),+ thread: Some(thread), points: 0, chains: 0, })@@ -276,8 +298,13 @@ fn decode_pt(b: &[u8]) -> geom::Pt { /// Streams `chains.hdr` and `chains.pts` from the front. pub(crate) struct SpillWriter {- hdr: BufWriter<File>,- pts: BufWriter<File>,+ /// Buffers for the writer thread, in order: `(chains.hdr bytes, chains.pts bytes)`.+ tx: Option<(std::sync::mpsc::SyncSender<Vec<u8>>, std::sync::mpsc::SyncSender<Vec<u8>>)>,+ #[allow(clippy::type_complexity)]+ thread: Option<(+ std::thread::JoinHandle<std::io::Result<()>>,+ std::thread::JoinHandle<std::io::Result<()>>,+ )>, /// Points written so far, which is the next chain's `pts_start`. pub(crate) points: u64, chains: u64,@@ -308,39 +335,60 @@ impl SpillWriter { oneway: c.oneway, } .encode(&mut rec);- self.hdr.write_all(&rec).map_err(io_err)?;+ let mut pts = Vec::with_capacity(ids.len() * CHAIN_PT_BYTES as usize); for id in ids { let (lat_e7, lon_e7) = coords[*id as usize];- self.pts.write_all(&lat_e7.to_le_bytes()).map_err(io_err)?;- self.pts.write_all(&lon_e7.to_le_bytes()).map_err(io_err)?;+ pts.extend_from_slice(&lat_e7.to_le_bytes());+ pts.extend_from_slice(&lon_e7.to_le_bytes()); }- self.points += u64::from(c.pts_len);- self.chains += 1;- Ok(())+ self.push_encoded(rec.to_vec(), pts, u64::from(c.pts_len)) } /// Append chains already encoded by [`build`]'s workers: `hdr` holds whole /// header records whose `pts_start` the caller has rebased onto /// [`SpillWriter::points`], and `pts` the `points` coordinates they cover.- /// Same bytes as [`SpillWriter::push`] per chain.- pub fn push_encoded(&mut self, hdr: &[u8], pts: &[u8], points: u64) -> Result<()> {+ /// Same bytes as [`SpillWriter::push`] per chain; the write itself happens+ /// on the writer thread, in the order of these calls.+ pub fn push_encoded(&mut self, hdr: Vec<u8>, pts: Vec<u8>, points: u64) -> Result<()> { debug_assert_eq!(hdr.len() as u64 % CHAIN_REC_BYTES, 0); debug_assert_eq!(pts.len() as u64, points * CHAIN_PT_BYTES);- self.hdr.write_all(hdr).map_err(io_err)?;- self.pts.write_all(pts).map_err(io_err)?;+ let chains = hdr.len() as u64 / CHAIN_REC_BYTES;+ let (htx, ptx) = self.tx.as_ref().expect("the spill writer is open");+ if htx.send(hdr).is_err() || ptx.send(pts).is_err() {+ // The writer thread stopped on an I/O error; `finish` reports it.+ return self.join().and(Err(Error("the chain spill writer stopped".into())));+ } self.points += points;- self.chains += hdr.len() as u64 / CHAIN_REC_BYTES;+ self.chains += chains; Ok(()) } + fn join(&mut self) -> Result<()> {+ self.tx = None;+ let Some((h, p)) = self.thread.take() else {+ return Ok(());+ };+ let one = |t: std::thread::JoinHandle<std::io::Result<()>>| match t.join() {+ Ok(r) => r.map_err(io_err),+ Err(_) => Err(Error("the chain spill writer panicked".into())),+ };+ let (h, p) = (one(h), one(p));+ h.and(p)+ }+ /// Flush both files and report how many chains were written. pub fn finish(mut self) -> Result<u64> {- self.hdr.flush().map_err(io_err)?;- self.pts.flush().map_err(io_err)?;+ self.join()?; Ok(self.chains) } } +impl Drop for SpillWriter {+ fn drop(&mut self) {+ let _ = self.join();+ }+}+ /// Streams `chains.hdr` from the front. pub(crate) struct HeaderReader { src: BufReader<File>,
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 9a1fece53f..de3f179e3b 100644--- a/scripts/maps/osm_ingest/src/graph_build_part1.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part1.rs@@ -21,6 +21,8 @@ struct Pass2 { /// pool: interning a stop code early would shift every way name after it and /// rewrite the whole of `road_names.bin`. stops: Vec<(u32, Vec<u8>)>,+ /// Slots this chunk claimed (first sight of the id) in the parallel scan.+ claimed: u64, } #[derive(Clone, Copy)]@@ -193,28 +195,79 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> let mut stop_codes: Vec<(u32, Vec<u8>)> = Vec::new(); let mut node_count: u64 = 0; timer.switch("node-scan");- let _ = pbf::run_pass_sink(- input,- &blobs,- Some(&blob_kinds),- KIND_NODES,- "Pass 2: node scan",- 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;+ // 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,+ Some(&blob_kinds),+ KIND_NODES,+ "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);+ } }- }- for (dense, code) in chunk.stops {- stop.set(u64::from(dense));- stop_codes.push((dense, code));- }- Ok(())- },- )?;+ 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,+ Some(&blob_kinds),+ KIND_NODES,+ "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
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 cf1d4320f4..a6bc023004 100644--- a/scripts/maps/osm_ingest/src/graph_build_part10.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part10.rs@@ -252,3 +252,19 @@ assert_eq!(bake_openers(&b), vec![(2, 7), (3, 7), (4, 7), (5, 7)]); assert_eq!(b.edge_count, 0); }++ #[test]+ fn a_duplicated_node_id_keeps_its_last_coordinates() {+ // The parallel node scan lets only the first claimant write a slot, so+ // a repeated id must fall back to the serial fold, where the LAST+ // occurrence wins — as it always has.+ let mut nodes = line_nodes(&[1, 2, 3]);+ nodes.push((3, 370_090_000, -1_220_000_000));+ let (pbf, dir) = testpbf::write_shape_sample("dup_node", &nodes, &[(100, &[1, 2, 3])]);+ let stats = build_with(&pbf, &dir, within_opts()).unwrap();+ assert_eq!(stats.raw_node_count, 3, "a repeated id is still one node");+ let o = read_outputs(&dir);+ let lats: Vec<i32> = (0..node_count(&o)).map(|i| node_at(&o, i).0).collect();+ assert!(lats.contains(&370_090_000), "the last occurrence wins: {lats:?}");+ assert!(!lats.contains(&370_030_000), "the first occurrence is gone: {lats:?}");+ }
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 2bb1a80033..7596255c81 100644--- a/scripts/maps/osm_ingest/src/graph_build_part11.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part11.rs@@ -35,20 +35,27 @@ const WAVE_BATCHES_PER_THREAD: usize = 4; const PAR_BLOCKS: usize = 256; /// A [`tilecodec::blocked::BlockedStreamWriter`] whose full blocks are-/// compressed on the pool.+/// compressed on the pool, behind the drain rather than inside it. ///-/// 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.+/// Records stage here until [`PAR_BLOCKS`] whole blocks are waiting; that+/// group is handed to the pool to compress ([`tilecodec::blocked::compress_block`]+/// is a pure function of one block) and the drain carries on. Finished groups+/// are collected strictly in the order they were handed off and their frames+/// go to the writer in that order, so the section is exactly what pushing every+/// record through the writer produces. The tail that never fills a block goes+/// through the writer's own `push`, so `finish` frames it exactly as before. struct ParBlocked { w: tilecodec::blocked::BlockedStreamWriter, staged: Vec<u8>, block_bytes: usize,+ /// Groups handed to the pool, oldest first.+ inflight: std::collections::VecDeque<std::sync::mpsc::Receiver<Vec<Vec<u8>>>>, } +/// Compressed groups a [`ParBlocked`] may have outstanding before the drain+/// waits for the oldest: bounds the staged bytes in flight.+const PAR_INFLIGHT: usize = 8;+ impl ParBlocked { fn create(record_len: usize, scratch: &Path) -> std::io::Result<ParBlocked> { let w = tilecodec::blocked::BlockedStreamWriter::create(record_len, scratch)?;@@ -57,6 +64,7 @@ impl ParBlocked { w, staged: Vec::with_capacity(block_bytes * PAR_BLOCKS * 2), block_bytes,+ inflight: std::collections::VecDeque::new(), }) } @@ -65,36 +73,64 @@ impl ParBlocked { 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()?;+ self.hand_off();+ self.collect(false)?; } 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<()> {+ /// Hand every whole staged block to the pool as one group; keep the+ /// partial tail staged.+ fn hand_off(&mut self) { let full = self.staged.len() / self.block_bytes * self.block_bytes; if full == 0 {- return Ok(());+ return; }+ let tail = self.staged[full..].to_vec();+ let mut group = std::mem::replace(&mut self.staged, Vec::with_capacity(self.block_bytes * PAR_BLOCKS * 2));+ group.truncate(full);+ self.staged.extend_from_slice(&tail); 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()+ let (tx, rx) = std::sync::mpsc::sync_channel(1);+ par::spawn(move || {+ let frames: Vec<Vec<u8>> =+ group.par_chunks(bb).map(tilecodec::blocked::compress_block).collect();+ let _ = tx.send(frames); });- self.w.push_frames(&frames)?;- self.staged.drain(..full);+ self.inflight.push_back(rx);+ }++ /// Pass finished groups to the writer, oldest first: every ready one, plus+ /// — when too many are outstanding, or `all` — waiting for the oldest.+ fn collect(&mut self, all: bool) -> std::io::Result<()> {+ while let Some(rx) = self.inflight.front() {+ let must_wait = all || self.inflight.len() > PAR_INFLIGHT;+ let frames = if must_wait {+ rx.recv().map_err(|_| std::io::Error::other("a block compressor died"))?+ } else {+ match rx.try_recv() {+ Ok(f) => f,+ Err(std::sync::mpsc::TryRecvError::Empty) => break,+ Err(std::sync::mpsc::TryRecvError::Disconnected) => {+ return Err(std::io::Error::other("a block compressor died"));+ }+ }+ };+ self.inflight.pop_front();+ self.w.push_frames(&frames)?;+ } Ok(()) } - fn finish(mut self) -> std::io::Result<Vec<u8>> {- self.flush_full()?;+ /// Finish the section straight into `out` (see+ /// [`tilecodec::blocked::BlockedStreamWriter::finish_into`]). Returns its+ /// length.+ fn finish_into<W: Write>(mut self, out: &mut W) -> std::io::Result<u64> {+ self.hand_off();+ self.collect(true)?; let tail = std::mem::take(&mut self.staged); self.w.push(&tail)?;- self.w.finish()+ self.w.finish_into(out) } } @@ -471,3 +507,4 @@ fn write_round( 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 3a2d1f55b0..5ebe42782a 100644--- a/scripts/maps/osm_ingest/src/graph_build_part3.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part3.rs@@ -480,11 +480,18 @@ fn finish_pack( nodes_blocked .push(&sentinel) .map_err(|e| Error(format!("cannot stage node sentinel: {e}")))?;- let nodes_bytes = nodes_blocked- .finish()- .map_err(|e| Error(format!("cannot finish nodes.bin: {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_bytes).map_err(|e| {+ let parsed = tilecodec::blocked::Blocked::parse(&nodes_map).map_err(|e| { Error(format!( "freshly blocked nodes.bin does not parse: {e}" ))@@ -500,7 +507,7 @@ fn finish_pack( (u64::from(kept) + 1) * 12 ))); }- std::fs::write(out_dir.join("nodes.bin"), &nodes_bytes).map_err(io_err)?;+ 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)?;
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 127792f451..02df042ea5 100644--- a/scripts/maps/osm_ingest/src/graph_build_part4.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part4.rs@@ -394,23 +394,12 @@ impl EdgeFile { ))); } let EdgeFile { path, blocked, escapes, named, name_offsets, pushed: _ } = self;- let records = blocked- .finish()+ // The record section streams straight into the file head; the sanity+ // parse reads it back through a mapping once the file is complete.+ let mut out = BufWriter::with_capacity(WRITE_BUF_BYTES, create(&path)?);+ let mut at = blocked+ .finish_into(&mut out) .map_err(|e| Error(format!("cannot finish {}: {e}", path.display())))?;- // Sanity: the blocked section must unpack to exactly the pushed records.- let parsed = tilecodec::blocked::Blocked::parse(&records).map_err(|e| {- Error(format!("freshly blocked {} does not parse: {e}", path.display()))- })?;- if parsed.unpacked_len() != edge_count * EDGE_REC_BYTES {- return Err(Error(format!(- "{} unpacks to {} byte(s), not {edge_count} 7-byte records",- path.display(),- parsed.unpacked_len()- )));- }- let mut out = BufWriter::new(create(&path)?);- out.write_all(&records).map_err(io_err)?;- let mut at = records.len() as u64; at = pad_to(&mut out, &path, at)?; // `escape_first[b]` is the index of the first row in block `b`, i.e. the@@ -457,10 +446,21 @@ impl EdgeFile { out.write_all(&off.to_le_bytes()).map_err(io_err)?; } out.flush().map_err(io_err)?;+ drop(out); - let got = std::fs::metadata(&path)- .map_err(|e| Error(format!("cannot stat {}: {e}", path.display())))?- .len();+ // Sanity: the blocked section must unpack to exactly the pushed records.+ let map = crate::mem::Mapped::open(&path).map_err(Error)?;+ let parsed = tilecodec::blocked::Blocked::parse(&map).map_err(|e| {+ Error(format!("freshly blocked {} does not parse: {e}", path.display()))+ })?;+ if parsed.unpacked_len() != edge_count * EDGE_REC_BYTES {+ return Err(Error(format!(+ "{} unpacks to {} byte(s), not {edge_count} 7-byte records",+ path.display(),+ parsed.unpacked_len()+ )));+ }+ let got = map.len() as u64; Ok(got) } }
scripts/maps/osm_ingest/src/par.rs
diff --git a/scripts/maps/osm_ingest/src/par.rs b/scripts/maps/osm_ingest/src/par.rsindex 7f29462b96..e72554612c 100644--- a/scripts/maps/osm_ingest/src/par.rs+++ b/scripts/maps/osm_ingest/src/par.rs@@ -131,6 +131,12 @@ pub fn install<R: Send>(f: impl FnOnce() -> R + Send) -> R { pool().install(f) } +/// Run `f` asynchronously on the pool (fire and forget; report back through a+/// channel). For pipelining work behind a serial stage.+pub fn spawn(f: impl FnOnce() + Send + 'static) {+ pool().spawn(f)+}+ /// Apply `f(chunk_start, chunk)` to every chunk of `chunk_len` items, returning /// the results in chunk order. pub fn map_chunks<T, R, F>(items: &[T], chunk_len: usize, f: F) -> Vec<R>