Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / extract_part2_s1.rs
extract_part2_s1.rs366 lines · 16.5 KiBRaw
| 1 | /// Lane inheritance over the ways spill. Moved whole from `extract`. |
| 2 | /// |
| 3 | /// The scan is batched: the expensive per-way work (coordinate lookup through the node |
| 4 | /// table — a rank-bitset search plus a mapped-file read per node) runs on the pool, while |
| 5 | /// the collector push stays serial in spill order. `table.line` is shared-read-only (the |
| 6 | /// materialise pass already calls it from `par_iter`), and the collector's output order |
| 7 | /// never reaches the archive — `finish` sorts every partition — so the bytes are identical. |
| 8 | /// What this buys: the scan is ~1.1 B sequential ways on a planet input, each paying ~10 |
| 9 | /// node lookups; serially that is tens of minutes of mapped-file random reads. |
| 10 | /// |
| 11 | /// `region` limits the join to the ways that can pair with a materialised way (see |
| 12 | /// [`fringe_touches`]): on a `--region` build over a larger input, the ways outside the |
| 13 | /// fringe can never share an endpoint node with a kept recipient, so resolving them would |
| 14 | /// be pure waste. `None` (world) disables the filter entirely. |
| 15 | fn inherit_lane_counts( |
| 16 | spill_path: &Path, |
| 17 | blocks: &WayBlocks, |
| 18 | table: &NodeLocations, |
| 19 | ways_classified: usize, |
| 20 | region: Option<&osm_ingest::bbox::BBox>, |
| 21 | ) -> Result<Vec<(i64, u8)>> { |
| 22 | // --- lane inheritance ------------------------------------------------------------------- |
| 23 | // |
| 24 | // A junction stub OSM left untagged takes a lane count from the road it interrupts, instead of |
| 25 | // the renderer's flat `oneway ? 1 : 2`. See [`crate::lanefill`] for the conditions and the |
| 26 | // measurements behind each of them. It runs here rather than in pass 1 because the conditions |
| 27 | // are geometric — a length and a turn angle — and coordinates are only resolved above. |
| 28 | // |
| 29 | // Block-parallel: every ways-spill block is decoded, filtered, resolved and turned into its |
| 30 | // endpoint records on the pool ([`for_each_way_block`]); only the fixed-width record writes |
| 31 | // stay serial, in block order -- which is spill order, so the partition files hold the same |
| 32 | // bytes the one-cursor scan wrote. On the planet the one-cursor scan was 6 min at ~4 cores. |
| 33 | let fringe = region.map(expanded_fringe); |
| 34 | let mut collector = crate::lanefill::Collector::create(spill_path)?; |
| 35 | let mut bar = Progress::new( |
| 36 | "Lane inheritance: scan".to_string(), |
| 37 | ways_classified, |
| 38 | "way(s)", |
| 39 | true, |
| 40 | ); |
| 41 | for_each_way_block( |
| 42 | blocks, |
| 43 | |mut reader| -> Result<Vec<crate::lanefill::Prepared>> { |
| 44 | let mut refs: Vec<i64> = Vec::new(); |
| 45 | let mut indices: Vec<usize> = Vec::new(); |
| 46 | let mut out = Vec::new(); |
| 47 | while let Some((id, class, name, lane_count, _, _, _, _)) = reader.next(&mut refs)? { |
| 48 | // Roads, and not slip roads. A ramp leaves a junction carrying its parent's name on |
| 49 | // very nearly its parent's heading, so it would inherit the mainline's width onto a |
| 50 | // single-lane ramp; `corridor` leaves links out of a corridor for the same reason. |
| 51 | if class.layer != tilecodec::mamaps::dict::LAYER_ROADS |
| 52 | || class.flags & tilecodec::mamaps::body::FLAG_IS_LINK != 0 |
| 53 | { |
| 54 | continue; |
| 55 | } |
| 56 | let Some(name) = name else { continue }; |
| 57 | let oneway = class.flags & tilecodec::mamaps::body::FLAG_IS_ONEWAY != 0; |
| 58 | if fringe.is_none() { |
| 59 | // World build: no fringe to test, so read only the coordinates the join needs |
| 60 | // (`lanefill::prepare_lazy`). A way with an unresolved node is one `prepare` |
| 61 | // drops (its line would be shorter than its refs). |
| 62 | if table.indices_if_complete(&refs, &mut indices) { |
| 63 | if let Some(prepared) = crate::lanefill::prepare_lazy( |
| 64 | id, |
| 65 | &name, |
| 66 | lane_count, |
| 67 | oneway, |
| 68 | &refs, |
| 69 | |i| table.coord_at(indices[i]), |
| 70 | ) { |
| 71 | out.push(prepared); |
| 72 | } |
| 73 | } |
| 74 | continue; |
| 75 | } |
| 76 | let line = table.line(&refs); |
| 77 | // A region build only joins the fringe: a recipient is at most 50 m long, so |
| 78 | // a donor sharing an endpoint node with a kept recipient always touches the |
| 79 | // expanded box (see `expanded_fringe`). Anything else can pair only with |
| 80 | // ways materialise drops — work with no reader. |
| 81 | if !fringe_touches(fringe.as_ref(), &line) { |
| 82 | continue; |
| 83 | } |
| 84 | if let Some(prepared) = crate::lanefill::prepare(&crate::lanefill::Segment { |
| 85 | id, |
| 86 | name: &name, |
| 87 | lanes: lane_count, |
| 88 | oneway, |
| 89 | nodes: &refs, |
| 90 | line: &line, |
| 91 | }) { |
| 92 | out.push(prepared); |
| 93 | } |
| 94 | } |
| 95 | Ok(out) |
| 96 | }, |
| 97 | |ways, prepared| { |
| 98 | for p in &prepared { |
| 99 | collector.push_prepared(p)?; |
| 100 | } |
| 101 | bar.tick_n(ways as usize, "way(s)"); |
| 102 | Ok(()) |
| 103 | }, |
| 104 | )?; |
| 105 | bar.finish("way(s)"); |
| 106 | collector.finish() |
| 107 | } |
| 108 | |
| 109 | /// Ways-spill blocks decoded per pool hand-off, per thread. Each block is at most |
| 110 | /// [`WAY_BLOCK_WAYS`] ways, so a group is ~1.5 M ways on 192 threads: enough to keep every core |
| 111 | /// busy with even load, and a bounded amount of finished work (endpoint records, spill records) |
| 112 | /// held while the previous group drains. |
| 113 | const BLOCKS_PER_THREAD: usize = 2; |
| 114 | |
| 115 | /// Run `work` over every block of the ways spill on the pool and hand each block's result to |
| 116 | /// `drain` **in block order**, which is spill order. |
| 117 | /// |
| 118 | /// Pipelined: while `drain` consumes group `k` on one thread, the pool computes group `k + 1`. |
| 119 | /// `work` gets a fresh cursor over its block; `drain` gets the block's way count (for progress) |
| 120 | /// and its result. The first error in block order wins, exactly as a one-cursor loop would |
| 121 | /// report it; work already computed past it is discarded. |
| 122 | fn for_each_way_block<T, W, D>(blocks: &WayBlocks, work: W, mut drain: D) -> Result<()> |
| 123 | where |
| 124 | T: Send, |
| 125 | W: Fn(WayReader) -> Result<T> + Sync, |
| 126 | D: FnMut(u64, T) -> Result<()> + Send, |
| 127 | { |
| 128 | let locs = blocks.locs(); |
| 129 | let group = (par::threads() * BLOCKS_PER_THREAD).max(1); |
| 130 | pipeline_ordered( |
| 131 | locs.len(), |
| 132 | group, |
| 133 | |i| blocks.reader(i).and_then(&work), |
| 134 | |i, result| drain(locs[i].ways(), result?), |
| 135 | ) |
| 136 | } |
| 137 | |
| 138 | /// Run `work(i)` for every `i in 0..len` on the pool, `group` items per hand-off, and hand each |
| 139 | /// result to `drain` **in index order**. While `drain` consumes one group on one thread, the pool |
| 140 | /// computes the next, so the serial drain overlaps the parallel work instead of alternating with |
| 141 | /// it -- and a slow item delays only its own group's drain, not a barrier every few thousand |
| 142 | /// items. The first error `drain` returns stops the loop; work already computed past it is |
| 143 | /// discarded. |
| 144 | pub(crate) fn pipeline_ordered<T, W, D>(len: usize, group: usize, work: W, mut drain: D) -> Result<()> |
| 145 | where |
| 146 | T: Send, |
| 147 | W: Fn(usize) -> T + Sync, |
| 148 | D: FnMut(usize, T) -> Result<()> + Send, |
| 149 | { |
| 150 | let group = group.max(1); |
| 151 | par::install(|| { |
| 152 | let mut start = 0usize; |
| 153 | let mut pending: Option<(usize, Vec<T>)> = None; |
| 154 | loop { |
| 155 | let end = (start + group).min(len); |
| 156 | let (drained, next) = rayon::join( |
| 157 | || -> Result<()> { |
| 158 | if let Some((first, results)) = pending.take() { |
| 159 | for (k, result) in results.into_iter().enumerate() { |
| 160 | drain(first + k, result)?; |
| 161 | } |
| 162 | } |
| 163 | Ok(()) |
| 164 | }, |
| 165 | || { |
| 166 | if start < end { |
| 167 | Some((start..end).into_par_iter().map(&work).collect::<Vec<T>>()) |
| 168 | } else { |
| 169 | None |
| 170 | } |
| 171 | }, |
| 172 | ); |
| 173 | drained?; |
| 174 | match next { |
| 175 | Some(results) => pending = Some((start, results)), |
| 176 | None => return Ok(()), |
| 177 | } |
| 178 | start = end; |
| 179 | } |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | /// One materialised way, decided on the pool: the serial drain only appends. |
| 184 | /// |
| 185 | /// `Failed` (no geometry) counts `geometry_failed`; `Dropped` (region-filtered) |
| 186 | /// counts nothing — exactly the two non-pushed paths the inline drain had. |
| 187 | /// `Kept` carries the finished spill record ([`PreRecord`]), so the drain neither walks vertices |
| 188 | /// nor encodes. |
| 189 | enum BuiltWay { |
| 190 | Failed, |
| 191 | Dropped, |
| 192 | Kept(PreRecord), |
| 193 | } |
| 194 | |
| 195 | /// Resolve one way's fate: geometry, region keep/drop, and its spill record. |
| 196 | /// |
| 197 | /// Pure over shared tables (`table`, `region`): safe across the pool. The record is built with |
| 198 | /// the same choice of shape the serial drain made -- a building carries its S3DB attributes, a |
| 199 | /// road with lane data carries those, everything else (a plain road included) goes the plain, |
| 200 | /// named way -- so `Sink::push_pre` stages exactly what `push_building` / `push_road` / |
| 201 | /// `push_named` would have. |
| 202 | #[allow(clippy::too_many_arguments)] |
| 203 | fn build_way( |
| 204 | class: &Class, |
| 205 | geometry: Option<Geometry>, |
| 206 | region: Option<&osm_ingest::bbox::BBox>, |
| 207 | name: Option<&str>, |
| 208 | id: u64, |
| 209 | lane_count: u8, |
| 210 | turn_fwd: &[u16], |
| 211 | turn_bwd: &[u16], |
| 212 | carriageway: Carriageway, |
| 213 | building: Option<BuildingAttrs>, |
| 214 | ) -> Result<BuiltWay> { |
| 215 | let Some(geometry) = geometry else { |
| 216 | return Ok(BuiltWay::Failed); |
| 217 | }; |
| 218 | // Region filter: roads, pois and buildings outside the bbox are dropped. |
| 219 | // The geometry is resolved by now, so this is a direct touches-box test |
| 220 | // on the line the way produced (a centroided point for labels). |
| 221 | if is_region_filtered(class.layer) && !geometry_touches(&geometry, region) { |
| 222 | return Ok(BuiltWay::Dropped); |
| 223 | } |
| 224 | let encoded = crate::store::EncodedGeom::live(&geometry)?; |
| 225 | let record = if let Some(b) = building { |
| 226 | PreRecord::building(class, &encoded, name, b)? |
| 227 | } else if lane_count > 0 || !turn_fwd.is_empty() || !turn_bwd.is_empty() || !carriageway.is_empty() { |
| 228 | PreRecord::road(class, &encoded, name, lane_count, turn_fwd, turn_bwd, carriageway)? |
| 229 | } else { |
| 230 | PreRecord::named(class, &encoded, name, id)? |
| 231 | }; |
| 232 | Ok(BuiltWay::Kept(record)) |
| 233 | } |
| 234 | |
| 235 | /// Materialise classified ways off disk, in id order. Moved whole from `extract`. |
| 236 | /// |
| 237 | /// `region` filters the built layers (`roads`, `poi`, `buildings`): a way in |
| 238 | /// one of those layers whose resolved line touches no bbox point is dropped. |
| 239 | /// Every other layer is always kept. Kept whole, never clipped — the tiler |
| 240 | /// clips per tile later. |
| 241 | /// |
| 242 | /// Consumes `blocks`: it is the spill's last reader, and the handle must be closed before the |
| 243 | /// file is removed (Windows refuses to delete an open file). |
| 244 | #[allow(clippy::too_many_arguments)] |
| 245 | fn materialise_ways( |
| 246 | ways_path: &Path, |
| 247 | blocks: WayBlocks, |
| 248 | promoted: &[(i64, u8)], |
| 249 | inherited_lanes: &[(i64, u8)], |
| 250 | table: &NodeLocations, |
| 251 | region: Option<&osm_ingest::bbox::BBox>, |
| 252 | sink: &mut Sink, |
| 253 | stats: &mut Stats, |
| 254 | ) -> Result<()> { |
| 255 | // Silent until now, and it is not a short step: on a north-america extract this loop ran 623 |
| 256 | // seconds on one thread with nothing on stdout, which is indistinguishable from a hang. |
| 257 | let mut bar = Progress::new( |
| 258 | "Materialise: ways".to_string(), |
| 259 | stats.ways_classified as usize, |
| 260 | "way(s)", |
| 261 | true, |
| 262 | ); |
| 263 | // Block-parallel end to end: decoding the spill, the coordinate lookups (`table.line`, an id |
| 264 | // search plus a random read of a mapped file per node), ring closing, the region test and the |
| 265 | // spill record itself all run on the pool, per block; the sink then appends the finished |
| 266 | // records **in block order** -- spill order -- which is what keeps the archive byte-identical: |
| 267 | // the spill's feature order is the archive's. Measured before this on California: decode |
| 268 | // (`fill`) 5.5 s and record encode + DEFLATE (`push`) 19.0 s of 26.6 s were serial. |
| 269 | let mut drain_wall = std::time::Duration::ZERO; |
| 270 | let wall = std::time::Instant::now(); |
| 271 | let (mut failed, mut kept) = (0u64, 0u64); |
| 272 | for_each_way_block( |
| 273 | &blocks, |
| 274 | |mut reader| -> Result<(RecordRun, u64)> { |
| 275 | let mut refs: Vec<i64> = Vec::new(); |
| 276 | // The block's kept records go straight into one run (`Sink::push_run`); the first |
| 277 | // failure in the block ends it with that error, which the in-order drain reports as |
| 278 | // the first in spill order -- as the record-by-record drain did. |
| 279 | let mut run = RecordRun::default(); |
| 280 | let mut block_failed = 0u64; |
| 281 | while let Some((id, class, name, lane_count, turn_fwd, turn_bwd, carriageway, building)) = |
| 282 | reader.next(&mut refs)? |
| 283 | { |
| 284 | let mut class = class; |
| 285 | // The corridor's zoom, where it is shallower than this way's own. Corridors |
| 286 | // are built from numbered roads alone, so a non-road way can never have an |
| 287 | // entry — searching for one is ~17 wasted compares per boundary, building |
| 288 | // and waterway on a region build. |
| 289 | if class.layer == tilecodec::mamaps::dict::LAYER_ROADS { |
| 290 | if let Ok(at) = promoted.binary_search_by_key(&id, |(id, _)| *id) { |
| 291 | class.min_zoom = promoted[at].1; |
| 292 | } |
| 293 | } |
| 294 | // A neighbour's lane count, where OSM tagged none on this way. Only ever consulted |
| 295 | // for a way that has none of its own, so a tag is never overridden. |
| 296 | let lane_count = if lane_count == 0 { |
| 297 | inherited_lanes |
| 298 | .binary_search_by_key(&id, |(id, _)| *id) |
| 299 | .map_or(0, |at| inherited_lanes[at].1) |
| 300 | } else { |
| 301 | lane_count |
| 302 | }; |
| 303 | // Only a label way carries its id onward. A road or a building is merged with its |
| 304 | // neighbours by `coalesce`, which leaves the survivor's id arbitrary, and the id |
| 305 | // table exists for `poi` and `places` alone. |
| 306 | let id = if is_label(class.layer) { |
| 307 | tagged_id(id, ELEMENT_WAY) |
| 308 | } else { |
| 309 | tilecodec::mamaps::body::ID_NONE |
| 310 | }; |
| 311 | let line = table.line(&refs); |
| 312 | // A label layer's ways are centroided to points: a town mapped as an area |
| 313 | // is still one label, not a loop. Everything else keeps its geometry. |
| 314 | let geometry = if is_label(class.layer) { |
| 315 | centroid(&line).map(|point| Geometry::Points(vec![point])) |
| 316 | } else { |
| 317 | way_geometry(&line, class.area) |
| 318 | }; |
| 319 | match build_way( |
| 320 | &class, |
| 321 | geometry, |
| 322 | region, |
| 323 | name.as_deref(), |
| 324 | id, |
| 325 | lane_count, |
| 326 | &turn_fwd, |
| 327 | &turn_bwd, |
| 328 | carriageway, |
| 329 | building, |
| 330 | )? { |
| 331 | BuiltWay::Failed => block_failed += 1, |
| 332 | BuiltWay::Dropped => {} |
| 333 | BuiltWay::Kept(record) => run.add(record), |
| 334 | } |
| 335 | } |
| 336 | Ok((run, block_failed)) |
| 337 | }, |
| 338 | |ways, built| { |
| 339 | let t = std::time::Instant::now(); |
| 340 | let (run, block_failed) = built; |
| 341 | failed += block_failed; |
| 342 | kept += run.len() as u64; |
| 343 | sink.push_run(run)?; |
| 344 | bar.tick_n(ways as usize, "way(s)"); |
| 345 | drain_wall += t.elapsed(); |
| 346 | Ok(()) |
| 347 | }, |
| 348 | )?; |
| 349 | stats.geometry_failed += failed; |
| 350 | stats.features += kept; |
| 351 | // TEMP-PROFILE: the serial drain's share of the phase wall. Removed with the other probes. |
| 352 | eprintln!( |
| 353 | " [profile] materialise-ways wall={:.1}s drain={:.1}s spill={:.2}GB", |
| 354 | wall.elapsed().as_secs_f64(), |
| 355 | drain_wall.as_secs_f64(), |
| 356 | sink.staged_bytes() as f64 / 1e9 |
| 357 | ); |
| 358 | bar.finish("way(s)"); |
| 359 | // Nothing reads the ways spill after this: the relations below reach their members through |
| 360 | // `members`, which is why that table is kept at all. The file backend's `.tmp` is removed |
| 361 | // (after its handle closes); the anon backend's segments unmap with the last `Arc`. |
| 362 | drop(blocks); |
| 363 | let _ = std::fs::remove_file(ways_path); |
| 364 | |
| 365 | Ok(()) |
| 366 | } |