/// The map half of one zoom: every feature in the store, clipped into per-chunk tile maps and /// spilled to `spill` as each is finished. /// /// Returns the chunks **in read order**, which is the only order the reduce may use them in. /// /// The reader gets a thread of its own rather than a task on the pool, and that is not a /// preference. A producer that blocks on a full channel from inside the pool it feeds deadlocks when /// the pool has one thread: the single worker *is* the producer, so nothing can drain what it is /// waiting to write. Off the pool, one thread is merely slow — which matters, because one thread is /// a configuration this has to stay byte-identical at. fn map_zoom( store: &Store, settings: &Settings, z: u8, tolerance: f64, buffer: f64, spill: &ChunkSpill, ) -> Result<(Vec, Tally)> { // The full budget, **not** minus the reader's prefetch lanes. Subtracting them was tried, on the // reasoning that 64 workers plus 16 lanes plus a reader is 81 runnable threads on 64 CPUs. It // fixed us-west (151.9 s to 94.4 s) and cost north-america more than it saved (766.9 s to // 900.4 s), because the premise is only true when the lanes are actually running: on // north-america the workers are the ones blocked, waiting on a channel the reader cannot fill // fast enough, so the lanes were competing with nothing and the subtraction just removed a // quarter of the clipping. z14's map went 138.7 s to 170.0 s, almost exactly the ratio. // // Which of those two regimes a build is in is what `crate::store::PREFETCH_LANES` has to be set // for, and it is not knowable from the thread count. let workers = par::threads().max(1); // Bounded, because this is the one place the parallel tiler holds features the sequential one // did not: `2 * threads` chunks of about `chunk_vertices()` vertices, and no more however far // ahead of the workers the reader gets. let (send, receive) = std::sync::mpsc::sync_channel::<(usize, Vec>)>(workers * 2); let receive = Mutex::new(receive); let done: Mutex> = Mutex::new(Vec::new()); let failed = std::sync::atomic::AtomicBool::new(false); std::thread::scope(|scope| -> Result<()> { // TEMP-PROFILE: reader wall (feed rate). The reader thread returns // its wall clock alongside its result; compared against the zoom's // map wall it answers feed-bound vs worker-bound. Removed with the // probes. let reader_start = std::time::Instant::now(); let reader = std::thread::Builder::new() .name("mamaps-read".to_string()) .spawn_scoped(scope, move || { let r = read_chunks(store, z, send); (r, reader_start.elapsed()) }) .map_err(|e| tile_build::proto::Error(format!("cannot start the store reader: {e}")))?; // One worker runs on this thread whatever happens, so a machine that will not give us // threads is slow rather than a build hung on a channel nobody is draining. let mut spawned = Vec::new(); for i in 1..workers { let worker = std::thread::Builder::new() .name(format!("mamaps-tile-{i}")) .stack_size(WORKER_STACK) .spawn_scoped(scope, || { tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms }) }); match worker { Ok(handle) => spawned.push(handle), Err(e) => { eprintln!("WARN: cannot start tiling thread {i} ({e}); continuing without"); break; } } } tile_chunks(TileChunksCtx { receive: &receive, done: &done, failed: &failed, spill, z, tolerance, buffer, country_zooms: &settings.country_zooms }); for handle in spawned { handle.join().map_err(|_| { tile_build::proto::Error("a tiling thread panicked".to_string()) })?; } let (reader_result, reader_wall) = reader.join().map_err(|_| { tile_build::proto::Error("the store reader thread panicked".to_string()) })?; // TEMP-PROFILE: stash the reader wall where the tally fold prints // it. Removed with the probes. crate::tiler::stash_reader_wall(z, reader_wall); reader_result })?; if failed.load(Ordering::Relaxed) { // Refused rather than published. A skipped chunk is a handful of features missing from a // handful of tiles: no error on device, no visibly broken tile, just an archive that is // quietly not the one the report describes. return err(format!("a chunk of z{z} could not be tiled; see the message above")); } let mut chunks = done.into_inner().expect("the chunk list outlives its workers"); // **The reduce order.** By the index a chunk was read at, never by the order it finished in, and // never by where in the scratch file it happened to land. This one line is what keeps the // archive independent of the thread count. chunks.sort_by_key(|(index, _, _)| *index); let mut tally = Tally::default(); for (_, _, chunk_tally) in &chunks { tally.add(*chunk_tally); } // TEMP-PROFILE: per-stage map walls, summed across chunks (CPU time, so // the sum exceeds wall on 64 threads — ratios, not walls, are the read), // plus the reader thread's own wall (feed rate) and the map wall implied // by the caller. `reader_ms` vs the zoom's `map_ms` answers feed-bound // vs worker-bound: a reader wall near the map wall means workers starved. // Removed with the probes. eprintln!( " [mapprofile] z{z}: project={:.1}s annotate={:.1}s filter={:.1}s subdiv={:.1}s reader={:.1}s", tally.profile.project.as_secs_f64(), tally.profile.annotate.as_secs_f64(), tally.profile.filter.as_secs_f64(), tally.profile.subdiv.as_secs_f64(), crate::tiler::take_reader_wall().as_secs_f64() ); Ok((chunks.into_iter().map(|(_, at, _)| at).collect(), tally)) } /// Cut the store into chunks of roughly [`chunk_vertices`] input vertices and send them on. /// /// The cut is a function of the feature stream alone — not of the thread count, not of how fast the /// workers drain — so two runs chunk identically even before the merge makes the boundaries /// invisible. /// /// A feature below the zoom's own floor never arrives: [`crate::store::ZoomReader`] drops it in one /// of its prefetch lanes. That filter used to be right here, and here it was one thread discarding /// most of a billion features — see the reader's own docs for what that cost. #[cfg(test)] mod tests_part1 { use super::*; fn empty_entry(id: u64) -> Encoded { (id, None, crate::rings::Stats::default(), crate::coalesce::Stats::default()) } fn stored_entry(id: u64) -> Encoded { ( id, Some((vec![7u8; 32], 32, tilecodec::mamaps::write::hash64(&[7u8; 32]))), crate::rings::Stats::default(), crate::coalesce::Stats::default(), ) } fn ids_of(done: &[Encoded]) -> Vec { done.iter().map(|(id, _, _, _)| *id).collect() } /// **Phase B subtree pruning: four empty siblings end the tree at the parent.** /// All four children of one z12 parent arrive `None` in one batch: all four are /// dropped, so the reader stops at the z11 parent (overzoom) instead of fetching /// four empty bodies. #[test] fn four_empty_siblings_are_pruned_to_the_parent() { use tilecodec::pmtiles::tile_id; let (px, py) = (1_200u64, 1_500u64); let z = 12u8; let mut done = vec![ empty_entry(tile_id(z, px * 2, py * 2)), empty_entry(tile_id(z, px * 2 + 1, py * 2)), empty_entry(tile_id(z, px * 2, py * 2 + 1)), empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)), ]; prune_barren_subtree(z, &mut done); assert!(done.is_empty(), "all four empty siblings must go: {done:?}"); } /// **A stored sibling vetoes the prune.** One child carries drawable content, so the /// parent cannot cover the set — dropping the other three would delete the map's /// answer for their ground (the reader would overzoom a parent that draws coarsely). #[test] fn a_stored_sibling_vetoes_the_prune() { use tilecodec::pmtiles::tile_id; let (px, py) = (1_200u64, 1_500u64); let z = 12u8; let mut done = vec![ empty_entry(tile_id(z, px * 2, py * 2)), stored_entry(tile_id(z, px * 2 + 1, py * 2)), empty_entry(tile_id(z, px * 2, py * 2 + 1)), empty_entry(tile_id(z, px * 2 + 1, py * 2 + 1)), ]; prune_barren_subtree(z, &mut done); assert_eq!(done.len(), 4, "a stored child keeps the whole set"); } /// **A partial set never prunes.** The parent split across a batch boundary keeps its /// children: the archive must not depend on where the cost-batcher cut, and three /// empties cannot prove the fourth is barren. #[test] fn a_partial_child_set_never_prunes() { use tilecodec::pmtiles::tile_id; let (px, py) = (1_200u64, 1_500u64); let z = 12u8; let mut done = vec![ empty_entry(tile_id(z, px * 2, py * 2)), empty_entry(tile_id(z, px * 2 + 1, py * 2)), empty_entry(tile_id(z, px * 2, py * 2 + 1)), ]; prune_barren_subtree(z, &mut done); assert_eq!(done.len(), 3, "a split parent keeps its children"); } /// **z0 never prunes.** The world tile has no parent to overzoom to; dropping it /// would delete the map's coarsest answer. #[test] fn the_world_tile_is_never_pruned() { use tilecodec::pmtiles::tile_id; let mut done = vec![ empty_entry(tile_id(0, 0, 0)), empty_entry(tile_id(0, 1, 0)), empty_entry(tile_id(0, 0, 1)), empty_entry(tile_id(0, 1, 1)), ]; let before = ids_of(&done); prune_barren_subtree(0, &mut done); assert_eq!(ids_of(&done), before, "z0 keeps everything"); } /// **Unrelated tiles are untouched.** A batch of four empties from different parents /// prunes nothing — the check is per-parent, not per-batch. #[test] fn empties_from_different_parents_do_not_prune() { use tilecodec::pmtiles::tile_id; let z = 12u8; let mut done = vec![ empty_entry(tile_id(z, 0, 0)), empty_entry(tile_id(z, 100, 100)), empty_entry(tile_id(z, 200, 200)), empty_entry(tile_id(z, 300, 300)), ]; prune_barren_subtree(z, &mut done); assert_eq!(done.len(), 4, "no parent has its full set here"); } }