Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / maps / mamaps_build / src / tiler_part1.rs
tiler_part1.rs755 lines · 36.9 KiBRaw
| 1 | /// Tile every feature and write the archive. |
| 2 | /// Tile every feature in `store` into a `.mamaps` archive. |
| 3 | /// |
| 4 | /// The store is read **once per zoom**, in order, rather than held in memory for all of them. Fifteen |
| 5 | /// sequential passes over a file cost seconds on any modern disk; holding the features cost 4.9 GB of |
| 6 | /// a measured 10.03 GB California peak. |
| 7 | pub fn build(store: &Store, settings: &Settings) -> Result<(Vec<u8>, Vec<ZoomStats>)> { |
| 8 | adopt_thread_budget(); |
| 9 | let mut writer = writer_for(store, settings)?; |
| 10 | // Tests share the zoom loop but report no phase: the timer is dropped without `finish`, |
| 11 | // so no `TIMING` line ever reaches test output. |
| 12 | let mut timer = crate::timing::PhaseTimer::start("tiles"); |
| 13 | let per_zoom = tile_zooms(store, settings, &mut writer, &mut timer)?; |
| 14 | let bytes = writer.finish()?; |
| 15 | Ok((bytes, per_zoom)) |
| 16 | } |
| 17 | |
| 18 | /// Tile every feature in `store` straight into the archive at `out`, without ever holding the |
| 19 | /// archive in memory. |
| 20 | /// |
| 21 | /// `build` above returns the whole archive as a `Vec<u8>` -- fine for tests, fatal for a planet: |
| 22 | /// the data section alone is tens of GB, and holding it beside the merge's own peak is what OOMs |
| 23 | /// a box with ~50 GB of commit headroom right after z14 merges. This runs the identical zoom loop |
| 24 | /// ([`tile_zooms`]) and finishes through [`StreamWriter::finish_to_path`], so the only thing ever |
| 25 | /// held is the prefix (the index, small next to the bodies). Same tiles, same order, same bytes: |
| 26 | /// the writer appends identically either way, and `finish_to_path` assembles the same |
| 27 | /// header/dictionary/root/leaves/data layout as `finish`. |
| 28 | pub fn build_to_path( |
| 29 | store: &Store, |
| 30 | settings: &Settings, |
| 31 | out: &std::path::Path, |
| 32 | timer: &mut crate::timing::PhaseTimer, |
| 33 | ) -> Result<Vec<ZoomStats>> { |
| 34 | adopt_thread_budget(); |
| 35 | let mut writer = writer_for(store, settings)?; |
| 36 | let per_zoom = tile_zooms(store, settings, &mut writer, timer)?; |
| 37 | writer.finish_to_path(out)?; |
| 38 | Ok(per_zoom) |
| 39 | } |
| 40 | |
| 41 | /// The [`StreamWriter`] for a build: zoom range, build id, compression, and the body scratch |
| 42 | /// beside the output. |
| 43 | /// |
| 44 | /// The scratch placement matters: the writer spills the data section (tens of GB on a planet) |
| 45 | /// through a temp file, and the default is the system temp dir -- routinely a small system |
| 46 | /// volume. Beside the output it shares the volume the operator already sized for the build |
| 47 | /// (feature spill, tile chunks, archive), and it is removed on drop like every other scratch |
| 48 | /// file. Path only, never bytes: the archive is identical wherever the scratch lives. |
| 49 | fn writer_for(store: &Store, settings: &Settings) -> Result<StreamWriter> { |
| 50 | let bbox = store.bbox(); |
| 51 | StreamWriter::new(Options { |
| 52 | min_zoom: 0, |
| 53 | max_zoom: crate::DEFAULT_MAX_ZOOM, |
| 54 | build_id: settings.build_id, |
| 55 | compress: true, |
| 56 | // Stage C runs on every tile below, so the claim is true. It is what lets the renderer |
| 57 | // skip its repair pass — and the renderer still keeps that pass, gated, because a claim is |
| 58 | // only as good as the generator making it. |
| 59 | rings_validated: true, |
| 60 | min_lon_e7: bbox.0, |
| 61 | min_lat_e7: bbox.1, |
| 62 | max_lon_e7: bbox.2, |
| 63 | max_lat_e7: bbox.3, |
| 64 | spill_dir: settings.scratch.parent().map(std::path::Path::to_path_buf), |
| 65 | ..Options::default() |
| 66 | }) |
| 67 | } |
| 68 | |
| 69 | /// The zoom loop both builders share: map, merge, encode and append z0..=z14 through `writer`. |
| 70 | /// |
| 71 | /// Extracted whole from `build` so the two finishes cannot diverge: the per-zoom stats, the |
| 72 | /// progress bars, the `check_books` gate and the append order are identical, and only the final |
| 73 | /// assembly differs (in-memory vs streaming). |
| 74 | fn tile_zooms( |
| 75 | store: &Store, |
| 76 | settings: &Settings, |
| 77 | writer: &mut StreamWriter, |
| 78 | timer: &mut crate::timing::PhaseTimer, |
| 79 | ) -> Result<Vec<ZoomStats>> { |
| 80 | |
| 81 | let mut per_zoom = Vec::new(); |
| 82 | // The tile-chunk spill's backend, decided once from the feature count: z14 holds the most |
| 83 | // clipped copies at once (the 53 GB north-america case that motivated the spill), so sizing |
| 84 | // for the whole store is the safe side. Per-zoom files share one scratch path -- each zoom's |
| 85 | // spill truncates it on create and removes it on drop, so peak disk is still the largest |
| 86 | // single zoom. |
| 87 | let chunk_plan = plan_chunk_spill(store, &settings.scratch); |
| 88 | // The operator's override wins over the gate: `force_chunk_spill_file` (from |
| 89 | // `MAPS_ANON_SPILL`, unset or non-`1`) stages through the scratch file even when the gate |
| 90 | // picks anon. Same chunks, same bytes, no commit charge for the merge to trip over. |
| 91 | let chunk_plan = if settings.force_chunk_spill_file |
| 92 | && chunk_plan == osm_ingest::mem::SpillPlan::Anon |
| 93 | { |
| 94 | eprintln!( |
| 95 | " [tiler] chunk spill -> {} (file backend: MAPS_ANON_SPILL)", |
| 96 | settings.scratch.display(), |
| 97 | ); |
| 98 | osm_ingest::mem::SpillPlan::File |
| 99 | } else { |
| 100 | chunk_plan |
| 101 | }; |
| 102 | for z in 0..=crate::DEFAULT_MAX_ZOOM { |
| 103 | let mut stats = ZoomStats { zoom: z, ..ZoomStats::default() }; |
| 104 | let tolerance = |
| 105 | simplify::tolerance_for(z, crate::DEFAULT_MAX_ZOOM, DEFAULT_SIMPLIFICATION); |
| 106 | let buffer = geom::buffer_for(EXTENT); |
| 107 | |
| 108 | // Per zoom, so peak scratch is the largest single zoom rather than the sum, and so a build |
| 109 | // that dies at z14 leaves one zoom behind rather than fifteen. Anonymous |
| 110 | // pagefile-backed memory (no file) when commit allows, else the scratch file; the merge |
| 111 | // reads through the same ChunkReader either way. |
| 112 | let spill = ChunkSpill::create_planned(&settings.scratch, chunk_plan)?; |
| 113 | // Per-zoom `map`: repeat visits merge into one total at `finish`. |
| 114 | timer.switch("map"); |
| 115 | let mapped = std::time::Instant::now(); |
| 116 | let (chunks, tally) = map_zoom(store, settings, z, tolerance, buffer, &spill)?; |
| 117 | stats.map_ms = mapped.elapsed().as_millis() as u64; |
| 118 | stats.features = tally.features; |
| 119 | stats.points = tally.points; |
| 120 | stats.dropped = tally.dropped; |
| 121 | |
| 122 | // Ascending by tile id because the merge makes it so, not because a sort step was |
| 123 | // remembered. A `BTreeMap` per chunk and a heap across them is the same guarantee the |
| 124 | // single-threaded `BTreeMap` gave; the maps now live on disk and the guarantee does not |
| 125 | // change, because a chunk's bytes are written in its key order and read back in file order. |
| 126 | // |
| 127 | // Range-parallel merge when the zoom repays planning: one worker k-way merges each |
| 128 | // cost-balanced tile range (see `tiler_part3::merge_parallel`), drained in order by the |
| 129 | // same consume loop below — sequence-identical to serial, so batches, prune and append |
| 130 | // are untouched. Small zooms stay serial: planning costs more than it saves there. So do |
| 131 | // z0–z3, whose tile spans (1–64) don't divide by the 256 cost buckets — the bucket table |
| 132 | // can't invert those edges exactly (see `parallel_merge_supported`). |
| 133 | // |
| 134 | // The choice is `merge_gate` below, hardcoded: no environment override. |
| 135 | // Operator control arrives through `--threads`/`MAPS_THREADS` (which sizes the |
| 136 | // worker count) exactly like every other parallel stage in this tree. |
| 137 | let merge_parallel = merge_gate(&chunks, z); |
| 138 | if merge_parallel { |
| 139 | let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS); |
| 140 | // One worker owns the whole tile space on a one-thread box, which is |
| 141 | // the serial sequence by construction — correctness never depends on |
| 142 | // the count, only speed does. |
| 143 | let merge_workers = merge_workers.max(1); |
| 144 | // Timed as its own subphase: the planning scan is a serial |
| 145 | // skip-walk over every chunk, and at z14 it is large enough to |
| 146 | // matter against the merge it parallelises. |
| 147 | timer.switch("merge-plan"); |
| 148 | let planning = std::time::Instant::now(); |
| 149 | let plan = crate::tiler::plan_ranges(&chunks, &spill, z, merge_workers)?; |
| 150 | stats.merge_ms += planning.elapsed().as_millis() as u64; |
| 151 | // One line per zoom on the parallel path: per-range cost estimates |
| 152 | // from the planning histogram. The coordinator drains ranges in |
| 153 | // order, so the slowest range sets the merge wall — a lopsided |
| 154 | // split here names the balancer, not the workers, as the limit. |
| 155 | // `hot` is the costliest single tile: ranges assign whole tiles, |
| 156 | // so the wall cannot go below it however the ranges split. |
| 157 | eprintln!( |
| 158 | " [merge] z{z}: {} range(s), cost {:?}, hot tile {} at {}, entries {}", |
| 159 | merge_workers, |
| 160 | plan.range_cost, |
| 161 | plan.hot_tile, |
| 162 | plan.hot_cost, |
| 163 | plan.remaining |
| 164 | .iter() |
| 165 | .map(|row| row.iter().sum::<u64>()) |
| 166 | .sum::<u64>(), |
| 167 | ); |
| 168 | std::thread::scope(|s| -> Result<()> { |
| 169 | let mut receivers = Vec::with_capacity(merge_workers); |
| 170 | // Shared refs are `Copy`: each spawned closure gets its own |
| 171 | // copy rather than moving `chunks`/`spill` on first use. |
| 172 | let chunks_ref = &chunks; |
| 173 | let spill_ref = &spill; |
| 174 | for r in 0..merge_workers { |
| 175 | let (tx, rx) = |
| 176 | std::sync::mpsc::sync_channel(crate::tiler::RANGE_QUEUE_BOUND); |
| 177 | receivers.push(rx); |
| 178 | let range_plan = &plan; |
| 179 | s.spawn(move || { |
| 180 | crate::tiler::merge_range_into( |
| 181 | chunks_ref, |
| 182 | spill_ref, |
| 183 | range_plan, |
| 184 | r, |
| 185 | tx, |
| 186 | ); |
| 187 | }); |
| 188 | } |
| 189 | let mut stream = |
| 190 | crate::tiler::MergeStream::Parallel(crate::tiler::ParallelMerge::new( |
| 191 | receivers, |
| 192 | )); |
| 193 | consume_merged( |
| 194 | &mut stream, |
| 195 | &mut stats, |
| 196 | z, |
| 197 | timer, |
| 198 | &settings.dem, |
| 199 | store.conventions(), |
| 200 | &settings.region_links, |
| 201 | writer, |
| 202 | )?; |
| 203 | Ok(()) |
| 204 | })?; |
| 205 | } else { |
| 206 | let mut stream = crate::tiler::MergeStream::Serial(merge(&chunks, &spill)); |
| 207 | consume_merged( |
| 208 | &mut stream, |
| 209 | &mut stats, |
| 210 | z, |
| 211 | timer, |
| 212 | &settings.dem, |
| 213 | store.conventions(), |
| 214 | &settings.region_links, |
| 215 | writer, |
| 216 | )?; |
| 217 | } |
| 218 | // Reserved, written, on disk and read back must agree. A chunk that quietly lost entries |
| 219 | // would produce an archive with holes in it and nothing downstream could tell. |
| 220 | spill.check_books()?; |
| 221 | per_zoom.push(stats); |
| 222 | } |
| 223 | |
| 224 | Ok(per_zoom) |
| 225 | } |
| 226 | |
| 227 | /// The entry gate for the range-parallel merge: big supported zoom on a |
| 228 | /// multi-thread box. |
| 229 | /// |
| 230 | /// Split out so the call site reads as intent rather than inline conditions. |
| 231 | /// z0–z3 stay serial however threaded: they can't invert their bucket edges |
| 232 | /// exactly, so they have one path and no divergence to compare. |
| 233 | fn merge_gate(chunks: &[ChunkRef], z: u8) -> bool { |
| 234 | let total_entries: u64 = chunks.iter().map(|c| c.entries).sum(); |
| 235 | let merge_workers = par::threads().min(crate::tiler::PARALLEL_MERGE_MAX_WORKERS); |
| 236 | total_entries >= crate::tiler::PARALLEL_MERGE_MIN_ENTRIES |
| 237 | && merge_workers > 1 |
| 238 | && crate::tiler::parallel_merge_supported(z) |
| 239 | } |
| 240 | |
| 241 | /// Merge → encode → prune → append for one zoom, over any tile-ordered merge |
| 242 | /// iterator. |
| 243 | /// |
| 244 | /// Extracted whole from the zoom loop so serial and range-parallel merges share |
| 245 | /// it: batches are contiguous pulls in merge order, `encode_batch` preserves |
| 246 | /// tile order, and prune/append see the identical sequence either way — which |
| 247 | /// is why the archive does not move between the two paths. |
| 248 | #[allow(clippy::too_many_arguments)] |
| 249 | fn consume_merged( |
| 250 | merged: &mut impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>, |
| 251 | stats: &mut ZoomStats, |
| 252 | z: u8, |
| 253 | timer: &mut crate::timing::PhaseTimer, |
| 254 | dem: &crate::dem::Dem, |
| 255 | conventions: &crate::schema::boundaries::Conventions, |
| 256 | region_links: &std::collections::HashMap<u64, u64>, |
| 257 | writer: &mut tilecodec::mamaps::write::StreamWriter, |
| 258 | ) -> Result<()> { |
| 259 | // Merge, encode and append have no total to count against -- the tile count is only known once |
| 260 | // the merge has produced it -- so the merge bar counts tiles merged and the encode line below |
| 261 | // counts tiles written. |
| 262 | let zoom_start = std::time::Instant::now(); |
| 263 | let mut merged_tiles = 0usize; |
| 264 | let mut merge_shown = 0usize; |
| 265 | let mut written = 0usize; |
| 266 | let mut shown = 0usize; |
| 267 | loop { |
| 268 | // Cost-batched rather than count-batched: z14 has tiles whose merged geometry is tens |
| 269 | // of MB (a dense city tile's whole layer set) beside rural tiles worth bytes. A |
| 270 | // fixed `batch_len()` of those holds ~GB of merged tiles plus their encoded copies |
| 271 | // before the writer takes them -- on top of the merge's own peak, on a box with |
| 272 | // ~50 GB of commit headroom, which is where `Map z14 [100%]` went followed by a |
| 273 | // 512 KiB allocation failure. Capped at `MERGE_BATCH_BYTES` of merged cost, so a |
| 274 | // heavy tile still gets its own batch (a minimum of one batch per pull) and common |
| 275 | // zooms -- whose batches never reach the cap -- take the same count they always |
| 276 | // did. Order is untouched: batches are contiguous pulls of the merge in order, and |
| 277 | // `encode_batch` preserves tile order, so the archive does not move. |
| 278 | // |
| 279 | // Batched rather than a task per tile: one tile's stage C and encode is tens of |
| 280 | // microseconds and rayon's stealing costs more than that. Batched rather than a whole |
| 281 | // zoom at once because the batch is what bounds the encoded bytes held before the |
| 282 | // writer takes them. |
| 283 | // |
| 284 | // The merge is timed around `collect` because that is where it happens: `merge` returns |
| 285 | // a lazy iterator, so pulling a batch out of it is the k-way merge doing its work. |
| 286 | // Per-zoom `merge`: repeat visits merge into one total at `finish`. |
| 287 | timer.switch("merge"); |
| 288 | let merging = std::time::Instant::now(); |
| 289 | // `collect` into a `Result`, because a truncated scratch file must fail the build rather |
| 290 | // than end the zoom early and publish a short archive. |
| 291 | let batch: Vec<(u64, Vec<ChunkEntry>)> = |
| 292 | merge_batch(&mut *merged, par::batch_len())?; |
| 293 | stats.merge_ms += merging.elapsed().as_millis() as u64; |
| 294 | if batch.is_empty() { |
| 295 | break; |
| 296 | } |
| 297 | // The merge did its work when `collect` returned: count the tiles now, so the bar moves |
| 298 | // during the serial merge rather than only when the parallel encode drains. |
| 299 | merged_tiles += batch.len(); |
| 300 | if merged_tiles - merge_shown >= 25_000 { |
| 301 | merge_shown = merged_tiles; |
| 302 | eprint!( |
| 303 | "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ", |
| 304 | format!("Merge z{z}"), |
| 305 | tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), |
| 306 | ); |
| 307 | let _ = std::io::Write::flush(&mut std::io::stderr()); |
| 308 | } |
| 309 | // Per-zoom `encode`: repeat visits merge into one total at `finish`. |
| 310 | timer.switch("encode"); |
| 311 | let encoding = std::time::Instant::now(); |
| 312 | let mut done = encode_batch(batch, dem, conventions, region_links)?; |
| 313 | stats.encode_ms += encoding.elapsed().as_millis() as u64; |
| 314 | // Phase B: prune barren subtrees. A tile whose four children all came back |
| 315 | // empty (`None` — genuinely featureless, or full-bleed water background) is |
| 316 | // itself the end of the tree: drop the children and let the reader stop at |
| 317 | // the parent (overzoom). Applies recursively up the pyramid, so a z13 tile |
| 318 | // whose z14 children are all ocean ends the tree at z13. Only above z0 (the |
| 319 | // world tile is never pruned) and only when all four children of a parent |
| 320 | // are present-and-empty in this batch — never across batch boundaries, so |
| 321 | // the archive stays independent of batching and thread count. |
| 322 | prune_barren_subtree(z, &mut done); |
| 323 | // Per-zoom `append`: repeat visits merge into one total at `finish`. |
| 324 | timer.switch("append"); |
| 325 | let appending = std::time::Instant::now(); |
| 326 | for (id, encoded, rings, lines) in done { |
| 327 | stats.rings.add(rings); |
| 328 | stats.lines.add(lines); |
| 329 | let encoded = encoded; |
| 330 | let Some((stored, raw_len, hash)) = encoded else { continue }; |
| 331 | // Uncompressed, as this column has always meant. |
| 332 | stats.bytes += raw_len as u64; |
| 333 | stats.tiles += 1; |
| 334 | writer.append_stored_with_hash(id, &stored, hash)?; |
| 335 | written += 1; |
| 336 | // Every 25k tiles: often enough to look alive on a continent, rare enough that the |
| 337 | // write itself is never the cost. |
| 338 | if written - shown >= 25_000 { |
| 339 | shown = written; |
| 340 | eprint!( |
| 341 | "\r{:<28} [{written:>10} tile(s)] {} elapsed ", |
| 342 | format!("Encode z{z}"), |
| 343 | tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), |
| 344 | ); |
| 345 | let _ = std::io::Write::flush(&mut std::io::stderr()); |
| 346 | } |
| 347 | } |
| 348 | stats.append_ms += appending.elapsed().as_millis() as u64; |
| 349 | } |
| 350 | if merged_tiles > 0 { |
| 351 | eprintln!( |
| 352 | "\r{:<28} [{merged_tiles:>10} tile(s)] {} elapsed ", |
| 353 | format!("Merge z{z}"), |
| 354 | tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), |
| 355 | ); |
| 356 | } |
| 357 | if written > 0 { |
| 358 | eprintln!( |
| 359 | "\r{:<28} [{written:>10} tile(s)] {} elapsed ", |
| 360 | format!("Encode z{z}"), |
| 361 | tile_build::progress::hms(zoom_start.elapsed().as_secs_f64()), |
| 362 | ); |
| 363 | } |
| 364 | Ok(()) |
| 365 | } |
| 366 | |
| 367 | /// One merge pull, capped by merged-geometry cost rather than by tile count. |
| 368 | /// |
| 369 | /// Pulls up to `max_tiles` from the merge, stopping early once the accumulated `tile_cost` -- |
| 370 | /// features plus coordinates, the same proxy the encode pass balances tasks by -- reaches |
| 371 | /// [`MERGE_BATCH_BYTES`]. Always pulls at least one tile, so a tile heavier than the cap on its |
| 372 | /// own still makes progress. The pulled prefix is contiguous merge order, so feeding it to |
| 373 | /// `encode_batch` (which preserves tile order) keeps the archive byte-identical: the only |
| 374 | /// change is how many tiles one batch holds. |
| 375 | /// |
| 376 | /// Contiguity is also what [`prune_barren_subtree`] relies on: four siblings of one parent |
| 377 | /// occupy consecutive tile ids, so a parent's whole child set is either inside one batch or |
| 378 | /// split across a batch boundary — and only the first case prunes, which keeps the archive |
| 379 | /// independent of where the batcher cut. |
| 380 | fn merge_batch( |
| 381 | merged: &mut impl Iterator<Item = Result<(u64, Vec<ChunkEntry>)>>, |
| 382 | max_tiles: usize, |
| 383 | ) -> Result<Vec<(u64, Vec<ChunkEntry>)>> { |
| 384 | let mut batch: Vec<(u64, Vec<ChunkEntry>)> = Vec::new(); |
| 385 | let mut cost: u64 = 0; |
| 386 | for tile in merged.by_ref().take(max_tiles) { |
| 387 | let (id, layers) = tile?; |
| 388 | cost += tile_cost(&layers); |
| 389 | batch.push((id, layers)); |
| 390 | // Checked after pushing, so the batch is never empty and a heavy tile closes its own |
| 391 | // batch -- the same shape as `partition_by_cost`'s grouping, for the same reason. |
| 392 | if cost >= MERGE_BATCH_BYTES { |
| 393 | break; |
| 394 | } |
| 395 | } |
| 396 | Ok(batch) |
| 397 | } |
| 398 | |
| 399 | /// Prune barren subtrees within one encoded batch: drop the four empty children of a |
| 400 | /// tile whose whole child set came back `None`. |
| 401 | /// |
| 402 | /// A `None` child is a tile with nothing drawable — genuinely featureless, or full-bleed |
| 403 | /// water background (Phase B). The reader's miss path already overzooms: a missing tile |
| 404 | /// falls back to its parent, whose background (or whose own body) shows through. So four |
| 405 | /// empty siblings carry no information their parent does not, and storing them buys index |
| 406 | /// entries, leaf span and fetches for zero pixels. |
| 407 | /// |
| 408 | /// The conditions are deliberately strict, because a wrong prune deletes drawable map: |
| 409 | /// |
| 410 | /// * `z == 0` never prunes: the world tile has no parent to overzoom to. |
| 411 | /// * All four children of a parent must be present **in this batch** and all `None`. |
| 412 | /// A parent split across a batch boundary keeps its children — the archive must not |
| 413 | /// depend on where the cost-batcher cut, and a partial set cannot prove barrenness. |
| 414 | /// * Only `None` children prune. A stored child (even a tiny one) means drawable content. |
| 415 | /// * The parent itself is untouched: it was merged and encoded in its own zoom pass (zooms |
| 416 | /// tile independently), so pruning children never orphans a stored parent. |
| 417 | /// |
| 418 | /// Recursion across zooms falls out of the zoom loop: a z13 tile whose z14 children were |
| 419 | /// all pruned is itself absent-or-water, so when z13 encodes, *its* parent sees four empty |
| 420 | /// children and prunes again — the tree ends where the content does. |
| 421 | /// |
| 422 | /// Runs on the serial append thread over the encoded batch (not in the parallel encode |
| 423 | /// workers): it inspects batch adjacency, which only the ordered batch has. Pure function |
| 424 | /// of the batch's `(id, Option)` pairs, so thread count and chunk boundaries cannot move it. |
| 425 | fn prune_barren_subtree(z: u8, done: &mut Vec<Encoded>) { |
| 426 | if z == 0 || done.len() < 4 { |
| 427 | return; |
| 428 | } |
| 429 | // Index by tile id for sibling lookup. The batch is ascending by id (merge order |
| 430 | // through `encode_batch`'s positional collect), so positions are found by search |
| 431 | // rather than assumed adjacent: siblings are consecutive ids but not necessarily |
| 432 | // consecutive positions (a stored neighbour may sit between them — which itself |
| 433 | // vetoes the prune, correctly). |
| 434 | let mut drop_ids: std::collections::BTreeSet<u64> = std::collections::BTreeSet::new(); |
| 435 | let mut at: std::collections::HashMap<u64, usize> = std::collections::HashMap::new(); |
| 436 | for (index, (id, _, _, _)) in done.iter().enumerate() { |
| 437 | at.insert(*id, index); |
| 438 | } |
| 439 | for (index, (id, encoded, _, _)) in done.iter().enumerate() { |
| 440 | let _ = index; |
| 441 | if encoded.is_some() { |
| 442 | continue; |
| 443 | } |
| 444 | let (tz, tx, ty) = tilecodec::pmtiles::tile_zxy(*id); |
| 445 | if tz != z { |
| 446 | continue; |
| 447 | } |
| 448 | // Only the top-left child starts the check, so each parent is considered once. |
| 449 | if tx % 2 != 0 || ty % 2 != 0 { |
| 450 | continue; |
| 451 | } |
| 452 | let (px, py) = (tx / 2, ty / 2); |
| 453 | let mut siblings: Vec<u64> = Vec::with_capacity(4); |
| 454 | for (dx, dy) in [(0u64, 0u64), (1, 0), (0, 1), (1, 1)] { |
| 455 | siblings.push(tilecodec::pmtiles::tile_id(z, px * 2 + dx, py * 2 + dy)); |
| 456 | } |
| 457 | // All four present in this batch and all empty: the parent covers them. |
| 458 | let all_empty = siblings.iter().all(|sib| { |
| 459 | at.get(sib).is_some_and(|&i| done[i].1.is_none()) |
| 460 | }); |
| 461 | if all_empty { |
| 462 | for sib in siblings { |
| 463 | drop_ids.insert(sib); |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | if !drop_ids.is_empty() { |
| 468 | done.retain(|(id, _, _, _)| !drop_ids.contains(id)); |
| 469 | } |
| 470 | } |
| 471 | |
| 472 | /// Cap on one merge pull's merged-geometry cost, in `tile_cost` units (features + coordinates). |
| 473 | /// |
| 474 | /// 8 M units is ~64 MB of merged tile geometry per batch at typical z14 density -- small against |
| 475 | /// the box, large against the pool (still hundreds of tiles per batch on common zooms, so the |
| 476 | /// encode pass stays fed). The failure this bounds held ~GB: `batch_len()` tiles at 64 threads |
| 477 | /// is 4096 tiles, and a planet z14 batch of those carries dense-city tiles tens of MB each. |
| 478 | const MERGE_BATCH_BYTES: u64 = 8 << 20; |
| 479 | |
| 480 | /// Which backend one zoom's tile-chunk spill stages in. |
| 481 | /// |
| 482 | /// The chunk spill holds clipped copies -- one record per (feature, tile) pair -- so its size |
| 483 | /// scales with the store's feature count times the tiling fan-out, not with anything known |
| 484 | /// exactly up front. The estimate is `features x 512 B`: a clipped copy carries the feature's |
| 485 | /// packed body (tens of bytes) plus its share of parts/coords, and z14's fan-out dominates. |
| 486 | /// Over-estimating files a zoom that would have fit anon; under-estimating pages it. Files are |
| 487 | /// the safe side -- same chunks, removed on drop -- so the constant leans that way. |
| 488 | /// |
| 489 | /// Unknown limits (or a small store under 1 M features): the historical anon path, no behaviour |
| 490 | /// change. |
| 491 | fn plan_chunk_spill(store: &Store, scratch: &std::path::Path) -> osm_ingest::mem::SpillPlan { |
| 492 | const CHUNK_BYTES_PER_FEATURE: u64 = 512; |
| 493 | const SMALL_STORE_FEATURES: u64 = 1_000_000; |
| 494 | if store.len() < SMALL_STORE_FEATURES { |
| 495 | return osm_ingest::mem::SpillPlan::Anon; |
| 496 | } |
| 497 | let mut budget = osm_ingest::mem::StageBudget::default(); |
| 498 | // Reuse the anon-commit field for the chunk estimate: it is the number `decide` compares |
| 499 | // against the commit allowance, and the chunk spill is the only anon charge this phase adds |
| 500 | // (the feature spill is already staged and counted separately). |
| 501 | budget.ways_spill_bytes = store.len().saturating_mul(CHUNK_BYTES_PER_FEATURE); |
| 502 | match osm_ingest::mem::SpillPlan::decide(&budget, scratch, "tiler chunk spill") { |
| 503 | Ok(plan) => { |
| 504 | if plan != osm_ingest::mem::SpillPlan::Anon { |
| 505 | eprintln!( |
| 506 | " [tiler] chunk spill -> {} (file backend: commit budget)", |
| 507 | scratch.display(), |
| 508 | ); |
| 509 | } |
| 510 | plan |
| 511 | } |
| 512 | Err(e) => { |
| 513 | // A zoom that fits neither backend is not a hard failure here: later zooms are |
| 514 | // smaller, and each zoom re-creates the spill. Warn and take files -- the operator |
| 515 | // sees the message and the build still has a chance. |
| 516 | eprintln!("WARN: {e}; continuing with file staging"); |
| 517 | osm_ingest::mem::SpillPlan::File |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | /// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps and |
| 523 | /// spilled to `spill` as each is finished. |
| 524 | /// |
| 525 | /// Returns the chunks **in read order**, which is the only order the reduce may use them in. |
| 526 | /// |
| 527 | /// The reader gets a thread of its own rather than a task on the pool, and that is not a |
| 528 | /// preference. A producer that blocks on a full channel from inside the pool it feeds deadlocks when |
| 529 | /// the pool has one thread: the single worker *is* the producer, so nothing can drain what it is |
| 530 | /// waiting to write. Off the pool, one thread is merely slow — which matters, because one thread is |
| 531 | /// a configuration this has to stay byte-identical at. |
| 532 | fn map_zoom( |
| 533 | store: &Store, |
| 534 | settings: &Settings, |
| 535 | z: u8, |
| 536 | tolerance: f64, |
| 537 | buffer: f64, |
| 538 | spill: &ChunkSpill, |
| 539 | ) -> Result<(Vec<ChunkRef>, Tally)> { |
| 540 | // The full budget, **not** minus the reader's prefetch lanes. Subtracting them was tried, on the |
| 541 | // reasoning that 64 workers plus 16 lanes plus a reader is 81 runnable threads on 64 CPUs. It |
| 542 | // fixed us-west (151.9 s to 94.4 s) and cost north-america more than it saved (766.9 s to |
| 543 | // 900.4 s), because the premise is only true when the lanes are actually running: on |
| 544 | // north-america the workers are the ones blocked, waiting on a channel the reader cannot fill |
| 545 | // fast enough, so the lanes were competing with nothing and the subtraction just removed a |
| 546 | // quarter of the clipping. z14's map went 138.7 s to 170.0 s, almost exactly the ratio. |
| 547 | // |
| 548 | // Which of those two regimes a build is in is what `crate::store::PREFETCH_LANES` has to be set |
| 549 | // for, and it is not knowable from the thread count. |
| 550 | let workers = par::threads().max(1); |
| 551 | // Bounded, because this is the one place the parallel tiler holds features the sequential one |
| 552 | // did not: `2 * threads` chunks of about `chunk_vertices()` vertices, and no more however far |
| 553 | // ahead of the workers the reader gets. |
| 554 | let (send, receive) = std::sync::mpsc::sync_channel::<(usize, Vec<Feature>)>(workers * 2); |
| 555 | let receive = Mutex::new(receive); |
| 556 | let done: Mutex<Vec<(usize, ChunkRef, Tally)>> = Mutex::new(Vec::new()); |
| 557 | let failed = std::sync::atomic::AtomicBool::new(false); |
| 558 | |
| 559 | std::thread::scope(|scope| -> Result<()> { |
| 560 | // TEMP-PROFILE: reader wall (feed rate). The reader thread returns |
| 561 | // its wall clock alongside its result; compared against the zoom's |
| 562 | // map wall it answers feed-bound vs worker-bound. Removed with the |
| 563 | // probes. |
| 564 | let reader_start = std::time::Instant::now(); |
| 565 | let reader = std::thread::Builder::new() |
| 566 | .name("mamaps-read".to_string()) |
| 567 | .spawn_scoped(scope, move || { |
| 568 | let r = read_chunks(store, z, send); |
| 569 | (r, reader_start.elapsed()) |
| 570 | }) |
| 571 | .map_err(|e| tile_build::proto::Error(format!("cannot start the store reader: {e}")))?; |
| 572 | |
| 573 | // One worker runs on this thread whatever happens, so a machine that will not give us |
| 574 | // threads is slow rather than a build hung on a channel nobody is draining. |
| 575 | let mut spawned = Vec::new(); |
| 576 | for i in 1..workers { |
| 577 | let worker = std::thread::Builder::new() |
| 578 | .name(format!("mamaps-tile-{i}")) |
| 579 | .stack_size(WORKER_STACK) |
| 580 | .spawn_scoped(scope, || { |
| 581 | tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms) |
| 582 | }); |
| 583 | match worker { |
| 584 | Ok(handle) => spawned.push(handle), |
| 585 | Err(e) => { |
| 586 | eprintln!("WARN: cannot start tiling thread {i} ({e}); continuing without"); |
| 587 | break; |
| 588 | } |
| 589 | } |
| 590 | } |
| 591 | tile_chunks(&receive, &done, &failed, spill, z, tolerance, buffer, &settings.country_zooms); |
| 592 | for handle in spawned { |
| 593 | handle.join().map_err(|_| { |
| 594 | tile_build::proto::Error("a tiling thread panicked".to_string()) |
| 595 | })?; |
| 596 | } |
| 597 | let (reader_result, reader_wall) = reader.join().map_err(|_| { |
| 598 | tile_build::proto::Error("the store reader thread panicked".to_string()) |
| 599 | })?; |
| 600 | // TEMP-PROFILE: stash the reader wall where the tally fold prints |
| 601 | // it. Removed with the probes. |
| 602 | crate::tiler::stash_reader_wall(z, reader_wall); |
| 603 | reader_result |
| 604 | })?; |
| 605 | |
| 606 | if failed.load(Ordering::Relaxed) { |
| 607 | // Refused rather than published. A skipped chunk is a handful of features missing from a |
| 608 | // handful of tiles: no error on device, no visibly broken tile, just an archive that is |
| 609 | // quietly not the one the report describes. |
| 610 | return err(format!("a chunk of z{z} could not be tiled; see the message above")); |
| 611 | } |
| 612 | |
| 613 | let mut chunks = done.into_inner().expect("the chunk list outlives its workers"); |
| 614 | // **The reduce order.** By the index a chunk was read at, never by the order it finished in, and |
| 615 | // never by where in the scratch file it happened to land. This one line is what keeps the |
| 616 | // archive independent of the thread count. |
| 617 | chunks.sort_by_key(|(index, _, _)| *index); |
| 618 | let mut tally = Tally::default(); |
| 619 | for (_, _, chunk_tally) in &chunks { |
| 620 | tally.add(*chunk_tally); |
| 621 | } |
| 622 | // TEMP-PROFILE: per-stage map walls, summed across chunks (CPU time, so |
| 623 | // the sum exceeds wall on 64 threads — ratios, not walls, are the read), |
| 624 | // plus the reader thread's own wall (feed rate) and the map wall implied |
| 625 | // by the caller. `reader_ms` vs the zoom's `map_ms` answers feed-bound |
| 626 | // vs worker-bound: a reader wall near the map wall means workers starved. |
| 627 | // Removed with the probes. |
| 628 | eprintln!( |
| 629 | " [mapprofile] z{z}: project={:.1}s annotate={:.1}s filter={:.1}s subdiv={:.1}s reader={:.1}s", |
| 630 | tally.profile.project.as_secs_f64(), |
| 631 | tally.profile.annotate.as_secs_f64(), |
| 632 | tally.profile.filter.as_secs_f64(), |
| 633 | tally.profile.subdiv.as_secs_f64(), |
| 634 | crate::tiler::take_reader_wall().as_secs_f64() |
| 635 | ); |
| 636 | Ok((chunks.into_iter().map(|(_, at, _)| at).collect(), tally)) |
| 637 | } |
| 638 | |
| 639 | /// Cut the store into chunks of roughly [`chunk_vertices`] input vertices and send them on. |
| 640 | /// |
| 641 | /// The cut is a function of the feature stream alone — not of the thread count, not of how fast the |
| 642 | /// workers drain — so two runs chunk identically even before the merge makes the boundaries |
| 643 | /// invisible. |
| 644 | /// |
| 645 | /// A feature below the zoom's own floor never arrives: [`crate::store::ZoomReader`] drops it in one |
| 646 | /// of its prefetch lanes. That filter used to be right here, and here it was one thread discarding |
| 647 | /// most of a billion features — see the reader's own docs for what that cost. |
| 648 | |
| 649 | #[cfg(test)] |
| 650 | mod tests_part1 { |
| 651 | use super::*; |
| 652 | |
| 653 | fn empty_entry(id: u64) -> Encoded { |
| 654 | (id, None, crate::rings::Stats::default(), crate::coalesce::Stats::default()) |
| 655 | } |
| 656 | |
| 657 | fn stored_entry(id: u64) -> Encoded { |
| 658 | ( |
| 659 | id, |
| 660 | Some((vec![7u8; 32], 32, tilecodec::mamaps::write::hash64(&[7u8; 32]))), |
| 661 | crate::rings::Stats::default(), |
| 662 | crate::coalesce::Stats::default(), |
| 663 | ) |
| 664 | } |
| 665 | |
| 666 | fn ids_of(done: &[Encoded]) -> Vec<u64> { |
| 667 | done.iter().map(|(id, _, _, _)| *id).collect() |
| 668 | } |
| 669 | |
| 670 | /// **Phase B subtree pruning: four empty siblings end the tree at the parent.** |
| 671 | /// All four children of one z12 parent arrive `None` in one batch: all four are |
| 672 | /// dropped, so the reader stops at the z11 parent (overzoom) instead of fetching |
| 673 | /// four empty bodies. |
| 674 | #[test] |
| 675 | fn four_empty_siblings_are_pruned_to_the_parent() { |
| 676 | use tilecodec::pmtiles::tile_id; |
| 677 | let (px, py) = (1_200u64, 1_500u64); |
| 678 | let z = 12u8; |
| 679 | let mut done = vec![ |
| 680 | empty_entry(tile_id(z, px * 2, py * 2)), |
| 681 | empty_entry(tile_id(z, px * 2 + 1, py * 2)), |
| 682 | empty_entry(tile_id(z, px * 2, py * 2 + 1)), |
| 683 | empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)), |
| 684 | ]; |
| 685 | prune_barren_subtree(z, &mut done); |
| 686 | assert!(done.is_empty(), "all four empty siblings must go: {done:?}"); |
| 687 | } |
| 688 | |
| 689 | /// **A stored sibling vetoes the prune.** One child carries drawable content, so the |
| 690 | /// parent cannot cover the set — dropping the other three would delete the map's |
| 691 | /// answer for their ground (the reader would overzoom a parent that draws coarsely). |
| 692 | #[test] |
| 693 | fn a_stored_sibling_vetoes_the_prune() { |
| 694 | use tilecodec::pmtiles::tile_id; |
| 695 | let (px, py) = (1_200u64, 1_500u64); |
| 696 | let z = 12u8; |
| 697 | let mut done = vec![ |
| 698 | empty_entry(tile_id(z, px * 2, py * 2)), |
| 699 | stored_entry(tile_id(z, px * 2 + 1, py * 2)), |
| 700 | empty_entry(tile_id(z, px * 2, py * 2 + 1)), |
| 701 | empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)), |
| 702 | ]; |
| 703 | prune_barren_subtree(z, &mut done); |
| 704 | assert_eq!(done.len(), 4, "a stored child keeps the whole set"); |
| 705 | } |
| 706 | |
| 707 | /// **A partial set never prunes.** The parent split across a batch boundary keeps its |
| 708 | /// children: the archive must not depend on where the cost-batcher cut, and three |
| 709 | /// empties cannot prove the fourth is barren. |
| 710 | #[test] |
| 711 | fn a_partial_child_set_never_prunes() { |
| 712 | use tilecodec::pmtiles::tile_id; |
| 713 | let (px, py) = (1_200u64, 1_500u64); |
| 714 | let z = 12u8; |
| 715 | let mut done = vec![ |
| 716 | empty_entry(tile_id(z, px * 2, py * 2)), |
| 717 | empty_entry(tile_id(z, px * 2 + 1, py * 2)), |
| 718 | empty_entry(tile_id(z, px * 2, py * 2 + 1)), |
| 719 | ]; |
| 720 | prune_barren_subtree(z, &mut done); |
| 721 | assert_eq!(done.len(), 3, "a split parent keeps its children"); |
| 722 | } |
| 723 | |
| 724 | /// **z0 never prunes.** The world tile has no parent to overzoom to; dropping it |
| 725 | /// would delete the map's coarsest answer. |
| 726 | #[test] |
| 727 | fn the_world_tile_is_never_pruned() { |
| 728 | use tilecodec::pmtiles::tile_id; |
| 729 | let mut done = vec![ |
| 730 | empty_entry(tile_id(0, 0, 0)), |
| 731 | empty_entry(tile_id(0, 1, 0)), |
| 732 | empty_entry(tile_id(0, 0, 1)), |
| 733 | empty_entry(tile_id(0, 1, 1)), |
| 734 | ]; |
| 735 | let before = ids_of(&done); |
| 736 | prune_barren_subtree(0, &mut done); |
| 737 | assert_eq!(ids_of(&done), before, "z0 keeps everything"); |
| 738 | } |
| 739 | |
| 740 | /// **Unrelated tiles are untouched.** A batch of four empties from different parents |
| 741 | /// prunes nothing — the check is per-parent, not per-batch. |
| 742 | #[test] |
| 743 | fn empties_from_different_parents_do_not_prune() { |
| 744 | use tilecodec::pmtiles::tile_id; |
| 745 | let z = 12u8; |
| 746 | let mut done = vec![ |
| 747 | empty_entry(tile_id(z, 0, 0)), |
| 748 | empty_entry(tile_id(z, 100, 100)), |
| 749 | empty_entry(tile_id(z, 200, 200)), |
| 750 | empty_entry(tile_id(z, 300, 300)), |
| 751 | ]; |
| 752 | prune_barren_subtree(z, &mut done); |
| 753 | assert_eq!(done.len(), 4, "no parent has its full set here"); |
| 754 | } |
| 755 | } |