/// Lane inheritance over the ways spill. Moved whole from `extract`. /// /// The scan is batched: the expensive per-way work (coordinate lookup through the node /// table — a rank-bitset search plus a mapped-file read per node) runs on the pool, while /// the collector push stays serial in spill order. `table.line` is shared-read-only (the /// materialise pass already calls it from `par_iter`), and the collector's output order /// never reaches the archive — `finish` sorts every partition — so the bytes are identical. /// What this buys: the scan is ~1.1 B sequential ways on a planet input, each paying ~10 /// node lookups; serially that is tens of minutes of mapped-file random reads. /// /// `region` limits the join to the ways that can pair with a materialised way (see /// [`fringe_touches`]): on a `--region` build over a larger input, the ways outside the /// fringe can never share an endpoint node with a kept recipient, so resolving them would /// be pure waste. `None` (world) disables the filter entirely. fn inherit_lane_counts( spill_path: &Path, blocks: &WayBlocks, table: &NodeLocations, ways_classified: usize, region: Option<&osm_ingest::bbox::BBox>, ) -> Result> { // --- lane inheritance ------------------------------------------------------------------- // // A junction stub OSM left untagged takes a lane count from the road it interrupts, instead of // the renderer's flat `oneway ? 1 : 2`. See [`crate::lanefill`] for the conditions and the // measurements behind each of them. It runs here rather than in pass 1 because the conditions // are geometric — a length and a turn angle — and coordinates are only resolved above. // // Block-parallel: every ways-spill block is decoded, filtered, resolved and turned into its // endpoint records on the pool ([`for_each_way_block`]); only the fixed-width record writes // stay serial, in block order -- which is spill order, so the partition files hold the same // bytes the one-cursor scan wrote. On the planet the one-cursor scan was 6 min at ~4 cores. let fringe = region.map(expanded_fringe); let mut collector = crate::lanefill::Collector::create(spill_path)?; let mut bar = Progress::new( "Lane inheritance: scan".to_string(), ways_classified, "way(s)", true, ); for_each_way_block( blocks, |mut reader| -> Result> { let mut refs: Vec = Vec::new(); let mut indices: Vec = Vec::new(); let mut out = Vec::new(); while let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? { // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on // very nearly its parent's heading, so it would inherit the mainline's width onto a // single-lane ramp; `corridor` leaves links out of a corridor for the same reason. if class.layer != tilecodec::mamaps::dict::LAYER_ROADS || class.flags & tilecodec::mamaps::body::FLAG_IS_LINK != 0 { continue; } let Some(name) = name else { continue }; let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0; if fringe.is_none() { // World build: no fringe to test, so read only the coordinates the join needs // (`lanefill::prepare_lazy`). A way with an unresolved node is one `prepare` // drops (its line would be shorter than its refs). if table.indices_if_complete(&refs, &mut indices) { if let Some(prepared) = crate::lanefill::prepare_lazy( id, &name, lane_count, oneway, &refs, |i| table.coord_at(indices[i]), ) { out.push(prepared); } } continue; } let line = table.line(&refs); // A region build only joins the fringe: a recipient is at most 50 m long, so // a donor sharing an endpoint node with a kept recipient always touches the // expanded box (see `expanded_fringe`). Anything else can pair only with // ways materialise drops — work with no reader. if !fringe_touches(fringe.as_ref(), &line) { continue; } if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment { id, name: &name, lanes: lane_count, oneway, nodes: &refs, line: &line, }) { out.push(prepared); } } Ok(out) }, |ways, prepared| { for p in &prepared { collector.push_prepared(p)?; } bar.tick_n(ways as usize, "way(s)"); Ok(()) }, )?; bar.finish("way(s)"); collector.finish() } /// Ways-spill blocks decoded per pool hand-off, per thread. Each block is at most /// [`WAY_BLOCK_WAYS`] ways, so a group is ~1.5 M ways on 192 threads: enough to keep every core /// busy with even load, and a bounded amount of finished work (endpoint records, spill records) /// held while the previous group drains. const BLOCKS_PER_THREAD: usize = 2; /// Run `work` over every block of the ways spill on the pool and hand each block's result to /// `drain` **in block order**, which is spill order. /// /// Pipelined: while `drain` consumes group `k` on one thread, the pool computes group `k + 1`. /// `work` gets a fresh cursor over its block; `drain` gets the block's way count (for progress) /// and its result. The first error in block order wins, exactly as a one-cursor loop would /// report it; work already computed past it is discarded. fn for_each_way_block(blocks: &WayBlocks, work: W, mut drain: D) -> Result<()> where T: Send, W: Fn(WayReader) -> Result + Sync, D: FnMut(u64, T) -> Result<()> + Send, { let locs = blocks.locs(); let group = (par::threads() * BLOCKS_PER_THREAD).max(1); pipeline_ordered( locs.len(), group, |i| blocks.reader(i).and_then(&work), |i, result| drain(locs[i].ways(), result?), ) } /// Run `work(i)` for every `i in 0..len` on the pool, `group` items per hand-off, and hand each /// result to `drain` **in index order**. While `drain` consumes one group on one thread, the pool /// computes the next, so the serial drain overlaps the parallel work instead of alternating with /// it -- and a slow item delays only its own group's drain, not a barrier every few thousand /// items. The first error `drain` returns stops the loop; work already computed past it is /// discarded. pub(crate) fn pipeline_ordered(len: usize, group: usize, work: W, mut drain: D) -> Result<()> where T: Send, W: Fn(usize) -> T + Sync, D: FnMut(usize, T) -> Result<()> + Send, { let group = group.max(1); par::install(|| { let mut start = 0usize; let mut pending: Option<(usize, Vec)> = None; loop { let end = (start + group).min(len); let (drained, next) = rayon::join( || -> Result<()> { if let Some((first, results)) = pending.take() { for (k, result) in results.into_iter().enumerate() { drain(first + k, result)?; } } Ok(()) }, || { if start < end { Some((start..end).into_par_iter().map(&work).collect::>()) } else { None } }, ); drained?; match next { Some(results) => pending = Some((start, results)), None => return Ok(()), } start = end; } }) } /// One materialised way, decided on the pool: the serial drain only appends. /// /// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered) /// counts nothing — exactly the two non-pushed paths the inline drain had. /// `Kept` carries the finished spill record ([`PreRecord`]), so the drain neither walks vertices /// nor encodes. enum BuiltWay { Failed, Dropped, Kept(PreRecord), } /// Resolve one way's fate: geometry, region keep/drop, and its spill record. /// /// Pure over shared tables (`table`, `region`): safe across the pool. The record is built with /// the same choice of shape the serial drain made -- a building carries its S3DB attributes, a /// road with lane data carries those, everything else (a plain road included) goes the plain, /// named way -- so `Sink::push_pre` stages exactly what `push_building` / `push_road` / /// `push_named` would have. #[allow(clippy::too_many_arguments)] fn build_way( class: &Class, geometry: Option, region: Option<&osm_ingest::bbox::BBox>, name: Option<&str>, id: u64, lane_count: u8, turn_fwd: &[u16], turn_bwd: &[u16], carriageway: Carriageway, building: Option, ) -> Result { let Some(geometry) = geometry else { return Ok(BuiltWay::Failed); }; // Region filter: roads, pois and buildings outside the bbox are dropped. // The geometry is resolved by now, so this is a direct touches-box test // on the line the way produced (a centroided point for labels). if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) { return Ok(BuiltWay::Dropped); } let encoded = crate::store::EncodedGeom::live(&geometry)?; let record = if let Some(b) = building { PreRecord::building(class, &encoded, name, b)? } else if lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() || !carriageway.is_empty() { PreRecord::road(class, &encoded, name, lane_count, turn_fwd, turn_bwd, carriageway)? } else { PreRecord::named(class, &encoded, name, id)? }; Ok(BuiltWay::Kept(record)) } /// Materialise classified ways off disk, in id order. Moved whole from `extract`. /// /// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in /// one of those layers whose resolved line touches no bbox point is dropped. /// Every other layer is always kept. Kept whole, never clipped — the tiler /// clips per tile later. /// /// Consumes `blocks`: it is the spill's last reader, and the handle must be closed before the /// file is removed (Windows refuses to delete an open file). #[allow(clippy::too_many_arguments)] fn materialise_ways( ways_path: &Path, blocks: WayBlocks, promoted: &[(i64, u8)], inherited_lanes: &[(i64, u8)], table: &NodeLocations, region: Option<&osm_ingest::bbox::BBox>, sink: &mut Sink, stats: &mut Stats, ) -> Result<()> { // Silent until now, and it is not a short step: on a north-america extract this loop ran 623 // seconds on one thread with nothing on stdout, which is indistinguishable from a hang. let mut bar = Progress::new( "Materialise: ways".to_string(), stats.ways_classified as usize, "way(s)", true, ); // Block-parallel end to end: decoding the spill, the coordinate lookups (`table.line`, an id // search plus a random read of a mapped file per node), ring closing, the region test and the // spill record itself all run on the pool, per block; the sink then appends the finished // records **in block order** -- spill order -- which is what keeps the archive byte-identical: // the spill's feature order is the archive's. Measured before this on California: decode // (`fill`) 5.5 s and record encode + DEFLATE (`push`) 19.0 s of 26.6 s were serial. let mut drain_wall = std::time::Duration::ZERO; let wall = std::time::Instant::now(); let (mut failed, mut kept) = (0u64, 0u64); for_each_way_block( &blocks, |mut reader| -> Result<(RecordRun, u64)> { let mut refs: Vec = Vec::new(); // The block's kept records go straight into one run (`Sink::push_run`); the first // failure in the block ends it with that error, which the in-order drain reports as // the first in spill order -- as the record-by-record drain did. let mut run = RecordRun::default(); let mut block_failed = 0u64; while let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) = reader.next(&mut refs)? { let mut class = class; // The corridor's zoom, where it is shallower than this way's own. Corridors // are built from numbered roads alone, so a non-road way can never have an // entry — searching for one is ~17 wasted compares per boundary, building // and waterway on a region build. if class.layer == tilecodec::mamaps::dict::LAYER_ROADS { if let Ok(at) = promoted.binary_search_by_key(&id, |(id, _)| *id) { class.min_zoom = promoted[at].1; } } // A neighbour's lane count, where OSM tagged none on this way. Only ever consulted // for a way that has none of its own, so a tag is never overridden. let lane_count = if lane_count == 0 { inherited_lanes .binary_search_by_key(&id, |(id, _)| *id) .map_or(0, |at| inherited_lanes[at].1) } else { lane_count }; // Only a label way carries its id onward. A road or a building is merged with its // neighbours by `coalesce`, which leaves the survivor's id arbitrary, and the id // table exists for `poi` and `places` alone. let id = if is_label(class.layer) { tagged_id(id, ELEMENT_WAY) } else { tilecodec::mamaps::body::ID_NONE }; let line = table.line(&refs); // A label layer's ways are centroided to points: a town mapped as an area // is still one label, not a loop. Everything else keeps its geometry. let geometry = if is_label(class.layer) { centroid(&line).map(|point| Geometry::Points(vec![point])) } else { way_geometry(&line, class.area) }; match build_way( &class, geometry, region, name.as_deref(), id, lane_count, &turn_fwd, &turn_bwd, carriageway, building, )? { BuiltWay::Failed => block_failed += 1, BuiltWay::Dropped => {} BuiltWay::Kept(record) => run.add(record), } } Ok((run, block_failed)) }, |ways, built| { let t = std::time::Instant::now(); let (run, block_failed) = built; failed += block_failed; kept += run.len() as u64; sink.push_run(run)?; bar.tick_n(ways as usize, "way(s)"); drain_wall += t.elapsed(); Ok(()) }, )?; stats.geometry_failed += failed; stats.features += kept; // TEMP-PROFILE: the serial drain's share of the phase wall. Removed with the other probes. eprintln!( " [profile] materialise-ways wall={:.1}s drain={:.1}s spill={:.2}GB", wall.elapsed().as_secs_f64(), drain_wall.as_secs_f64(), sink.staged_bytes() as f64 / 1e9 ); bar.finish("way(s)"); // Nothing reads the ways spill after this: the relations below reach their members through // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed // (after its handle closes); the anon backend's segments unmap with the last `Arc`. drop(blocks); let _ = std::fs::remove_file(ways_path); Ok(()) }