maps: parallelize road_graph's serial pre-write stages (#perf)
- Commit
5361c68d7d99891a757cbb5bbeb649b523ce584e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-10 19:29 UTC (25 days ago)
- Parents
2987ad6
After the write pipeline landed, California spent most of its wall in stages that ran on one core or fought themselves at 192 threads. Each change below is byte-neutral by construction; all seven outputs hash identical to baseline-bin/road_graph. Root cause of the ~400 s of system time per California run (vs ~110 s user): eu-stack during pass 1 showed ~60 decode threads in realloc blocked in __lll_lock_wait_private and ~125 parked on the reorder window. visit_block built a fresh Scratch per blob, so every block regrew ~10 decode vectors from empty; with 192 threads that churn serialised on allocator locks (kernel futex hash-bucket spinlocks in perf). Meanwhile the PBF passes' sinks were single-threaded scatters that capped each pass at one core, and run_pass_sink ran the sink under the one mutex every worker takes and notify_all-ed every parked worker on each deposit. - osm.rs: the decode Scratch is thread-local and reused across blocks (every visitor already clears what it uses). - pbf.rs run_pass_sink: the sink runs on the calling thread outside the lock, strictly in chunk order as before; a deposit is a slot store + unpark; a window waiter is woken only when its own chunk enters the window. Worker failure / unwinding still cannot strand the drain. - Pass 1 (refs-stops): refs and stops are marked from the workers into the mask through an atomic view (Bitset::atomic / AtomicBits). Set union is order-free, and set() reports each bit's clear->set transition exactly once, so the marked count and max id are exact. No per-chunk ref vectors at all. - Pass 3 (collapse-degrees): saturating u8 increments straight into a shared degree array (min(255, n) commutes). The region build's extra "region locations" node scan is gone: it rebuilt the coordinates pass 2 already holds for exactly the same nodes. - Pass 4 (collapse-chains): workers encode chains.hdr records and resolve chains.pts coordinates, and mark endpoints atomically; the ordered sink only interns names and rebases pts_start/name/lane fields in place before appending two buffers. Kept-node selection is one byte (8 nodes) per item on the pool. - rank-index: per-block popcounts on the pool + serial prefix sum. - morton-sort: keys built in place on the pool (kept rank gives each slot range its output slice); final ids are a permutation scatter; node_coords an ordered map; stops_final per byte. - edge-index(-scatter): both chains.hdr scans run on the pool over the mapping; counts are atomic adds, scatter slots come from an atomic cursor, and the existing per-group sort makes targets identical. Verified: California --region california, sha256 of all outputs equal to baseline at --rounds 1/3 and --threads 1 (rounds 3), 8 and 192. cargo test -p osm_ingest: 301 passed. California wall (192 threads, Phase 4 running): 16.1 s -> 4.5 s. refs-stops 3.3 -> 0.5, rank-index 1.9 -> 0.06, node-scan 0.6 -> 0.3, collapse-degrees 1.8 -> 0.3, morton-sort 1.1 -> 0.2, edge-index + scatter 2.5 -> <0.1 s. System time 390 s -> ~80 s.
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 3e3ad48ca7..fc3ee06eb7 100644--- a/scripts/maps/osm_ingest/src/chains.rs+++ b/scripts/maps/osm_ingest/src/chains.rs@@ -47,10 +47,10 @@ use std::path::{Path, PathBuf}; use crate::compact::Chain; use crate::geom;-use crate::graph_build::{way_attrs, Bitset, NodeIndex, WayAttrs, BITSET_SIZE};+use crate::graph_build::{way_attrs, AtomicBits, Bitset, NodeIndex, WayAttrs}; use crate::names::{LocalNames, NamePool, NO_NAME}; use crate::osm::{visit_block, Element};-use crate::pbf::{self, BlobLoc, KIND_NODES, KIND_WAYS};+use crate::pbf::{self, BlobLoc, KIND_WAYS}; use crate::proto::{Error, Result}; use crate::spatial::accurate_dist_mm; use crate::tags;@@ -74,12 +74,20 @@ pub(crate) fn segment(index: &NodeIndex, a: i64, b: i64) -> Option<(u32, u32)> { /// Nodes with more incidences than a byte can hold are junctions whatever the /// true count is, so the counter saturates. Only `== 2` changes a decision, and /// no node with 255 incidences is a pass-through.+///+/// Counted straight into the shared array from the decode workers: a+/// saturating increment commutes (the result is `min(255, incidences)` in any+/// order), so nothing reaches the sink and nothing about the order of chunks+/// can show. The sink used to scatter every endpoint single-threaded, which+/// bounded the whole pass to one core. #[derive(Default)]-struct DegreePass {- /// Both endpoints of every segment, in decode order. Per chunk, so the- /// random scatter into the global array happens once, single-threaded, in the- /// sink.- endpoints: Vec<u32>,+struct DegreePass;++/// Saturating `+1` on a shared degree byte.+#[inline]+fn bump(d: &std::sync::atomic::AtomicU8) {+ use std::sync::atomic::Ordering::Relaxed;+ let _ = d.fetch_update(Relaxed, Relaxed, |v| v.checked_add(1)); } /// One saturating incidence count per dense node id.@@ -88,18 +96,39 @@ struct DegreePass { /// which touches the region contributes no incidence, so its nodes stay degree /// 0 and never survive. Both this and [`build`] must ask the same question — /// see [`segment`] — or a chain dead-ends where the degrees say pass-through.+///+/// The region test reads pass 2's `coords`, exactly as [`build`]'s does. It used+/// to resolve the marked nodes' locations again in a side table with an extra+/// node scan; that table held the same coordinates for the same nodes+/// (`coords[d]` is set for exactly the nodes `index.dense` accepts), so the+/// test is unchanged and the scan is gone. pub(crate) fn count_degrees( input: &Path, blobs: &[BlobLoc], blob_kinds: &[u8], index: &NodeIndex,+ coords: &[geom::Pt], slots: u32, filter: crate::graph_build::RegionFilter, ) -> Result<Vec<u8>> { let mut degree = vec![0u8; slots as usize];- if filter.is_none() {- // World build: the fast path, unchanged. Every routable way's segments- // count, and no coordinate table is needed.+ {+ let bytes: &mut [u8] = &mut degree;+ // SAFETY: `AtomicU8` has the layout of `u8`, and the exclusive borrow of+ // `degree` is held for as long as this view lives.+ let shared: &[std::sync::atomic::AtomicU8] =+ unsafe { &*(bytes as *mut [u8] as *const [std::sync::atomic::AtomicU8]) };+ let touches = |refs: &[i64]| -> bool {+ let Some(b) = filter.as_ref() else {+ return true;+ };+ refs.iter().any(|r| {+ index.dense(*r).is_some_and(|d| {+ let (lat, lon) = coords[d as usize];+ b.contains_e7(lat, lon)+ })+ })+ }; let _ = pbf::run_pass_sink( input, blobs,@@ -107,15 +136,15 @@ pub(crate) fn count_degrees( KIND_WAYS, "Pass 3: node degrees", DegreePass::default,- |state: &mut DegreePass, block| {+ |_state: &mut DegreePass, block| { let mut kinds = 0u8; visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| { if let Element::Way(w) = el {- if tags::get_hw_id(w.tags.get_str("highway")) != 0 {+ if tags::get_hw_id(w.tags.get_str("highway")) != 0 && touches(w.refs) { for pair in w.refs.windows(2) { if let Some((u, v)) = segment(index, pair[0], pair[1]) {- state.endpoints.push(u);- state.endpoints.push(v);+ bump(&shared[u as usize]);+ bump(&shared[v as usize]); } } }@@ -124,92 +153,9 @@ pub(crate) fn count_degrees( })?; Ok(kinds) },- |chunk| {- for e in chunk.endpoints {- let d = &mut degree[e as usize];- *d = d.saturating_add(1);- }- Ok(())- },- )?;- return Ok(degree);- }- // Region build: degrees must agree with the chain walk's filter, or a- // chain dead-ends where the degrees say pass-through. The filter needs- // coordinates, which live in pass 2's `coords` — not visible here — so- // this resolves the marked nodes' locations in a side table first. One- // extra node-region scan; dwarfed by what the region saves downstream.- let bbox = filter.expect("checked above");- let mut locs: Vec<Option<(i32, i32)>> = vec![None; slots as usize];- {- // (dense id, lat_e7, lon_e7), folded in chunk order.- let _ = pbf::run_pass_sink(- input,- blobs,- Some(blob_kinds),- KIND_NODES,- "Pass 3: region locations",- Vec::<(u32, i32, i32)>::new,- |state: &mut Vec<(u32, i32, i32)>, block| {- 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 && index.mask.get(n.id as u64) {- let d = index.mask.dense(n.id as u64);- state.push((d, n.lat_e7, n.lon_e7));- }- }- Ok(())- })?;- Ok(kinds)- },- |chunk| {- for (d, lat, lon) in chunk {- locs[d as usize] = Some((lat, lon));- }- Ok(())- },+ |_chunk| Ok(()), )?; }- let touches = |refs: &[i64]| -> bool {- refs.iter().any(|r| {- index.dense(*r).and_then(|d| locs[d as usize]).is_some_and(|(lat, lon)| {- bbox.contains_e7(lat, lon)- })- })- };- let _ = pbf::run_pass_sink(- input,- blobs,- Some(blob_kinds),- KIND_WAYS,- "Pass 3: node degrees",- DegreePass::default,- |state: &mut DegreePass, block| {- let mut kinds = 0u8;- visit_block(block, KIND_WAYS, &mut kinds, &mut |el: Element| {- if let Element::Way(w) = el {- if tags::get_hw_id(w.tags.get_str("highway")) != 0 && touches(w.refs) {- for pair in w.refs.windows(2) {- if let Some((u, v)) = segment(index, pair[0], pair[1]) {- state.endpoints.push(u);- state.endpoints.push(v);- }- }- }- }- Ok(())- })?;- Ok(kinds)- },- |chunk| {- for e in chunk.endpoints {- let d = &mut degree[e as usize];- *d = d.saturating_add(1);- }- Ok(())- },- )?; Ok(degree) } @@ -233,11 +179,18 @@ pub(crate) struct Chains { #[derive(Default)] struct ChainPass {- chains: Vec<Chain>,- pts: Vec<u32>,+ /// `chains.hdr` records, pre-encoded on the worker with CHUNK-LOCAL+ /// `pts_start`, name id and lane offsets; the sink rebases those three+ /// fields in place ([`rebase_header`]) and appends the bytes.+ hdr: Vec<u8>,+ /// `chains.pts` bytes for this chunk's chains, coordinates already+ /// resolved — the random `coords` reads now happen on the pool instead of+ /// in the single-threaded sink.+ pts: Vec<u8>,+ /// Points in `pts`, i.e. the next chain's chunk-local `pts_start`.+ points: u64, lanes: Vec<u16>, names: LocalNames,- endpoints: Vec<u32>, splits: usize, raw_edge_count: u64, }@@ -251,6 +204,13 @@ struct ChainPass { /// Nothing chain-shaped is retained. Only one chunk's worth exists at a time, /// which is what keeps this pass's footprint proportional to a chunk rather than /// to the road network.+///+/// The workers do everything that does not depend on earlier chunks: encode+/// each header record, resolve every point to coordinates, and mark chain+/// endpoints (a set union, straight into a shared bitset). The ordered sink+/// does only what does: intern the chunk's names, rebase the lane pool and the+/// point offsets, and append two byte buffers. Same bytes as encoding each+/// chain in the sink. #[allow(clippy::too_many_arguments)] pub(crate) fn build<W: Write + Send>( input: &Path,@@ -265,61 +225,79 @@ pub(crate) fn build<W: Write + Send>( pool: &mut NamePool<W>, spill: &Spill, ) -> Result<Chains> {- let mut out = Chains {- chain_count: 0,- lanes: Vec::new(),- endpoints: Bitset::new(u64::from(slots)),- splits: 0,- raw_edge_count: 0,- kinds: Vec::new(),- };+ let mut endpoints = Bitset::new(u64::from(slots));+ let mut lanes: Vec<u16> = Vec::new();+ let mut splits = 0usize;+ let mut raw_edge_count = 0u64; let mut writer = spill.writer()?;- out.kinds = pbf::run_pass_sink(- input,- blobs,- Some(blob_kinds),- KIND_WAYS,- "Pass 4: chains",- ChainPass::default,- |state: &mut ChainPass, block| chain_blob(state, block, index, coords, degree, stop, filter),- |chunk| {- let name_map = chunk- .names- .flush(pool)- .map_err(|e| Error(e.to_string()))?;- let lane_base = out.lanes.len() as u32;- out.lanes.extend_from_slice(&chunk.lanes);- crate::graph_build::cap_lane_pool(out.lanes.len())?;- for mut c in chunk.chains {- let lo = c.pts_start as usize;- let ids = &chunk.pts[lo..lo + c.pts_len as usize];- c.name_offset = if c.name_offset == u32::MAX {- NO_NAME- } else {- name_map[c.name_offset as usize]- };- if c.fwd_lane_count > 0 {- c.fwd_lane_off += lane_base;- }- if c.bwd_lane_count > 0 {- c.bwd_lane_off += lane_base;+ let kinds = {+ let ends = endpoints.atomic();+ pbf::run_pass_sink(+ input,+ blobs,+ Some(blob_kinds),+ KIND_WAYS,+ "Pass 4: chains",+ ChainPass::default,+ |state: &mut ChainPass, block| {+ chain_blob(state, block, index, coords, degree, stop, filter, &ends)+ },+ |mut chunk| {+ let name_map = chunk+ .names+ .flush(pool)+ .map_err(|e| Error(e.to_string()))?;+ let lane_base = lanes.len() as u32;+ lanes.extend_from_slice(&chunk.lanes);+ crate::graph_build::cap_lane_pool(lanes.len())?;+ let points_base = writer.points;+ for rec in chunk.hdr.chunks_exact_mut(CHAIN_REC_BYTES as usize) {+ rebase_header(rec, points_base, &name_map, lane_base); }- // `pts_start` is assigned by the writer, so the chunk-local value- // is only used to find the ids above.- writer.push(&c, ids, coords)?;- }- for e in chunk.endpoints {- out.endpoints.set(u64::from(e));- }- out.splits += chunk.splits;- out.raw_edge_count += chunk.raw_edge_count;- Ok(())- },- )?;- out.chain_count = writer.finish()?;- Ok(out)+ writer.push_encoded(&chunk.hdr, &chunk.pts, chunk.points)?;+ splits += chunk.splits;+ raw_edge_count += chunk.raw_edge_count;+ Ok(())+ },+ )?+ };+ let chain_count = writer.finish()?;+ Ok(Chains {+ chain_count,+ lanes,+ endpoints,+ splits,+ raw_edge_count,+ kinds,+ }) } +/// Turn a worker-encoded header's chunk-local fields into global ones: exactly+/// what the sink used to do to the `Chain` before encoding it.+#[inline]+fn rebase_header(rec: &mut [u8], points_base: u64, name_map: &[u32], lane_base: u32) {+ let u32_at = |r: &[u8], o: usize| u32::from_le_bytes(r[o..o + 4].try_into().expect("4 bytes"));+ let u16_at = |r: &[u8], o: usize| u16::from_le_bytes(r[o..o + 2].try_into().expect("2 bytes"));+ let start = u64::from_le_bytes(rec[0..8].try_into().expect("8 bytes")) + points_base;+ rec[0..8].copy_from_slice(&start.to_le_bytes());+ let name = u32_at(rec, 24);+ let name = if name == u32::MAX {+ NO_NAME+ } else {+ name_map[name as usize]+ };+ rec[24..28].copy_from_slice(&name.to_le_bytes());+ if u16_at(rec, 36) > 0 {+ let off = u32_at(rec, 28) + lane_base;+ rec[28..32].copy_from_slice(&off.to_le_bytes());+ }+ if u16_at(rec, 38) > 0 {+ let off = u32_at(rec, 32) + lane_base;+ rec[32..36].copy_from_slice(&off.to_le_bytes());+ }+}++#[allow(clippy::too_many_arguments)] fn chain_blob( state: &mut ChainPass, block: &pbf::PrimitiveBlock,@@ -328,6 +306,7 @@ fn chain_blob( degree: &[u8], stop: &Bitset, filter: crate::graph_build::RegionFilter,+ ends: &AtomicBits, ) -> Result<u8> { let mut kinds = 0u8; let mut path: Vec<u32> = Vec::new();@@ -371,7 +350,7 @@ fn chain_blob( if path.last() != Some(&u) { // The start of the way, the far side of a gap the graph does not // bridge, or the node the previous cut ended on.- flush(state, &path, &hops, &attrs, coords);+ flush(state, &path, &hops, &attrs, coords, ends); path.clear(); hops.clear(); path.push(u);@@ -383,14 +362,14 @@ fn chain_blob( // stop the reconnect pass addresses directly. Cut there; the next pair // restarts from it by the rule above. if degree[v as usize] != 2 || stop.get(u64::from(v)) {- flush(state, &path, &hops, &attrs, coords);+ flush(state, &path, &hops, &attrs, coords, ends); path.clear(); hops.clear(); } } // The way's last node is a chain boundary whatever its degree: a chain may // not continue into the next way.- flush(state, &path, &hops, &attrs, coords);+ flush(state, &path, &hops, &attrs, coords, ends); Ok(()) })?; Ok(kinds)@@ -403,6 +382,7 @@ fn flush( hops: &[u32], attrs: &WayAttrs, coords: &[geom::Pt],+ ends: &AtomicBits, ) { if path.len() < 2 { return;@@ -413,29 +393,42 @@ fn flush( state.splits += runs.len() - 1; } for (lo, hi) in runs {- state.endpoints.push(path[lo]);- state.endpoints.push(path[hi]);- let pts_start = state.pts.len() as u64;- state.pts.extend_from_slice(&path[lo..=hi]);+ ends.set(u64::from(path[lo]));+ ends.set(u64::from(path[hi]));+ let ids = &path[lo..=hi]; // Directed edges an uncompacted build would have emitted for this run: // one per segment per permitted direction. Runs tile every segment of the // way exactly once, so summing them is exact without keeping the segments. state.raw_edge_count += (hi - lo) as u64 * if attrs.oneway { 1 } else { 2 };- state.chains.push(Chain {- pts_start,+ let mut rec = [0u8; CHAIN_REC_BYTES as usize];+ ChainRec {+ // Chunk-local; rebased by the sink.+ pts_start: state.points, pts_len: (hi - lo + 1) as u32,+ first: ids[0],+ last: ids[ids.len() - 1], dist_mm: hops[lo..hi].iter().fold(0u32, |a, d| a.saturating_add(*d)),+ // Chunk-local name id (or u32::MAX); rebased by the sink. name_offset: attrs.name,- type_: attrs.type_,- speed_limit: attrs.speed_limit,- oneway: attrs.oneway, // Forward is along ref order, and so is the chain: no reorientation,- // so no chance of handing the masks to the wrong end.+ // so no chance of handing the masks to the wrong end. Chunk-local+ // offsets; rebased by the sink when the count is non-zero. fwd_lane_off: attrs.fwd_lane_off,- fwd_lane_count: attrs.fwd_lane_count, bwd_lane_off: attrs.bwd_lane_off,+ fwd_lane_count: attrs.fwd_lane_count, bwd_lane_count: attrs.bwd_lane_count,- });+ type_: attrs.type_,+ speed_limit: attrs.speed_limit,+ oneway: attrs.oneway,+ }+ .encode(&mut rec);+ state.hdr.extend_from_slice(&rec);+ for id in ids {+ let (lat_e7, lon_e7) = coords[*id as usize];+ state.pts.extend_from_slice(&lat_e7.to_le_bytes());+ state.pts.extend_from_slice(&lon_e7.to_le_bytes());+ }+ state.points += ids.len() as u64; } }
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 3532df23df..37a8518aaf 100644--- a/scripts/maps/osm_ingest/src/chains_part1.rs+++ b/scripts/maps/osm_ingest/src/chains_part1.rs@@ -279,7 +279,7 @@ pub(crate) struct SpillWriter { hdr: BufWriter<File>, pts: BufWriter<File>, /// Points written so far, which is the next chain's `pts_start`.- points: u64,+ pub(crate) points: u64, chains: u64, } @@ -319,6 +319,20 @@ impl SpillWriter { Ok(()) } + /// 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<()> {+ 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)?;+ self.points += points;+ self.chains += hdr.len() as u64 / CHAIN_REC_BYTES;+ Ok(())+ }+ /// Flush both files and report how many chains were written. pub fn finish(mut self) -> Result<u64> { self.hdr.flush().map_err(io_err)?;
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 53892709bd..340f653976 100644--- a/scripts/maps/osm_ingest/src/graph_build.rs+++ b/scripts/maps/osm_ingest/src/graph_build.rs@@ -58,6 +58,7 @@ use std::fs::File; use std::io::{BufReader, BufWriter, Write}; use std::path::{Path, PathBuf};+use std::sync::atomic::Ordering; use crate::compact::{self, Seg, REMOVED}; use crate::chains;@@ -363,6 +364,21 @@ impl Bitset { self.bits[(idx / 8) as usize] & (1u8 << (idx % 8)) != 0 } + /// A shared, atomic view of the bits for marking from many threads at once.+ ///+ /// Setting bits is a set union, which is commutative and idempotent, so the+ /// final bits — and the count of bits that went from clear to set, which+ /// [`AtomicBits::set`] reports exactly once per bit — are independent of+ /// which thread got there first. That is what lets the PBF passes mark from+ /// their decode workers instead of a single-threaded sink.+ pub(crate) fn atomic(&mut self) -> AtomicBits<'_> {+ let bytes: &mut [u8] = &mut self.bits;+ // SAFETY: `AtomicU8` has the size, alignment and bit validity of `u8`,+ // and the exclusive borrow of `self.bits` is held for the view's+ // lifetime, so no plain access can race with the atomic ones.+ AtomicBits(unsafe { &*(bytes as *mut [u8] as *const [std::sync::atomic::AtomicU8]) })+ }+ /// Index the blocks covering ids up to and including `max_id`, returning the /// total number of set bits. ///@@ -374,21 +390,23 @@ impl Bitset { fn build_rank(&mut self, max_id: u64) -> u64 { let used = (max_id / 8 + 1) as usize; let blocks = used.div_ceil(RANK_BLOCK_BYTES);- self.rank = Vec::with_capacity(blocks + 1);+ // Per-block popcounts on the pool, then one serial prefix sum: the+ // counts are integers, so the result cannot depend on the split.+ let bits = &self.bits[..used];+ let mut rank: Vec<u64> = par::install(|| {+ bits.par_chunks(RANK_BLOCK_BYTES)+ .map(|c| c.iter().map(|b| u64::from(b.count_ones())).sum::<u64>())+ .collect()+ });+ debug_assert_eq!(rank.len(), blocks); let mut total = 0u64;- let mut prog = crate::progress::Progress::new("Rank index", blocks as u64);- for b in 0..blocks {- self.rank.push(total);- let start = b * RANK_BLOCK_BYTES;- let end = (start + RANK_BLOCK_BYTES).min(used);- total += self.bits[start..end]- .iter()- .map(|byte| u64::from(byte.count_ones()))- .sum::<u64>();- prog.inc();+ for r in rank.iter_mut() {+ let n = *r;+ *r = total;+ total += n; }- prog.finish();- self.rank.push(total);+ rank.push(total);+ self.rank = rank; total } @@ -411,6 +429,25 @@ 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. ///@@ -440,11 +477,13 @@ impl NodeIndex { #[derive(Default)] struct Pass1 {- /// Node ids referenced by a routable way, and the ids of stop-tagged nodes.- /// Per chunk and freed by the sink: nothing about a way is retained, because- /// the ways pass re-reads them.- refs: Vec<i64>,- stop_nodes: Vec<i64>,+ /// 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.
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 3c1f1b26a8..9a1fece53f 100644--- a/scripts/maps/osm_ingest/src/graph_build_part1.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part1.rs@@ -142,29 +142,23 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // 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 = pbf::run_pass_sink(- input,- &blobs,- None,- KIND_NODES | KIND_WAYS,- "Pass 1: refs + stops",- Pass1::default,- |state, block| pass1_blob(state, block, filter),- |chunk| {- for id in chunk.refs.iter().chain(chunk.stop_nodes.iter()) {- if *id >= 0 && (*id as u64) < BITSET_SIZE {- if mask.set(*id as u64) {- marked += 1;- }- // The rank index is sized from the largest id actually- // marked, not from BITSET_SIZE: indexing all 20 G nominal ids- // would cost 313 MB to describe blocks no node reaches.- max_id = max_id.max(*id as u64);- }- }- Ok(())- },- )?;+ let blob_kinds = {+ let bits = mask.atomic();+ pbf::run_pass_sink(+ input,+ &blobs,+ None,+ KIND_NODES | KIND_WAYS,+ "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@@ -278,40 +272,90 @@ pub fn build_with(input: &Path, out_dir: &Path, opts: Options) -> Result<Stats> // to be collapsed away. timer.switch("morton-sort"); println!("Sorting {kept_count} surviving node(s) by spatial key...");- let mut keys: Vec<(u64, u32)> = Vec::with_capacity(kept_count as usize);- let mut prog = crate::progress::Progress::new("Morton keys", u64::from(slots));- for i in 0..slots {- if kept.get(u64::from(i)) {- let (lat_e7, lon_e7) = coords[i as usize];- keys.push((spatial_from_e7(lat_e7, lon_e7), i));+ // 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<((usize, usize), &mut [(u64, u32)])> = 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; }- prog.inc();+ 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());+ });+ }); }- prog.finish();- debug_assert_eq!(keys.len(), kept_count as usize);- // The key is `(spatial, dense)`, and the loop above pushed `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.+ // 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 node_coords: Vec<geom::Pt> = Vec::with_capacity(kept_count as usize); let mut stops_final = Bitset::new(u64::from(kept_count));- let mut prog = crate::progress::Progress::new("Final id assignment", keys.len() as u64);- for (final_id, (_, dense)) in keys.iter().enumerate() {- final_of_kept[kept.dense(u64::from(*dense)) as usize] = final_id as u32;- node_coords.push(coords[*dense as usize]);- if stop.get(u64::from(*dense)) {- stops_final.set(final_id as u64);- }- prog.inc();- }- prog.finish();+ 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
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 47ec8eb0d3..e41c0847a6 100644--- a/scripts/maps/osm_ingest/src/graph_build_part2.rs+++ b/scripts/maps/osm_ingest/src/graph_build_part2.rs@@ -16,7 +16,7 @@ fn collapse_within_ways<W: std::io::Write + Send>( timer: &mut crate::timing::PhaseTimer, ) -> Result<Collapsed> { timer.switch("collapse-degrees");- let degree = chains::count_degrees(input, blobs, blob_kinds, index, slots, filter)?;+ let degree = chains::count_degrees(input, blobs, blob_kinds, index, coords, slots, filter)?; let spill = chains::Spill::split(spill_dir, spill_pts_dir); timer.switch("collapse-chains"); let built = chains::build(@@ -24,15 +24,31 @@ fn collapse_within_ways<W: std::io::Write + Send>( )?; report_way_blobs(blobs.len(), &built.kinds); + // One byte of `kept` (eight nodes) per item, on the pool: each byte is a+ // pure function of its own nodes, so the split cannot show. let mut kept = Bitset::new(u64::from(slots));- let mut prog = crate::progress::Progress::new("Selecting kept nodes", u64::from(slots));- for i in 0..slots {- if index.present.get(u64::from(i)) && chains::survives(&built.endpoints, °ree, stop, i) {- kept.set(u64::from(i));- }- prog.inc();+ {+ let n = u64::from(slots);+ let present = &index.present;+ let ends = &built.endpoints;+ let degree = °ree;+ par::install(|| {+ kept.bits.par_chunks_mut(1 << 16).enumerate().for_each(|(ci, chunk)| {+ for (j, byte) in chunk.iter_mut().enumerate() {+ let base = (((ci << 16) + j) as u64) * 8;+ let mut v = 0u8;+ for k in 0..8u64 {+ let i = base + k;+ if i < n && present.get(i) && chains::survives(ends, degree, stop, i as u32)+ {+ v |= 1 << k;+ }+ }+ *byte = v;+ }+ });+ }); }- prog.finish(); drop(degree); let count = spill.chain_count()?;@@ -158,17 +174,33 @@ fn build_csr( ) -> Result<Csr> { println!("Building the edge index over {kept_count} node(s)..."); let chain_total = spill.chain_count()?;+ // Both scans run on the pool over the mapped header file.+ //+ // Counting is integer addition into per-node counters, so atomic+ // increments give the same counts in any order. The scatter claims each+ // slot with an atomic cursor, so WHERE in its group a target lands depends+ // on scheduling — but every group is sorted right after (below), and a+ // sorted group of `u32`s has one arrangement, so `targets` comes out+ // identical to the serial scan's.+ let headers = spill.headers_mapped()?;+ if headers.len()? != chain_total {+ return Err(Error("chains.hdr changed size under the edge index".into()));+ } let mut edge_ptr = vec![0u64; kept_count as usize + 2];- let mut hdr = spill.headers()?;- let mut prog = crate::progress::Progress::new("Edge index: counting", chain_total);- while let Some(c) = hdr.next()? {- edge_ptr[ids.get(c.first) as usize + 1] += 1;- if !c.oneway {- edge_ptr[ids.get(c.last) as usize + 1] += 1;- }- prog.inc();+ {+ let counts = atomic_u64s(&mut edge_ptr);+ let errs: Vec<Result<()>> = par::map_ranges(chain_total as usize, 1 << 16, |r| {+ for ci in r {+ let c = headers.get(ci as u64)?;+ counts[ids.get(c.first) as usize + 1].fetch_add(1, Ordering::Relaxed);+ if !c.oneway {+ counts[ids.get(c.last) as usize + 1].fetch_add(1, Ordering::Relaxed);+ }+ }+ Ok(())+ });+ errs.into_iter().collect::<Result<Vec<()>>>()?; }- prog.finish(); for i in 0..=kept_count as usize { edge_ptr[i + 1] += edge_ptr[i]; }@@ -176,22 +208,28 @@ fn build_csr( let total = edge_ptr[kept_count as usize]; timer.switch("edge-index-scatter"); let mut targets = vec![0u32; total as usize];- let mut cursor: Vec<u64> = edge_ptr[..=kept_count as usize].to_vec();- let mut hdr = spill.headers()?;- let mut prog = crate::progress::Progress::new("Edge index: scatter", chain_total);- while let Some(c) = hdr.next()? {- let (a, b) = (ids.get(c.first), ids.get(c.last));- let slot = &mut cursor[a as usize];- targets[*slot as usize] = b;- *slot += 1;- if !c.oneway {- let slot = &mut cursor[b as usize];- targets[*slot as usize] = a;- *slot += 1;- }- prog.inc();+ {+ let mut cursor: Vec<u64> = edge_ptr[..=kept_count as usize].to_vec();+ let cursor = atomic_u64s(&mut cursor);+ let out = par::SyncPtr(targets.as_mut_ptr());+ let errs: Vec<Result<()>> = par::map_ranges(chain_total as usize, 1 << 16, |r| {+ for ci in r {+ let c = headers.get(ci as u64)?;+ let (a, b) = (ids.get(c.first), ids.get(c.last));+ let slot = cursor[a as usize].fetch_add(1, Ordering::Relaxed);+ // SAFETY: `fetch_add` hands every slot out exactly once, and the+ // counts above bound each group's slots to its own range.+ unsafe { out.write(slot as usize, b) };+ if !c.oneway {+ let slot = cursor[b as usize].fetch_add(1, Ordering::Relaxed);+ // SAFETY: as above.+ unsafe { out.write(slot as usize, a) };+ }+ }+ Ok(())+ });+ errs.into_iter().collect::<Result<Vec<()>>>()?; }- prog.finish(); edge_ptr.truncate(kept_count as usize + 1); // Per group, so `twin_is_unique` can binary-search it. Sorting the whole array@@ -233,6 +271,17 @@ fn build_csr( Ok(Csr { edge_ptr, targets }) } +/// A `Vec<u64>` as shared atomic counters for the length of the borrow.+fn atomic_u64s(v: &mut [u64]) -> &[std::sync::atomic::AtomicU64] {+ // SAFETY: `AtomicU64` has the size and bit validity of `u64` and, on every+ // target this tool builds for, its alignment too (asserted below); the+ // exclusive borrow is held for the view's lifetime.+ const _: () = assert!(+ std::mem::align_of::<std::sync::atomic::AtomicU64>() == std::mem::align_of::<u64>()+ );+ unsafe { &*(v as *mut [u64] as *const [std::sync::atomic::AtomicU64]) }+}+ /// True when `target`'s edge range holds exactly one edge pointing back at /// `source`. ///@@ -264,8 +313,20 @@ fn pass1_blob( state: &mut Pass1, block: &pbf::PrimitiveBlock, filter: RegionFilter,+ mask: &AtomicBits, ) -> Result<u8> { let mut kinds = 0u8;+ let mut mark = |id: i64| {+ if id >= 0 && (id as u64) < BITSET_SIZE {+ if mask.set(id as u64) {+ state.marked += 1;+ }+ // The rank index is sized from the largest id actually marked,+ // not from BITSET_SIZE: indexing all 20 G nominal ids would cost+ // 313 MB to describe blocks no node reaches.+ state.max_id = state.max_id.max(id as u64);+ }+ }; visit_block( block, KIND_NODES | KIND_WAYS,@@ -283,13 +344,15 @@ fn pass1_blob( // place the region filter can apply without a location // table. if crate::bbox::keep_e7(filter.as_ref(), n.lat_e7, n.lon_e7) {- state.stop_nodes.push(n.id);+ mark(n.id); } } } Element::Way(w) => { if tags::get_hw_id(w.tags.get_str("highway")) != 0 {- state.refs.extend_from_slice(w.refs);+ for r in w.refs {+ mark(*r);+ } } } Element::Relation(_) => {}
scripts/maps/osm_ingest/src/osm.rs
diff --git a/scripts/maps/osm_ingest/src/osm.rs b/scripts/maps/osm_ingest/src/osm.rsindex c4219116fe..559801bc2b 100644--- a/scripts/maps/osm_ingest/src/osm.rs+++ b/scripts/maps/osm_ingest/src/osm.rs@@ -119,7 +119,33 @@ pub fn visit_block<F>( where F: FnMut(Element) -> Result<()>, {- let mut scratch = Scratch::default();+ // Reuse this thread's decode buffers across blocks. A fresh `Scratch` per+ // block regrew ~10 vectors from empty to tens of KB on every blob, and with+ // 192 decode threads that malloc/realloc churn serialised on allocator+ // locks (most of a California build's ~400 s of system time). Contents are+ // cleared before every use, so reuse changes nothing but the allocations.+ // Taken, not borrowed, so a nested visit (none exists) would just get a+ // fresh one.+ let mut scratch = SCRATCH.with(|c| c.take());+ let r = visit_groups(block, want, kinds, f, &mut scratch);+ SCRATCH.with(|c| c.set(scratch));+ r+}++thread_local! {+ static SCRATCH: std::cell::Cell<Scratch> = std::cell::Cell::new(Scratch::default());+}++fn visit_groups<F>(+ block: &PrimitiveBlock,+ want: u8,+ kinds: &mut u8,+ f: &mut F,+ scratch: &mut Scratch,+) -> Result<()>+where+ F: FnMut(Element) -> Result<()>,+{ for group in &block.groups { let mut g = Reader::new(group); while let Some((field, wire)) = g.next_field()? {@@ -132,28 +158,28 @@ where *kinds |= KIND_NODES; let body = g.bytes()?; if want & KIND_NODES != 0 {- visit_node(block, body, &mut scratch, f)?;+ visit_node(block, body, scratch, f)?; } } 2 => { *kinds |= KIND_NODES; let body = g.bytes()?; if want & KIND_NODES != 0 {- visit_dense(block, body, &mut scratch, f)?;+ visit_dense(block, body, scratch, f)?; } } 3 => { *kinds |= KIND_WAYS; let body = g.bytes()?; if want & KIND_WAYS != 0 {- visit_way(block, body, &mut scratch, f)?;+ visit_way(block, body, scratch, f)?; } } 4 => { *kinds |= KIND_RELATIONS; let body = g.bytes()?; if want & KIND_RELATIONS != 0 {- visit_relation(block, body, &mut scratch, f)?;+ visit_relation(block, body, scratch, f)?; } } _ => g.skip(wire)?,
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 68f205facb..7f29462b96 100644--- a/scripts/maps/osm_ingest/src/par.rs+++ b/scripts/maps/osm_ingest/src/par.rs@@ -171,6 +171,40 @@ where .collect() } +/// Apply `f(lo..hi)` to every fixed `chunk_len`-sized range of `0..n`,+/// returning the results in range order. [`map_chunks`] over indices without+/// materialising them: the deterministic shape for loops over billions of ids.+pub fn map_ranges<R, F>(n: usize, chunk_len: usize, f: F) -> Vec<R>+where+ R: Send,+ F: Fn(std::ops::Range<usize>) -> R + Sync,+{+ let chunk_len = chunk_len.max(1);+ let starts: Vec<usize> = (0..n.div_ceil(chunk_len)).map(|c| c * chunk_len).collect();+ map_chunks(&starts, 1, |_, s| f(s[0]..(s[0] + chunk_len).min(n)))+}++/// A raw pointer that may be shared across the pool, for scatters whose+/// targets are provably distinct (a permutation, or slots claimed by an atomic+/// cursor). Every use states why its writes cannot collide.+#[derive(Clone, Copy)]+pub struct SyncPtr<T>(pub *mut T);+// SAFETY: only ever dereferenced at indices the caller has proven disjoint.+unsafe impl<T: Send> Send for SyncPtr<T> {}+unsafe impl<T: Send> Sync for SyncPtr<T> {}++impl<T> SyncPtr<T> {+ /// Write `v` at `i`.+ ///+ /// # Safety+ /// `i` is in bounds of the allocation and no other thread reads or writes+ /// index `i` concurrently.+ #[inline]+ pub unsafe fn write(self, i: usize, v: T) {+ unsafe { self.0.add(i).write(v) }+ }+}+ #[cfg(test)] mod tests { use super::*;@@ -207,6 +241,15 @@ mod tests { assert_eq!(resolve(0, Some(" 3 ")), 3, "surrounding space is tolerated"); } + #[test]+ fn ranges_cover_everything_once_in_order() {+ let out = map_ranges(1001, 64, |r| (r.start, r.end));+ assert_eq!(out.first(), Some(&(0, 64)));+ assert_eq!(out.last(), Some(&(960, 1001)));+ assert!(out.windows(2).all(|w| w[0].1 == w[1].0));+ assert!(map_ranges(0, 8, |r| r).is_empty());+ }+ #[test] fn empty_input_produces_no_chunks() { let out = map_chunks::<usize, usize, _>(&[], 8, |_, _| unreachable!());
scripts/maps/osm_ingest/src/pbf.rs
diff --git a/scripts/maps/osm_ingest/src/pbf.rs b/scripts/maps/osm_ingest/src/pbf.rsindex 997dec449f..4de76319d4 100644--- a/scripts/maps/osm_ingest/src/pbf.rs+++ b/scripts/maps/osm_ingest/src/pbf.rs@@ -18,7 +18,7 @@ use std::fs::File; use std::io::{BufReader, Read, Seek, SeekFrom, Write}; use std::path::Path; use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering};-use std::sync::{Condvar, Mutex};+use std::sync::Mutex; use crate::proto::{self, Error, Reader, Result, WIRE_BYTES}; use crate::pbf_extra::decode_blob_header;@@ -285,9 +285,9 @@ impl<'a> PrimitiveBlock<'a> { /// together. Here a chunk is folded and freed while its neighbours are still /// being decoded, which also overlaps the merge with the I/O. ///-/// `sink` is called under a lock, so it is serialised against the workers. That-/// is the same single-threaded merge [`run_pass`]'s callers already do, only-/// earlier.+/// `sink` runs on the calling thread, one chunk at a time and strictly in chunk+/// order, outside any lock the workers take — so it overlaps with decoding but+/// is still the same single-threaded, ordered merge [`run_pass`]'s callers do. /// /// `blob_kinds` (from a previous full pass) lets later passes skip blobs that /// hold nothing they want — a real win because a PBF stores all nodes first,@@ -311,11 +311,11 @@ where H: FnMut(S) -> Result<()> + Send, { let n_chunks = blobs.len().div_ceil(CHUNK_BLOBS).max(1);- let drain: Mutex<Drain<S, H>> = Mutex::new(Drain {+ let shared: Mutex<Shared<S>> = Mutex::new(Shared { slots: (0..n_chunks).map(|_| None).collect(), next: 0,- sink,- err: None,+ waiters: Vec::new(),+ failed: false, }); let kinds: Vec<AtomicU8> = (0..blobs.len()).map(|_| AtomicU8::new(0)).collect(); @@ -327,6 +327,8 @@ where let pass_start = std::time::Instant::now(); let n_threads = crate::par::threads().min(n_chunks); let mut first_err: Option<Error> = None;+ let mut sink_err: Option<Error> = None;+ let mut sink = sink; // How far ahead of the sink the workers may run. // // Without this the reorder buffer is unbounded: a worker deposits and immediately@@ -343,14 +345,40 @@ where // its doc for the 2.19 GB that cost. Bounding this in bytes would mean measuring `S`, // which is opaque here by design. let window = n_threads.saturating_mul(2).max(2);- let progressed = Condvar::new();+ // Workers still running; the drain stops waiting once it reaches zero, so a+ // worker that failed (or unwound, in tests) cannot strand it.+ let alive = AtomicUsize::new(n_threads); + // The sink runs HERE, on the calling thread, and never under the lock.+ //+ // It used to run inside `deposit`, under the one mutex every worker takes+ // to deposit and to check the window, and each deposit `notify_all`-ed+ // every worker parked on the window. At 192 threads with a sink that is the+ // bottleneck that was a thundering herd: California spent ~400 s of system+ // time (vs ~110 s user) in futex hash-bucket spinlocks. Now a deposit is a+ // slot store plus an unpark of the drain thread, the sink overlaps with the+ // deposits, and a window waiter is woken only when ITS chunk enters the+ // window. Order is unchanged: the sink still sees chunks strictly in index+ // order, one at a time, on one thread.+ let drain_thread = std::thread::current(); std::thread::scope(|scope| { let mut handles = Vec::with_capacity(n_threads); for _ in 0..n_threads { handles.push(scope.spawn(|| -> Result<()> {+ struct Alive<'a>(&'a AtomicUsize, std::thread::Thread);+ impl Drop for Alive<'_> {+ fn drop(&mut self) {+ self.0.fetch_sub(1, Ordering::AcqRel);+ self.1.unpark();+ }+ }+ let _alive = Alive(&alive, drain_thread.clone());+ let fail = |e: Error| -> Error {+ shared.lock().expect("chunk slot mutex").failed = true;+ e+ }; let mut file = File::open(path)- .map_err(|e| Error(format!("cannot open {}: {e}", path.display())))?;+ .map_err(|e| fail(Error(format!("cannot open {}: {e}", path.display()))))?; let mut compressed = Vec::new(); let mut inflated = Vec::new(); loop {@@ -361,11 +389,17 @@ where // Hold off until this chunk is inside the window. The worker that // owns the lowest outstanding chunk always passes this test, so it // always makes progress and the wait cannot deadlock.- {- let mut d = drain.lock().expect("chunk slot mutex");- while chunk >= d.next + window {- d = progressed.wait(d).expect("chunk slot mutex");+ loop {+ let mut st = shared.lock().expect("chunk slot mutex");+ if chunk < st.next + window || st.failed {+ st.waiters.retain(|(c, _)| *c != chunk);+ break;+ }+ if !st.waiters.iter().any(|(c, _)| *c == chunk) {+ st.waiters.push((chunk, std::thread::current())); }+ drop(st);+ std::thread::park(); } let start = chunk * CHUNK_BLOBS; let end = ((chunk + 1) * CHUNK_BLOBS).min(blobs.len());@@ -375,20 +409,74 @@ where match blob_kinds.filter(|k| k[idx] & want == 0) { Some(k) => kinds[idx].store(k[idx], Ordering::Relaxed), None => {- read_exact_at(&mut file, loc, &mut compressed)?;- inflate_blob(&compressed, &mut inflated)?;- let block = PrimitiveBlock::decode(&inflated)?;- let seen = body(&mut state, &block)?;+ read_exact_at(&mut file, loc, &mut compressed).map_err(fail)?;+ inflate_blob(&compressed, &mut inflated).map_err(fail)?;+ let block = PrimitiveBlock::decode(&inflated).map_err(fail)?;+ let seen = body(&mut state, &block).map_err(fail)?; kinds[idx].store(seen, Ordering::Relaxed); } } report(label, &done_blobs, &last_pct, blobs.len(), &pass_start); }- drain.lock().expect("chunk slot mutex").deposit(chunk, state);- progressed.notify_all();+ shared.lock().expect("chunk slot mutex").slots[chunk] = Some(state);+ drain_thread.unpark(); } })); }++ // The in-order drain.+ let mut next = 0usize;+ while next < n_chunks {+ let (ready, failed) = {+ let mut st = shared.lock().expect("chunk slot mutex");+ match st.slots[next].take() {+ Some(s) => {+ st.next = next + 1;+ // Admit exactly the waiters whose chunk just entered the window.+ let limit = st.next + window;+ let mut i = 0;+ while i < st.waiters.len() {+ if st.waiters[i].0 < limit {+ st.waiters.swap_remove(i).1.unpark();+ } else {+ i += 1;+ }+ }+ (Some(s), st.failed)+ }+ None => (None, st.failed),+ }+ };+ match ready {+ Some(s) => {+ next += 1;+ // Keep draining after a failure: the pass reports the first error+ // at the end, and stopping here would strand the remaining chunks.+ if let Err(e) = sink(s) {+ if sink_err.is_none() {+ sink_err = Some(e);+ }+ }+ }+ None => {+ if failed || alive.load(Ordering::Acquire) == 0 {+ // A worker failed (its chunk will never arrive), or every+ // worker is gone: release anyone parked on the window and+ // stop; the join below reports the error.+ let mut st = shared.lock().expect("chunk slot mutex");+ st.failed = true;+ for (_, t) in st.waiters.drain(..) {+ t.unpark();+ }+ if alive.load(Ordering::Acquire) == 0 {+ break;+ }+ }+ std::thread::park_timeout(std::time::Duration::from_millis(50));+ }+ }+ }+ for h in handles { match h.join() { Ok(Ok(())) => {}@@ -404,18 +492,19 @@ where } } }+ if first_err.is_none() && next < n_chunks {+ first_err = Some(Error(format!(+ "pass {label}: chunks {next}..{n_chunks} were never produced"+ )));+ } }); if let Some(e) = first_err { return Err(e); }- let mut d = drain.into_inner().expect("chunk slot mutex");- if let Some(e) = d.err.take() {+ if let Some(e) = sink_err { return Err(e); }- // Every chunk was deposited, and deposits drain in order, so nothing can be- // left behind unless a sink call failed above.- debug_assert_eq!(d.next, n_chunks, "chunks left undrained"); // Snap to 100% in the same standard shape, then a fresh line so the next // stage starts clean instead of on top of the meter. {@@ -428,32 +517,16 @@ where Ok(kinds.iter().map(|k| k.load(Ordering::Relaxed)).collect()) } -/// Holds finished chunks until their turn comes, so the sink sees chunk order-/// however the workers finish.-struct Drain<S, H> {+/// Finished chunks waiting for their turn, plus the window bookkeeping. The+/// sink itself lives on the draining thread, outside this lock.+struct Shared<S> { slots: Vec<Option<S>>,+ /// The next chunk the drain will hand to the sink. next: usize,- sink: H,- err: Option<Error>,-}--impl<S, H: FnMut(S) -> Result<()>> Drain<S, H> {- fn deposit(&mut self, chunk: usize, state: S) {- self.slots[chunk] = Some(state);- while self.next < self.slots.len() {- let Some(s) = self.slots[self.next].take() else {- break;- };- self.next += 1;- // Keep draining after a failure: the pass reports the first error at- // the end, and stopping here would strand the remaining chunks.- if let Err(e) = (self.sink)(s) {- if self.err.is_none() {- self.err = Some(e);- }- }- }- }+ /// Workers parked until their chunk enters the window: `(chunk, thread)`.+ waiters: Vec<(usize, std::thread::Thread)>,+ /// A worker failed, so a chunk will never arrive: stop waiting.+ failed: bool, } /// Run one pass over the file in parallel, returning every chunk's accumulator.